Practising multiple pieces

Question: I'm currently beginning to study repetoire in preparation for my DipAbrsm piano diploma. In total I will be playing 4 pieces (Bach E minor Toccata, Beethoven Moonlight Sonata, Schubert Impromptu No. 3, Rachmaninoff Prelude in C# minor). As one can see this is quite a mixture, and I was wondering if anyone could give any advice on how to practice many pieces at once and maintain them.
Any comments appreciated.
Answer: That is tough.  I am not sure if advice from a guitarist will carry over to piano but...
I try to maintain a diverse repertoire on two instruments.  The approach depends on whether you are learning these pieces from scratch and working them up to performance level or just ironing out glitches but already know them.  And, how much time you have to get them up to par.
If I have a piece that is in muscle memory I can afford to not practice it for a while.  When I come back to it I need to polish it but that doesn't take long.  For me, if the pieces are new, I try to hit each one every day perhaps focusing on one section of each for a week, then the next section for a week, etc.  Where section is somewhat subjective, I try to slice the piece in a way that I can handle the practice of all time wise and there is a natural stopping point in each piece.  I did this for a set of classical guitar pieces where one was a set of Renaissance pieces that were mostly chord melody, a second was a solo by Haydn with very fast arpeggios, and the third a Spanish flamenco piece that was continuous tremolo.  These each required a completely different technique.  If I spent a month on the Haydn the others would sink, and similarly for any choice.  That required each to be touch every day (at the very least if was going to forego one I needed to hit basic exercises for the techniques highlighted in the piece).
For the renaissance set I found it easier to work through one line of each song together culminating in a complete set after a certain number of weeks/months, rather than attempt to master one then another.
Answer: At dip. level, you and your teacher should be addressing this. It's a personal thing, and while one may say practise all four simultaneously, another may say do one for a week/fortnight, then another, and so on. We all work differently, so it's impossible to give good advice that'll work for you.
With the exam maybe 12 months away, I'd be learning a big chunk of one piece, to the exclusion of the others. When I was happy with that, I'd put it on the back burner, and start the next. Obviously there's other stuff to learn, too. But in reality, given something to learn, I lock myself away until I can't play it wrongly (happily, very rarely nowadays do I have/need to do that...) but why should that work for anybody else?
Above all, I wouldn't advocate sitting down to a long (2hr+) session and play more than a couple - until a month or so before the exam, when all need to be played consecutively, as will be expected during the exam.
Answer: I could waffle on, but it's all going to boil down to the obvious advice: do some work on one of them then do some work on the next one. What else?
It MAY be that the well-known phenomenon of methodical practice only resulting in improved fluency after 'sleeping on it' also applies after working on other pieces.  But don't worry if it doesn't.

Practising multiple pieces


Creating A Script To Replicate A Table And Its Contents?

Question: I know you can create a script to replicate a table using:
right click table > script table as > create to > new query editor window
But how can I generate a script that contains a bunch of insert commands for each row in the table?
Table1
Id1, Row1
Id2, Row2
Id3, Row3

Insert into Table1 values(Row1);
Insert into Table1 values(Row2);
Insert into Table1 values(Row3);

Answer: I ended up doing this
right click database > Tasks > Generate Scripts ... > selected the tables > in the advanced options I set "Types of data to script" to "Schema and data"
Answer: Select
  'Insert into Table (
     IntField1
     StringField2
     Column3)
   values (' +
     IntField1 + ',' +
     + '''' + StringField2 + ''',' +
     Column2 + ')'  as InsertQuery
From Table

Something like this, just remember if your string contains a single quote you will need to make sure you replace it like this replace(stringfield, '''', '''''')
Comment: Also NULL values will reduce that string to nothing, might want to get the ISNULL in there too.
Answer: Assuming Row is an INT NOT NULL. You could write a SELECT statement that outputs SQL;
SELECT N'INSERT INTO Table1 VALUES (' + CAST(Row AS NVARCHAR(10)) + N');'
FROM Table1

Then output your results to text.
Answer: So this isnt super pretty cuz I kind of took one of my sp's and hacked it up for this. But basically this will take any table and print a series of insert statements into a table called tbl_text (which you would need to create)
The arguments are the table name and the table ID from sysobjects
--this is how you get the tbl_id
SELECT id FROM sysobjects WHERE type = 'U' AND name = 'tablename'

CREATE PROCEDURE dbo.sp_export_table
@tblhdr varchar(100),
@tblID varchar(100)
AS

SET NOCOUNT ON

IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
   DROP TABLE ##temptable
END

DECLARE @identity bit
DECLARE @typestmt nvarchar(100)
DECLARE @typeval int
DECLARE @rowstmt nvarchar(1000)
DECLARE @rowID varchar(50)
DECLARE @orderby nvarchar(100)
DECLARE @clmnstmt varchar(200)
DECLARE @clmnhdr varchar(50)
DECLARE @clmnstring varchar(1000)
DECLARE @valuestmt nvarchar(200)
DECLARE @valuestring nvarchar(3000)
DECLARE @value nvarchar(1000)
DECLARE @insertstmt varchar(1000)
DECLARE @params nvarchar(100)
DECLARE @param2 nvarchar(100)
SELECT @rowstmt = N'SELECT TOP 1 @inside_var = name FROM syscolumns WHERE id = ' + @tblID + ' ORDER BY colorder'
SELECT @params = N'@inside_var  NVARCHAR(1000) OUTPUT'
EXEC sp_executesql @rowstmt, @params, @inside_var = @orderby OUTPUT

SELECT @rowstmt = 'SELECT *, ROW_NUMBER() OVER (ORDER BY ' + @orderby + ') AS row INTO ##temptable FROM ' + @tblhdr
exec(@rowstmt)

IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
    DECLARE row_cursor CURSOR FOR
    SELECT row FROM ##temptable

    OPEN row_cursor

    FETCH NEXT FROM row_cursor
    INTO @rowID

    --if table has identity and has records write identity_insert on
    SET @identity = 0
    IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
    WHERE OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),
    'TableHasIdentity') = 1 AND TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME = @tblhdr) AND EXISTS(SELECT * FROM ##temptable)
    BEGIN
        SET @identity = 1
        INSERT INTO dbo.tbl_text VALUES('SET IDENTITY_INSERT dbo.' + @tblhdr + ' ON')
    END

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @clmnstmt = 'DECLARE column_cursor CURSOR FOR SELECT name FROM syscolumns WHERE id = ' + @tblID + ' ORDER BY colorder'
        exec(@clmnstmt)

        OPEN column_cursor

        FETCH NEXT FROM column_cursor
        INTO @clmnhdr

        SELECT @clmnstring = '('
        SELECT @valuestring = '('

        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF @clmnhdr <> 'row'
            BEGIN
                SELECT @clmnstring = @clmnstring + @clmnhdr + ','
                SELECT @valuestmt = N'SELECT @inside_var = ' + @clmnhdr + ' FROM ##temptable WHERE row = ' + @rowID
                EXEC sp_executesql @valuestmt, @params, @inside_var = @value OUTPUT

                SELECT @typestmt = N'SELECT @inside_var2 = xtype FROM syscolumns WHERE name = ''' + @clmnhdr + ''' AND id = ' + @tblID
                SELECT @param2 = N'@inside_var2 INT OUTPUT'
                EXEC sp_executesql @typestmt, @param2, @inside_var2 = @typeval OUTPUT

                IF @typeval NOT IN (48,52,56,59,60,62,104,108,122,127)
                BEGIN
                    SET @value = REPLACE(@value,'''','''''')
                    SET @value  = '''' + @value + ''''
                    SET @value = ISNULL(@value, '''''')
                END

                IF NOT (@typeval = 34)
                BEGIN
                    SELECT @valuestring = @valuestring + @value + ','
                END
                ELSE
                BEGIN
                    SELECT @valuestring = @valuestring + '''''' + ','
                END
            END

            FETCH NEXT FROM column_cursor
            INTO @clmnhdr

        END

        SET @clmnstring = LEFT(@clmnstring, LEN(@clmnstring) - 1)
        SET @valuestring = LEFT(@valuestring, LEN(@valuestring) - 1)

        INSERT INTO dbo.tbl_text VALUES('INSERT INTO dbo.' + @tblhdr + ' ' + @clmnstring + ') VALUES' + @valuestring + ')')

        FETCH NEXT FROM row_cursor
        INTO @rowID

        CLOSE column_cursor
        DEALLOCATE column_cursor

    END

    --if it wrote identity_insert on, turn it off
    IF (@identity = 1)
    BEGIN
            INSERT INTO dbo.tbl_text VALUES('SET IDENTITY_INSERT dbo.' + @tblhdr + ' OFF')
    END

    CLOSE row_cursor
    DEALLOCATE row_cursor
END

IF object_id('tempdb..##temptable') IS NOT NULL
BEGIN
    DROP TABLE ##temptable
END

GO

Answer: If you've got an account on SSC, you can use the script I published last year. It works without cursors an it enables custom filtering.
http://www.sqlservercentral.com/scripts/Script+Data/65998/
Hope this helps


Qual formato de cor deve ser usado nos parâmetros de range da função "cv2.inRange"?

Question: Eu quero criar uma máscara para a minha imagem com o OpenCV usando a função inRange, porém não sei qual o formato de cor utilizar. Na documentação só diz que a imagem (primeiro parâmetro) deve estar em HSV, porém não fala o formato das cores do range.
Eu encontrei um exemplo do uso dele nesse site, que define o seguinte range para a cor azul:
blue_lower = np.array([94, 80, 2], np.uint8)
blue_upper = np.array([120, 255, 255], np.uint8)
blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper)

O problema é que se o formato da cor for RBG, o blue_lower tem cor amarela e o blue_upper tem cor azul. Se o formato da cor for BGR, dá no mesmo só que fica invertido. E o formato certamente não deve ser HSV porque os dois últimos valores são maiores que 100%.
Disso isso, qual formato de cor eu devo usar? Se for mesmo BGR ou RGB, esse range para a cor azul está realmente correto?
Comment: Não manjo de OpenCV e muito menos de C++ mas no repositório do projeto tem [este teste](https://github.com/opencv/opencv/blob/68d15fc62edad980f1ffa15ee478438335f39cc3/modules/python/test/test_copytomask.py#L25) que usa BGR e [esse aqui](https://github.com/opencv/opencv/blob/68d15fc62edad980f1ffa15ee478438335f39cc3/samples/cpp/tutorial_code/video/meanshift/camshift.cpp#L51) também.. então suponho que dê pra assumir que o formato de cores é esse mesmo.
Comment: Estas duas respostas falam sobre isso: > Diferentes aplicações usam diferentes escalas para o HSV. Por exemplo gimp usa H = 0-360, S = 0-100 and V = 0-100. Mas OpenCV usa H: 0-179, S: 0-255, V: 0-255. 1- [Choosing the correct upper and lower HSV boundaries for color detection with `inRange` (OpenCV)](https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv/48367205#answers) 2- [How to detect two different colors using `cv2.inRange` in Python-OpenCV?](https://stackoverflow.com/questions/48109650/how-to-detect-two-different-color
Comment: Pessoal, vocês podem por favor me explicar o motivo de tantos negativos, tanto na pergunta quanto na resposta?
Comment: @LucasPedro obrigado pela a sua ajuda!
Comment: Jean, eu também não entendo o que acontece com o Stack em português. Então te dei um upvote pra dar uma moral.
Answer: O cv2.inRange() usa HSV (que já deve saber, é usado por ser mais próximo ao que os olhos humanos percebem) e se buscar na própria documentação:

https://docs.opencv.org/master/df/d9d/tutorial_py_colorspaces.html

Já teria a a explicação dos intervalos que a API usa:

For HSV, hue range is [0,179], saturation range is [0,255], and value range is [0,255]. Different software use different scales. So if you are comparing OpenCV values with them, you need to normalize these ranges.

Traduzindo:

Para HSV, o intervalo de matiz (hue/H) é [0,179], o intervalo de saturação (saturation/h) é [0,255] e o intervalo de valor (value/V) é [0,255]. Softwares diferentes usam escalas diferentes, então se você está comparando valores do OpenCV com eles, você precisará normalizar esses intervalos.

No entanto isso você vai usar se deseja fazer na "mão" (claro que depende do que você deseja fazer), mas o OpenCV tem funções para resolver isso, que pode encontrar o HSV para um valor BGR
green = np.uint8([[[0,255,0 ]]])
hsv_green = cv.cvtColor(green,cv.COLOR_BGR2HSV)
print( hsv_green ) # resulta em [[[ 60 255 255]]]

E para converter HSV para BGR ou RGB (range de 0 a 180):
cv::COLOR_HSV2BGR = 54,
cv::COLOR_HSV2RGB = 55,

Ou (range de 0 a 255, provavelmente para questões de converter imagens esse vai ser o seu caso):
cv::COLOR_HSV2BGR_FULL = 70,
cv::COLOR_HSV2RGB_FULL = 71,

Então, sim o OpenCV pode trabalhar com RGB, além do BGR, depende de olhar a documentação, tanto para entender os padrões, quanto outras situações, e como dito na nota acima, softwares diferentes usam escalas diferentes.
Answer: O formato de cor utilizado nos parâmetros lowerb e upperb é o HSV (Hue-Saturation-Value).
Assim como o Lucas Pedro comentou, e está escrito nessa resposta em inglês, o motivo dos valores SV ultrapassarem 100, valor esse que teoricamente deveria ser o limite, é que diferentes aplicações podem usar diferentes escalas para o sistema de cor HSV.
Por exemplo, o GIMP utiliza para a H um valor de zero à 360 e para S e V um valor entre zero e 100. No caso do OpenCV, o range dos componentes da cor HSV são as seguintes:
H (matriz)     |  0 - 179
S (saturação)  |  0 - 255
V (brilho)     |  0 - 255

E sim, os ranges das cores da pergunta estão corretas. Para verificar isso, basta converter a cor HSV do OpenCV para a cor HSV normal, como no código abaixo:
blue_upper = [120, 255, 255]
int(360 / 179 * blue_upper[0]) # H: 241       HSV Normal: (241, 100, 100)
int(100 / 255 * blue_upper[1]) # S: 100%      RGB: (4, 0, 255)
int(100 / 255 * blue_upper[2]) # V: 100%      Hexadecimal: 0400FF


Classification in real time without prior knowledge of the number of classes

Question: Is there an implemented algorithm (with python/R or java in preference) that can classify incoming data from an unknown generator with absolutely no prior knowledge or assumption.
For example:
Let G be a generator of 2d vectors that generate one vector in each second.
What we know, and nothing else, is that this vectors are separable into clusters in space (euclidean distance).
Question: How can I classify my data in real time so that at each iteration, the algorithm propose clusters?
Comment: Are you asking about [cluster analyses](http://en.wikipedia.org/wiki/Cluster_analysis)? To classify, you have to know what the classes are.
Comment: Thanks for the comment, I know about clustering, The problem here that I don't have the number of clusters.
Comment: So is it that you want to cluster data where you don't know the right number of clusters in advance?
Comment: @gung yes that's my problem
Comment: Current voting suggests this question may be too vague and too broad to be answerable. Perhaps you could edit the post to provide more information about the data and the purposes of the classification.
Comment: Thanks--it's getting clearer.  It could help further to explain what measure of distance or similarity you intend to use for the clustering. It's not always just Euclidean distance!  You should also indicate whether you want this clustering itself to be performed in real time ("online"), or whether you can cache all the data and perform the clustering procedure later. The two problems are different in some profound ways.
Comment: @whuber yes of course, thanks and sorry for the lack of clarity
Comment: Either you need to be more application specific or you are trying to screw a square peg in a round hole.
What do you mean by real time classification? Do you have latency constraints or you are refering to the classification of stream data?
If you have stream datasource are the observations evolving or do you work with differnt instances over time? (like a service)
Comment: @Ramalho I look for an answer for the simple case described above (geometric classification with euclidean distance )
Answer: DBSCAN seems to suit your purpose, it doesnt need a fixed number of clusters and will surely find correct clusters in the separable clusters case.
If instances where not random but actually drifting between time instances (like moving points) i would give incremental DBSCAN a try.
DBSCAN is available in either of the languages you mentioned.
Regarding the temporal "dimension" of the problem you accumulate instances and after a certain criteria is met (minimum number of instances, time window size) you cluster the accumulated observations and repeat.
Comment: The problem is that DBSCAN don't works with clusters with different density (it's a very strong assumption in my case)
Comment: It will work for the specific case of clusters being well separated. Tough if dbscan really doesn't work you may try OPTICS.


Find prime numbers in range

Question: def is_prime(number):
    for i in range(2, number):
        if number % 1 == 0 and number % i == 0:
            return False
        else:
            return True
print(is_prime(13))
print(is_prime(55)) #True ##Why ???
def prime_numbers(a, b):
    lst = []
    for i in range(a,b+1):
        if is_prime(i):
            lst.append(i)
    return lst

print(prime_numbers(50, 100))

This is my code and suppose I have prime_numbers(50, 100).
It should return [53, 59, 61, 67, 71, 73, 79, 83, 89, 97] instead of
[51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99].
So what is wrong with my code ?
Comment: Dont think number%1==0 is needed, it is always True. To make it more efficient only go upto square root of the number + 1 (1 added to make sure you go upto the next integer when sqrt returns a float)
Comment: This has already been answered below, but I'd just add that there's no point in iterating over the range `(2, number)`. You only need to go as far as half of `number` as any number greater than that cannot divide evenly into `number`. I'd probably also make sure that `number` is an integer otherwise the `range` is likely to throw an error.
Comment: possible duplicate of [isPrime Function for Python Language](http://stackoverflow.com/questions/15285534/isprime-function-for-python-language)
Comment: But you return `True` far to eagerly.
Answer: Relocate the return True line:
def is_prime(number):
    for i in range(2, number):
        if number % 1 == 0 and number % i == 0:
            return False

    return True

print(is_prime(13)) # True
print(is_prime(55)) # False

Your code isn't working because you return True or False during the first iteration.
Comment: then print(is_prime(13))  will be false as well
Comment: which should be True for this case
Comment: @user3419984 no, `is_prime(13)` is True

Find prime numbers in range


Which Lilypond engraver handles accent marks?

Question: In the following example (from my recent question, Globally removing engravers from LilyPond), I've managed to remove every engraver I need except for one: whichever engraver is responsible for the accent (>) on the bass clef's B.

What engraver do I remove to automatically get rid of such marks?
\version "2.20.0"
\language "english"

global = {
  \key e \minor
  \time 2/2
  \partial 4
}

right = \relative c' {
  \global
  e8_\mf r8 |
  g4 fs8 e ds4 e8 fs |
  b,4\( cs8 ds e4\)
}

left = \relative c {
  \global
  g8( fs |
  e4) a b4._> a8 |
  g4 fs e
}

\score {
  \new PianoStaff <<
    \new Staff = "upper" \right
    \new Staff = "lower" { \clef bass \left }
  >>
  \layout {
    \context {
      \Staff
        \remove "Time_signature_engraver"
    }
    \context {
      \Voice
        \remove "Stem_engraver"
        \remove "Rest_engraver"
        \remove "Phrasing_slur_engraver"
        \remove "Slur_engraver"
        \remove "Tie_engraver"
        \remove "Dynamic_engraver"
        \remove "Dots_engraver"
    }
  }
}

Answer: Extending on Ramillies part: Articulations are handled both by the Script_engraver as well as the New_fingering_engraver. These differ slightly in how they work. Script_engraver will listen to articulation type events, while the New_fingering_engraver does only acknowledge note heads and adds articulations from the articulations property of the cause.
Note that events handled by the Script_engraver will then be removed from this articulations property, as can be seen here.
#(define (eng context)
   (make-engraver
    (acknowledgers
     ((rhythmic-head-interface engraver grob srceng)
      (display (ly:event-property (ly:grob-property grob 'cause) 'articulations))
      (newline)))))

% prints empty list
\score {
  c->
  \layout {
    \context {
      \Voice
      \consists #eng
    }
  }
}

% prints list with articulation event
\score {
  c->
  \layout {
    \context {
      \Voice
      \consists #eng
      \remove Script_engraver
    }
  }
}

This means that usually articulations will be handled by the Script_engraver. If you remove that one they will instead be handled by the New_fingering_engraver. So you also need to remove that one.
Answer: That's actually an interesting question, and I've hit a bit of block here. But first of all, I would like to show you how to get this kind of info from the docs.
First we need to know what kind of object these articulations are. Often, the best way is to skim the basic docs (in this case, 1.3.1 "Expressive marks attached to notes"). After each section, there is a "see also" part that also has links to the internals reference. Here we can see that it links to Script and TextScript objects. So we inspect these pages, and it turns out that TextScript is the object that handles all the markups, while Script handles the articulations. So the articulations are Scripts.
Next, we can look at its internals reference page, and we see that it's drawn by Script_engraver. And looking at the Script_engraver's page in turn, we see that it's used by Voice (see the line "Script_engraver is a part of the following contexts:" at the bottom). So it looks like adding \remove "Script_engraver" should do the job.
However — it does not!! I'm sorry, but I have no idea why — perhaps someone else will be able to enlighten us both. However, nothing is lost, because you can put pretty much any kind of \overrides and related commands into the \context blocks as well. So if you add \omit Script into the second context block in your code, it will do what you want.
Comment: I swear I read that first page three or four times earlier today :-) But the next few steps were largely new to me, so thank you! I'll wait to see what others say, but your solution works great.
Comment: For reasons that are a little difficult to explain, you also need to remove `New_fingering_engraver` in addition to `Script_engraver`.
Comment: @ABOUSAMRAJean Hi Jean! Is there any reason why this is this way? As I understand the code any articulation type event or text script type event should be handled by `Script_engraver` and `Text_engraver`, without ever being touched by the `New_fingering_engraver` unless you remove one of these engravers. Do we have script-type events that are neither articulation-type nor text-script-type?
Comment: Hi Valentin. I guess you answered your own question in your answer? Or did I misunderstand the question?


Hook_menu_alter not working?

Question: <code>**
* Implements hook_menu().
*/

define('RATE_PATH_RESULTS_PAGE', 'node/%node/rating');

function rate_menu() {
  $menu = array();

   $menu[RATE_PATH_RESULTS_PAGE] = array(
     'title' => 'Voting results',
     'page callback' => 'rate_results_page',
     'page arguments' => array(1),
     'access callback' => 'rate_results_page_access',
     'access arguments' => array('view rate results page', 1),
     'type' => MENU_LOCAL_TASK,
     'weight' => 10,
    'file' => 'rate.results.inc',
);

  return $menu;
}
</code>
Above menu item comes from rate module, I want to override permission of this menu item. For now permissions are defined for user roles from permissions page. But according to my requirement I want this menu link visible to users on nodes only when user is author of node. Due to this I want to take control of this menu item in my custom module.
<code>function custom_menu_alter(&$menu){
  $menu[RATE_PATH_RESULTS_PAGE] = array(
    'title' => 'Voting results page',
 );

}
</code>
I am trying by writing above function for alter menu in my custom module. Please guid me with proper way, what I am doing wrong.
Thanks!
Comment: An empty alter function will never do anything, can you edit the actual code you're using into the question and describe what it's doing/not doing/what you expect it to do?
Comment: sorry I updated question now
Comment: I just tried by changing title but nothing changes and my previous working menu also disappear
Answer: You're overwriting the whole item with this:
<code>$menu[RATE_PATH_RESULTS_PAGE] = array(
  'title' => 'Voting results page',
);
</code>
Which clears out the page callback, access callback, and so on.
Instead, you want to replace the individual relevant components like this:
<code>$menu[RATE_PATH_RESULTS_PAGE]['title'] = 'Voting results page';
</code>
Comment: Thanks ! now in similar way I can change function to be used for access callback.

Hook_menu_alter not working?


How can I straighten a violin tailpiece (and do I need to)?

Question: My violin tailpiece is at a noticeable angle, as shown in the pictures below. I assume this is partly because the bridge is quite steeply-raked (which presumably can't be altered significantly, as the bridge matches the profile of the fingerboard).
Is this something that would usually be seen as a problem? Is there any simple remedy that I could try myself, such as changing or removing the adjusters?
Answer: This is not a problem since the tail piece is in equilibrium.  However, check your fine tuners regularly.  If they are close to the violin top, turn them out most of the way, coarse tune using the pegs, then adjust the fine tuners.
Answer: The angle the tailpiece takes depends on several factors- the shape of the bridge as you mentioned, the various tensions of the strings, the height and number of fine tuners, etc.  The only way to change the angle without changing the bridge or the strings is with the fine tuners: most violins are designed for having just one, so the tailpiece rides lower than planned if you have all four.
But actually, unless the tailpiece or a fine tuner is touching the belly of the violin, it's not a problem.  Check out your clearance: it should be at least a couple of millimeters or you're likely to put dings in the belly and of course not sound optimal.  As you suggest, the easiest thing would be to take off all the fine tuners except perhaps the E.


Entity Framework Core: manually changing RowVersion of entity has no effect on concurrency handling

Question: I'm having a problem with concurrency. When two users attempt to save the same record one after the other, EF allows them to do so.
My front end is Angular and on the backend I'm using EF Core 7 with a database-first approach.
When both users load the row, it contains a property called Rv (RowVersion) which is stored as a byte[] in the backend and ArrayBuffer in the frontend.
Backend in C#:
public partial class User
{
    public int Id { get; set; }
    public byte[] Rv { get; set; }
    ...
}

Frontend in Angular:
export interface User {
    id: number;
    Rv: ArrayBuffer;
    ...
}

When user A updates the row and clicks Save, the backend runs the following code:
Chrome DevTools Shows the following being sent in the Network tab for the RV: "AAAAAAAAEBE="
public async Task<ActionResult> Save(User dto)
{
    var entity = await context.Users.FindAsync(id);
    // Here entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,17

    mapper.Map(dto, entity); // Updates all properties on Entity using AutoMapper
    // Now entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,17

    await context.SaveChangesAsync();
    // SQL GENERATED: UPDATE [Users] SET LastName = 'ABC' WHERE [Id] = 22 AND [RV] = '0x0000000000001011'

    // Now entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,18
}

When user B updates the record and clicks Save, the backend runs the following code:
Chrome DevTools Shows the following being sent in the Network tab for the RV: "AAAAAAAAEBE="
public async Task<ActionResult> Save(User dto)
{
    var entity = await context.Users.FindAsync(id);
    // Here entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,18

    mapper.Map(dto, entity); // Updates all properties on Entity using AutoMapper
    // Now entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,17

    await context.SaveChangesAsync();
    // SQL GENERATED: UPDATE [Users] SET LastName = 'XYZ' WHERE [Id] = 22 AND [RV] = '0x0000000000001012'

    // Now entity's RowVersion = byte[8] = 0,0,0,0,0,0,16,19
}

When running DbScaffold to reverse engineer the database, the following Fluent config was added to DbContext:
entity.Property(e => e.Rv)
      .IsRequired()
      .IsRowVersion()
      .IsConcurrencyToken()
      .HasColumnName("RV");

I can see that AutoMapper correctly maps/changes the Rv property on the entity to that coming from the DTO (request), but it seems to have no effect on the GENERATED SQL as it does not reflect this change.
Is this the wrong approach to update the RowVersion prior to saving in Entity Framework Core?
Shouldn't EF Core detect during SaveChanges() that the RowVersion was changed and throw a concurrency exception?
Answer: EF Core Optimistic Concurrency documentation topic contains the following explanation:

In EF Core, optimistic concurrency is implemented by configuring a property as a concurrency token. The concurrency token is loaded and tracked when an entity is queried - just like any other property. Then, when an update or delete operation is performed during SaveChanges(), the value of the concurrency token on the database is compared against the original value read by EF Core.

The most important is that "the value of the concurrency token on the database is compared against the original value".
This explains the generated WHERE conditions you see. However, "when an entity is queried" and "read by EF Core" are not quite correct, because these are just some of the cases when the original value is updated.
EF Core change tracker tracks 2 values of a property - current and original. Current is basically what is the property value of the object. Original however is maintained purely inside the change tracker, and is updated with current after the entity is read from the database, or after successful update, or can be set manually.
Note that the original value must be compared to the database value and not the current value, because even if it was read from the database, it is snapshot at the time read query was executed, and the database could have changed after that.
With all that being said, it should be clear that you need to set the original value of the concurrency token property (row version in your case) which you send to and receive unmodified from the frontend.
AutoMapper cannot help in this scenario, because what it does is equivalent of the setting the current value manually. Also it has no access to the db context metadata/change tracker needed. Also has no way to know (same for EF Core itself) that the value inside the object must be treated as original, and all it can do eventually is to ignore it (as EF Core will since IsRowRomber implies ValueGeneratedOnAddOrUpdate).
You are the only one who has that information, so you have to provide it manually to EF Core. It can be done in a several ways, all  requiring access to the change tracker entry for the entity and invoked after setting regular properties and before 'SaveChanges`.
For instance
context.Entry(entity).OriginalValues.SetValues(new { entity.Rv });

or
context.Entry(entity).OriginalValues[nameof(entity.Rv)] = entity.Rv;

or (probably the most natural)
context.Entry(entity).Property(e => e.Rv).OriginalValue = entity.Rv;

or even (when the current value is already set to what is supposed to be the original)
var rv = context.Entry(entity).Property(e => e.Rv);
rv.OriginalValue = rv.CurrentValue;


How to load an RSA512 public key and exponent from a .bin file into python

Question: I'm having trouble loading an RSA512 public key from a .bin file into python. The issue mainly stems from the fact that I don't know what format the key is stored in. This is the only description of the file I was given.
"key.bin - Raw binary bytes of RSA 512 bit public key and exponent. Used to verify signature of incoming
packets."
I don't know if this is helpful but here are bytes printed in python of the .bin file.
9902c4a66b1ff76392919e7bbc35d51a5128b9da03e131b489d5ed01c1d075fc4c139a9952e9a3b040d984219a4aef0d421f6b8f9c79e1c3c35a218ecba54dc9010001
The goal of the actual challenge is to build a udp server that verifies the digital signature and integrity of an incoming packet. Currently i'm using python 2.7 with the cryptography library. Documentation can be found below.
https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/?highlight=rsa%20512
I have already tried the code below but I get the same error for the first two formats and a slightly different one for the third.
with open("key.bin", "rb") as key_file:
    private_key = serialization.load_der_public_key(key_file.read(), backend=default_backend())

ValueError: Could not deserialize key data.

with open("key.bin", "rb") as key_file:
    private_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend())

ValueError: Could not deserialize key data.

with open("key.bin", "rb") as key_file:
    private_key = serialization.load_ssh_public_key(key_file.read(), backend=default_backend())

ValueError: Key is not in the proper format or contains extra data.

Also the hashing algorithm used for verification is SHA256 but that is probably irrelevant.
Comment: Consider `pycryptodomex` https://pypi.org/project/pycryptodomex/
Answer: Your key is not encoded in a known standard. You need to extract the modulus and exponent, and then build the public key out of them.
The modulus defines the RSA key size and is therefore 512 bits or 64 bytes as unsigned big endian value. The public exponent may have any size, but is usually small. The most used exponent value is 010001 in hexadecimals, which is the fifth prime of Fermat (also called F4, zero based index). Better however to simply get the first 64 bytes and assume the rest encodes is the public exponent.
So you can use RSAPublicNumbers to create the values from the modulus n and exponent e. Trick is to make sure that you create the modulus as positive value instead of a negative value.

Let's say that data is the binary data read from the file. Then you can get the public key in the following way.
You may want to use 'little' instead of 'big' if the following doesn't work (big endian is the RSA default, but you never know). However, in your case the little endian value is dividable by e.g. 11, so that's not a likely modulus value (the prime values should be close to half the key size in bits to be secure).
modsize = 512 // 8

modBytes = data[slice(0, modsize)]
mod = int.from_bytes(modBytes, byteorder='big')

expBytes = data[slice(modsize, None)]
exp = int.from_bytes(expBytes, byteorder='big')

pubkey = RSAPublicNumbers(exp, mod).public_key(default_backend())

Note that from_bytes has only been added in Python 3.2. RSAPublicNumbers is a bit weird in the sense that it takes the exponent parameter before the modulus. Every other API that I've seen takes the modulus before the exponent.
Answer:
key.bin - Raw binary bytes of RSA 512 bit public key and exponent. Used to verify signature of incoming packets.

In a RSA-512 key, the modulus is a 512-bit number, which fits in 64 bytes or 128 hexadecimal digits. Your file is represented by 134 hex digits, so it's likely that 128 of these digits are the modulus and the rest is the public exponent and possibly metadata.
The public exponent is almost always 3 or 65537=0x010001. Given that key.bin ends with 010001 in hex, a reasonable guess is that those last 3 bytes are the public exponent, and the first 64 bytes are the modulus.
with open("key.bin", "rb") as key_file:
    n_bytes = key_file.read(64)
    e_bytes = key_file.read(3)

You now need to figure out whether the encoding is little-endian or big-endian. You can't tell from the public exponent because it's palindromic. So try both possibilities:
n = int(n_bytes.encode('hex'), 16)

or
n = int(reversed(n_bytes).encode('hex'), 16)

Since you have the key in an ad hoc format, rather than a standard format that is used in real life, you're probably meant to use arithmetic primitives rather than a cryptography library to work with the key.
Comment: You can use `from_bytes` instead of the hex. That function also helpfully takes a byte order parameter. Of course, your `key_file.read()` is a bit better than my slicing, on the other hand :)


Extrair apenas o nome de um arquivo a partir do caminho completo

Question: Quero fazer um shell script que receba um nome de arquivo com seu caminho completo, por exemplo /home/42/arquivoEscolhido.txt, e extraia apenas o nome do arquivo (arquivoEscolhido.txt), que no caso seria tudo após a última barra (/), levando em conta que o nome do arquivo sempre pode mudar.
Cheguei em algo parecido com isso mas não deu certo:
echo -n 'Informe o arquivo: '

read dir       #/home/42/teste.txt

arq=${dir#*/}

Answer: Só faltou um #: arq=${dir##*/} vai ser teste.txt
${var#padrão}  vai remover só até a primeira ocorrência do padrão.
${var##padrão}  vai remover até a última ocorrência do padrão.
Comment: Muito obrigado! It works!!
Answer: Como se trata do caminho de um arquivo, outra opção é usar o comando basename:
basename /home/42/teste.txt

A saída é:
teste.txt

Dentro de um script, basta executar o comando com a sintaxe de command substitution, colocando-o entre $( ):
echo -n 'Informe o arquivo: '

read dir       #/home/42/teste.txt

# executa o comando basename, a saída é colocada na variável arq
arq=$(basename $dir)

Assim, se o caminho do arquivo for /home/42/teste.txt, a variável arq terá o valor teste.txt.

Bônus
Segundo a documentação:

strip directory and suffix from filenames

Em tradução livre:

remove o diretório e o sufixo de nomes de arquivos

Ou seja, também pode-se passar como parâmetro o sufixo a ser retirado. Com isso, também é possível remover a extensão do arquivo, por exemplo:
basename /home/42/teste.txt .txt

Saída:
teste


What is the largest prime number?

Question: I want to know, what is the largest prime number? I know prime numbers are whole numbers that cannot be divided by any whole number except 1 and themselves, I also know some primes  like 2, 3, 5, 7, 11... But what is the largest prime number?
Comment: [There isn't one](http://en.wikipedia.org/wiki/Euclid%27s_theorem).
Comment: You'll find that assuming there is a biggest anything is a bad idea in math.
Comment: I saw at least 4 upvotes for this question at one point. Does anyone care to elaborate why they think this question deserves to be upvoted?
Comment: @user2566092: On SO we have come to the conclusion that these kinds of upvotes are from the same kinds of users that would also ask this kinds of questions. They simply think "oh, I always wanted to know that too"
Comment: Exact duplicate of: [Is there possibly a largest prime number?](http://math.stackexchange.com/questions/201/is-there-possibly-a-largest-prime-number).
Answer: There is no largest prime number, since there are infinitely many prime numbers as proved by Euclid back to 300BC. However, there is a largest known prime which is: $$2^{57885161}-1
$$ as of January 2014, discovered by the GIMPS project. You can even help find a new one, by following the simple steps described here and letting your computer do the job.
Answer: When you try to catch the latest prime number:
(づ。◕‿‿◕。)づ $\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ 53$

Another one appears behind you

$59 \ \ \ \ \ \ \ \ \ \ \ \ $ (づ。◕‿‿◕。)づ $\ \ \ \ \ \ \ \ \ \ \ \ 53$
They're infinite!
Euler proved it with the zeta function:
$$\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s} = \prod_{p}^\infty \frac{1}{(1-\frac{1}{p^s})}\tag{$p$ is a prime}$$
Comment: The zeta function is a bit of an overkill....
Comment: Haha made me smile :)
Comment: @Prism thanks, that was the intention :)
Answer: I would like to provide a little more detail and offer the proof for the infinitude of the primes. Suppose that there was a last prime number. If we numbered the primes, we'd have $p_1$, $p_2$ and so on until the last one which we'll call $p_k$.
We now consider the product of all of these prime numbers plus 1. $n=p_1p_2p_3\cdots p_k+1$. To check to see if a number is prime, it suffices to divide by all prime numbers smaller than it, so if we divide out any of the primes, maybe $p_i$ for all $i$ between $1$ and $k$, we would have then ${p_1p_2\cdots p_{i-1}p_ip_{i+1}\cdots p_k$+1} \over p_{i}$. We could simplify this term then to include a product of primes on the left, cancelling out $p_i$, but then we would still have the last term $1\over{p_i}$, which is not an integer since $p_i$ is greater than 1. But that means that $n$ was not divisible by $p_i$. Since $i$ was any arbitrary positive integer less than or equal to $k$, $n$ is not divisible by any of the primes smaller than itself, so $n$ too is prime, contradicting the idea of a last prime.
So we conclude their are infinitely many primes.
Comment: This isn't the best way to do it.  Instead of assuming in advance that there are only finitely many, just say you have some finite set of primes, for example $\{2,7,43,101\}$.  Show that if you multiply them and add $1$, then the prime factors of the resulting number are not within the finite set you started with.  Thus every  finite set of primes can be extended to a larger finite set of primes.  There are disadvantages of rearranging this argument into a proof by contradiction.
Comment: Euclid's proof is indeed that described by my comment above. It can be rearranged into a proof by contradiction, and many authors do that, and many, even respectable ones, including no less than Dirichlet, assert falsely that that is what Euclid did. Among the disadvantages of doing that are that some authors then write that since $1+\prod S$ is not divisible by any primes in the finite set $S$, which was assumed to be the set of all primes, it follows that that number is not divisible by any primes, and therefore prime itself. It is then mistakenly thought by some that [.....]
Comment: ...that it was proved that $1+\prod S$, where $S$ is the set of the first $n$ primes, it always prime itself.  But that is false: in many cases it is composite, in particular when $n=6$, since $30031=59\times509$. Only the assumption that a certain set contains all primes makes anyone say that if a number is not divisible by any primes in that set, then it is not divisible by any primes. And only that conclusion makes anyone conclude that it is therefore prime itself. Among the consequences are (1) an erroneous proposal to prove the twin-prime conjecture by.....
Comment: looking at $\pm1+\prod S$, where $S$ is the set of the first $n$ primes, and saying those two numbers are twin primes; (2) noticing that there are many counterexamples to the primality of $1+\prod S$, where $S$ is the set of the first $n$ primes, and falsely concluding that therefore Euclid's proof is simply mistaken; (3) mistakenly thinking Euclid's proof is non-constructive since it proves existence by contradiction.
Comment: This is pretty much Euclid's proof, as I understand it. Can you share some of the disadvantages of using a contradiction? To me it looks the same, but I'd love to hear your reasoning.
Comment: Catherine Woodgold and I wrote a joint paper on this, which was published in the Fall 2009 issue of the _Mathematical Intelligencer_.  It is titled "Prime Simplicity".
Answer: The largest prime we know till now, is $2^{57885161}-1$
source: http://en.m.wikipedia.org/wiki/Largest_known_prime_number
There is no biggest prime. Its just that we currently don't know what is the next biggest prime, but there is one!
Comment: It would be prettyy important to note that there's no largest prime number, only that prime number is the largest we currently know of.
Comment: That's a strange numbering system you're using! Does it mean the same as $2^{57885161}$? If not, you will have to argue it out with حكيم الفيلسوف الضائع.
Comment: That was a mistake, edited!
Comment: Yup, I agree @Darksonn
Comment: Yes, it mean the same @TonyK

What is the largest prime number?


What are the minimum requirements for a custom Drupal 8 theme that can be enabled

Question: I'm testing creating new themes in Drupal 8 and I'd like to know the very minimum it takes to create one that can be enabled. I'm not worried about any actual styling yet.
I've created a theme folder in themes called uktheme and I currently have a uktheme.info.yml file in that folder.
the contents of that file are
name: UK Theme
type: theme
description: 'Test theme'
package: Core

regions:
  header: Header
  primary_menu: 'Primary Menu'
  feature: 'Feature'
  content: 'Content'
  page_bottom: 'Page Bottom'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'

However I receive
The website encountered an unexpected error. Please try again later.

when attempting to go into the appearance settings. I do not believe it's my folder structure and location because I successfully created another theme copying the content of Bartik.
Answer: Perhaps you've missed core.
Required params in *.info.yml are:
name
description
type
core
regions:content
Also you can check your *.info.yml for using tabs instead of spaces:

Tabs are NOT allowed, use spaces ONLY.
  You MUST indent your properties
  and lists with 1 or more spaces.

See more in official docs: https://www.drupal.org/theme-guide/8/defining-a-theme
Answer: There is a space in your name, that should be wrapped in quotes: name: 'UK Theme'. That space could be causing an error as it produces invalid code.
And also I am pretty sure your theme does not ship with core ;)
Comment: Hmm, it seems spaces are allowed in YAML (I always thought it was more JSON like). This probably does not solve the issue...


Aguardar a consulta ao banco para dar retorno

Question: Estou fazendo uma consulta ao banco SQLite.
Porém a função acaba dando retorno antes da consulta ser realizada.
Estou tentando solucionar isso utilizando um tipo de controle enquanto a consulta não prossegue. Tem alguma forma de resolver essa questão?
Meu código está abaixo:
model.executarSql = function (sSql) {
   var bExec = false; // Controle se pode prosseguir ou não

   db.transaction(function(tx){
      tx.executeSql(sSql, [], function(txs, results){
         var aRet  = []; // Array bidimensional com todos os resultados
         var aItem = []; // Array com um resultado por vez

         for(it = 0; it < results.rows.length; it++){
            while (aItem.length > 0){ aItem.pop() }; // limpar o array

            for(cp = 0; cp < results.rows.item(it).length; cp++){
               aItem.push(results.rows.item(it)[cp]);
            }

            aRet.push(aItem);
         }

         bExec = true;
      });
   });

   while (!bExec){
      // Aguardar a consulta ao banco
   };

   return aRet;
};

Comment: Rodrigo, o Javascript trabalha de forma assíncrona. Sugiro que você de uma olhada em `callback` e `Promise`. Tive o mesmo problema no entendimento [await](https://pt.stackoverflow.com/questions/379766/await-n%C3%A3o-aguarda-execu%C3%A7%C3%A3o-da-promise-resolvido) [Callback](https://pt.stackoverflow.com/questions/27177/o-que-%C3%A9-callback)
Answer: Amigo, sugiro você usar uma estratégia de promises do javascript.
Porque ai o dado vindo do banco virá dentro da resolução da sua promise e nesse contexto você irá utilizar o dado ou manipula-lo.
function consultaBanco (msg, who, timeout) {
return new Promise((resolve, reject) => {
    resolve("Executa a sua consulta")
})
}
consultaBanco().then((resultaDaConsulta) =>
 "Aqui você você tem garantia que seu dado existira antes de manipular"
).catch((msg) => {
"Aqui é você terá o objeto de error caso aconteça"})

Espero que tenha ajudado. Boa sorte.


Triangle inequalities, with angle bisector

Question: I came across this question while I was taking one of the pratice Mu Alpha Theta tests for my school and I wasn't sure how to solve it. It reads:
In $\Delta USA $, $\angle S$ is bisected by $\overrightarrow {SY}$, with $Y$ on side $\overline {UA}$. If all sides have integer values, $ \overline{US}=18 $ and $ \overline{UY} = 12 $; find the smallest possible perimeter of $\Delta USA$.
The answer key with the solutions skipped to the part with the triangle inequalities, so that is why I am not sure what to do. I think there is some ratio when it comes to splitting a triangle with an angle bisector but I am not sure what it is. My question is how would I solve this question, and for future reference what is that ratio for an angle bisector in a triangle.
Answer: Hint: The relevant theorem about angle bisectors (adapted to your labels) is
$$\frac{AY}{YU}=\frac{SA}{SU}.$$
Comment: Oh then you could, find the lengths, and then using The Triangle Inequality find what the shortest possible lengths could be. Thank You!


Converting base 6 to decimal and vice versa in Python?

Question: I'm trying to convert a number from decimal to base 6 and vice versa, but it's not working. It seems that I'm not figuring out the algorithm to get it to work. Could someone please explain to me how to implement it in Python?
Here is a link(Click here) which gives an explanation on how to do it, but when I try to make it in Python using a while loop, but it's not working and turning out to be an infinite loop. And finally, I don't understand how I will append all the remainders together to form the final value.
Thanks
Answer: i hope this will help you more
def dec2hex(num):
    if num == 0:
        return 0
    ans = ""
    while num > 0:
        ans = str(num%6) + ans
        num /= 6
    return int(ans)

def hex2dec(num):
    if num == 0:
        return 0
    num = str(num)
    ans = int(num[0])
    for i in num[1:]:
        ans *= 6
        ans += int(i)
    return ans

if __name__ == '__main__':
    a = dec2hex(78)
    b = hex2dec(a)
    print a, b

the output is:
210 78

Comment: I wouldn't use the name `hex` for that - normally you think of base 16 then.
Answer: One direction is clear:
>>> int('42', 6)
26

The other way - convert a number to a base 6 representation - is trickier. There seems to be no way to do it with built-in functions and without a loop.
So one could do something like
def str_base(val, base):
    res = ''
    while val > 0:
        res = str(val % base) + res
        # val /= base # only valid for Py2
        val //= base # for getting integer division
    if res: return res
    return '0'

This gives e.g.:
>>> str_base(7,6)
'11'

Till now, it only works with bases <= 10; for the others you'd need to define an alphabet string:
import string
alphabet = string.digits + string.ascii_lowercase

and use it in the function like
res = alphabet[val % base] + res

It (probably) still doesn't work with negative numbers. If you need these, you have to add another bit of effort.
Comment: -glglgl  I get this when tryin 7,6 in the str_base function:
it's too long but it goes like that: 1.5e-3238e-3234.9e-3222.945 ...


Try Again Do-While Loop

Question: It is a very simple program. The computer and user chooses a number between 0-3. I want the program to loop back if the user does not guess the same number as the computer.
    String input; // input is a string variable
    int cpucrazy;
    int convertstring;

// First Step //
    input = JOptionPane.showInputDialog("Guess a number between 0-3");
    convertstring = Integer.parseInt(input);

// Random section //
    Random ran = new Random ();
    cpucrazy = ran.nextInt(3);

// computation!
if (cpucrazy < convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }

else if (cpucrazy > convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }

else JOptionPane.showMessageDialog(null, "Correct!!");

Comment: You'll want to pick your random number _before_ asking for input, then ask for input, do your comparisons, and show your message dialog all within a `do { ... } while (convertstring != cpucrazy)` loop
Comment: Please elaborate on the problem that you faced.
Comment: The do-while loop did work as you mentioned. However, the computer changes the number when it loops. I want the computer to remember the number and allow the user to keep guessing.
Comment: @ninjacoder Look at my answer. You will see that to avoid the computer from picking a new number you have it pick a number *before* entering the loop. Inside the loop you only get input from the user and compare the two numbers.
Answer: if (cpucrazy < convertstring) {
 JOptionPane.showInputDialog(null, "Your guess is too high. Guess again?"); }

else if (cpucrazy > convertstring) {
     JOptionPane.showInputDialog(null, "Your guess is too low. Guess again?"); }

else JOptionPane.showMessageDialog(null, "Correct!!");

You need to put a while loop ( or some type of looping construct ) around the above code and exit the construct when: cpucrazy == convertstring or stay in the loop construct while cpucrazy != convertstring
The loop could look like the following pseudo-code:
b = random();

do
{
     input a;
     if( a != b )
     {
         if(a < b )
         {
              print "Too low";
         }
         else
         {
              print "Too high";
         }
     }
} while( a != b );

print "You got it correct"

Comment: @ninjacoder If my answer helped you, please 'accept' my answer. Glad to have been of help.

Try Again Do-While Loop


Evaluating $\lim\limits_{n\to\infty}\frac{n^{n^{1/n}}}{e^{n(n^{1/n}-1)}}$

Question:
Evaluate $L=\lim\limits_{n\to\infty}\frac{n^{n^{1/n}}}{e^{n(n^{1/n}-1)}}$.

My try: The numerator can be written as: $e^{n^{1/n}\ln n}$, so we get:
$$L=\lim_{n\to\infty}e^{\lim_{n \to \infty}(n^{1/n}\ln n-n(n^{1/n}-1))}$$
Now its enough to find the limit in power as:
$$P=\lim_{n \to \infty}n^{\frac{1}{n}}\:\ln n-n(n^{\frac{1}{n}}-1)$$
Letting $n=\frac{1}{y}$ we get:
$$P=\lim_{y \to 0}\frac{-y\ln y-1+y^{\frac{1}{y}}}{y^{1+\frac{1}{y}}}$$
Which is in $0/0$ form
Using L'Hopital's Rule its too complicated. any way to solve?
Answer: You should have$$P=\lim_{y\to0^+}p(y),\,p(y):=\frac{-y\ln y-1+y^{y}}{y^{1+y}}.$$As $y\to0^+$, $y\ln y\to0$ and $y^y=\exp(y\ln y)=1+y\ln y+\frac12y^2\ln^2y+o(y^2\ln^2y)$, so the numerator $\sim\frac12y^2\ln^2y$ and $p\sim\frac12y^{1-y}\ln^2y$. Since $y^\epsilon\ln y=\frac{1}{\epsilon}y^\epsilon\ln(y^\epsilon)\in o(1)$ for all $\epsilon>0$, $P=0$ so $L=1$.
Answer: $$
n^{1/n}=\exp\left(\frac1n\log n\right)
$$
Now
$$
\xi(n):=\frac1n\log n\to0,\;\;n\to+\infty
$$
and
$$
e^{\xi}-1=\xi+o(\xi),\;\;\xi\to0
$$
thus
$$
n(n^{1/n}-1)=n\left(\xi(n)+o(\xi(n))\right)=\log n+\underbrace{no(1/n\log n)}_{\to0}\to+\infty
$$
as $n\to+\infty$.
Thus your denominator goes as $n$, likewise your numerator. Your limit is 1.
Comment: I'm unsure about your last step. I agree that $\frac{e^\xi-\xi-1}{\xi}\to 0$ which is the same as $\frac{n(n^{1/n}-1)-\log n}{\log n}\to 0$. I don't see how it follows that $n(n^{1/n}-1)-\log n\to 0$ from there, which we want for the denominator to be $\sim n$. What am I missing?
Comment: The denominator is $e^{n(n^{1/n}-1)}=e^{\log n + o(1/n\log n)}\sim n$ as $n\to+\infty$.
Comment: Sorry, but it doesn't seem that you read my comment. I asked you where does it follow from that $n(n^{1/n}-1) = \log n + o(1/n\log n)$? What you wrote looks like you are using $no(f(n)) = o(f(n))$, which is not true.
Comment: You're right. I just took care of the fact the second summand would have vanished. I edited


No Persistence provider for EntityManager named persistence

Question: Hello I need help to solve this problem. When trying to run my java web application on intellij i get the following message:

javax.persistence.PersistenceException: No Persistence provider for
  EntityManager named persistence

-- src
|-- main
|   |-- java
|   |   `-- service
|   |     `-- dao
|   |         `-- mapping
|   |             |--
|   |             |--
|   |             `--
|   `-- resources
|       `-- META-INF
|           `-- persistence.xml

here is my persistence.xml file in resources/META-INF/
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0">
<persistence-unit name="persistence">
       <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <mapping-file>Dao/mapping/user.xml</mapping-file>
    <class>Dao.mapping.UserEntity</class>
    <properties>
        <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
    <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/test"/>
    <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
    <property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>

my gradle build
group 'com.test'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.5

repositories {
mavenCentral()
}

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile group: 'org.hibernate', name: 'hibernate-core', version:          '5.2.4.Final'
compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.5'
compile group: 'org.apache.tomcat', name: 'tomcat-catalina', version: '9.0.0.M13'

compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.3.3.Final'
compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.1-api', version: '1.0.0.Final-redhat-1'

}

thank you .
Comment: You need to add org.hibernate:hibernate-entitymanager to your dependencies.
Answer: One option is that the error is caused by the referenced entity not existing.
You have "Dao.mapping.UserEntity" in the persistence.xml, but the directory suggests it should be "service.dao.mapping.UserEntity".
A complete stacktrace could help solve the problem.


boto3 equivalent to boto.utils.get_instance_metadata()?

Question: In regular boto 2.38 I used to access instance metadata (e.g. get current stack-name), through boto's
boto.utils.get_instance_metadata()

Is there an equivalent in boto3, or do I need to go to the down level direct http address to fetch metadata about the running instance?
Answer: Nope, still no equivalent in boto3, just hit this  gap myself.
They have an open  feature request for this https://github.com/boto/boto3/issues/313 that references this question.
As for workarounds,
you can  continue to use boto.utils or use urllib/urllib2 to do the HTTP requests manually ie.
# Python2
import urllib2
instanceid = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()

# Python3
import urllib.request
instanceid = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode()

see What is the quickest way to HTTP GET in Python? for a quick intro on urllib and http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-data-categories for the URI structure of the metadata service.
Comment: is this *still* true?! siiiiiiigh
Comment: @dwanderson Unfortunately Yes !
Comment: Additionally you can use the  adamchainz/ec2-metadata package. It would have to be pip installed so is perhaps not ideal for Lambda but this package is simple to use.
Answer: You could use the third-party library ec2-metadata.
Here an example from the docs showing how to get your EC2 region:
  pip install ec2-metadata

  >>> from ec2_metadata import ec2_metadata
  >>> print(ec2_metadata.region)
  us-east-1

Answer: You can fetch specific metadata from the the IMDSFetcher in botocore:
from botocore.utils import IMDSFetcher

IMDSFetcher()._get_request("/latest/meta-data/instance-type", None).text

This will also work on instances where IMDSv2 is enforced.
Comment: This does not work fir IMDSv2 enforced enviroments. as a third argument `token=IMDSFetcher()._fetch_metadata_token()` must be given.

otherwise this is the only valid answer to the origin question!


UINavigationBar Background Color Animation

Question: I am trying to implement Apple's detail screen from their Podcast, Music, and App Store Apps. The navigation bar starts off transparent then increases the alpha the further down you scroll.
I have the desired effect working changing the alpha value of the navigationBar itself. However, this also affects the buttons within the navigationBar.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    var offset = scrollView.contentOffset.y / 350
    if offset > 1 {
        offset = 1
        self.navigationController?.navigationBar.alpha = offset
        self.navigationItem.setHidesBackButton(false, animated: false)
    } else {
        self.navigationController?.navigationBar.alpha = offset
        self.navigationItem.setHidesBackButton(true, animated: false)
    }
}

I believe I need to change either

The Navigation Bar's backgroundColor
The Navigation Bar's barTintColor

Upon implementing each of these and replacing:
self.navigationController?.navigationBar.alpha = offset

with
self.navigationController?.navigationBar.barTintColor = Color.background?.withAlphaComponent(offset)

or
self.navigationController?.navigationBar.backgroundColor = Color.background?.withAlphaComponent(offset)

The animation does not transition, it simply goes from transparent to opaque.
I am setting up my Navigation Bar on this controller using iOS 13 methods
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
self.navigationController?.navigationBar.standardAppearance = appearance

Answer: To achieve the desired effect of a smoothly transitioning navigation bar while maintaining button visibility, you might consider using a combination of alpha adjustments for the background and manipulating the button's visibility separately.
Here's a suggestion:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offset = scrollView.contentOffset.y / 350

    if offset > 1 {
        updateNavigationBar(withAlpha: 1)
        self.navigationItem.setHidesBackButton(false, animated: true)
    } else {
        updateNavigationBar(withAlpha: offset)
        self.navigationItem.setHidesBackButton(true, animated: true)
    }
}

func updateNavigationBar(withAlpha alpha: CGFloat) {
    let backgroundColor = Color.background?.withAlphaComponent(alpha)

    // Update background with a fade animation
    UIView.animate(withDuration: 0.3) {
        self.navigationController?.navigationBar.backgroundColor = backgroundColor
    }

    // Update only the background alpha without affecting the buttons
    self.navigationController?.navigationBar.alpha = alpha
}

This separates the handling of background transparency (with a fade animation for a smoother transition) from the adjustment of the navigation bar's alpha to maintain button visibility. Adjust the duration of the animation (animate(withDuration: 0.3)) as needed for the desired effect.


Can animated visualizations help to understand music better?

Question: There are lots of animated visualizations (of a specific kind) of performed music around that I would like to understand better:

How accurate are they?

Do they help to understand music better? If so: how and why?

Or are they some kind of hoax and misleading?

The above mentioned "specific kind" is: To visualize the flow of music along a time line which a "camera" follows - similar to standard notation.
Based on standard notation

https://www.youtube.com/playlist?list=PL1B7060F21E6C1D51
Inspired by standard notation

https://www.musanim.com/watch_mam.html
Free style

Especially with respect to the (admittedly very impressive) free style examples (based on Line Rider) some questions came to my mind:

How accurate are they?

Couldn't there be completely different pieces of music with rather similar visualizations?

Or the same piece of music with completely different visualizations?

Are there possibly (Line Rider) examples around

of the same piece of music but visualized completely differently?

of the same visualization but of completely different pieces of music?

To condense this post into one question:

Is there evidence that animated visualizations of music can help to
understand music better?
Comment: The phrase "understand music better" is undefinable, I fear.
Comment: Try whatever re-wording you like, just keep in mind "is it objectively answerable?" BTW, I voted to re-open. I thought the question was clear enough, but other members probably want more objectivity.
Comment: @CarlWitthoft: I agree. This is a main drawback of my question. Could you be of help to improve the question, assuming that there is some sense in it?
Comment: @Hans-PeterStricker - It's your question.  Could you use the comment box to riff on what you are curious about, what you'd like to understand better, and most importantly, *why*?  What led you to be interested in this?  Are you focused on *learning tools*, by any chance?  And if so, who is the target audience, what is their level, what do they want to get out of it?
Comment: @aparente001: Good (because specific) questions! I'll try to answer them. So much for now: It's not about learning tools, it's more about giving new insights for those who are already learned.
Comment: @aparente001: To answer your question "why?" Because there is a lot in music that even learned musicians don't understand.
Comment: @Hans-PeterStricker. The problem is with "understand." Clarify what you mean. Understand what? Harmony? Rhythm? How to sight read, how to analyze?
Comment: Better than what?
Comment: @MichaelCurtis: Let me try to put it this way: To understand (better) how music affects our minds - both cognitively and emotionally and maybe synesthetically.
Comment: Personally i think it's sometimes good to leave a question open to enough interpretation to allow answers from different perspectives. Voted to reopen.
Answer: I'm not an academic musicologist but I really cannot see this kind of sound-to-light generation being remotely useful in replacing standard notation to transmit, store, or analyse music in the way you suggest.
Unless an agreed standard is reached where colours and positions can be agreed to represent notes, durations and rhythms, these will always be an on-screen visual accompaniment to the music, a kind of YouTube son-et-lumiere show; maybe nice to look at as you're listening, but no more meaningful than the light show at a rock concert.
And of course if there was an agreed standard of colours and position to pitch etc., it will still be a long way short of conveying information in the density that standard notation does.
Answer: (Bunus video link at the bottom)
Q: How accurate are they?
A: Some of them (e.g. some MIDI-to-colored-lines) can be pretty accurate in terms of pitch and duration, many others are mostly an artist's impression. (Like the line rider)
Q: Couldn't there be completely different pieces of music with rather similar visualizations?
A: Yes, if the visualization principle is a simplification. E.g. if the visualization principle is that music going higher is visualized by a line going higher, and vice-versa, there can be many different melodies with a similar pattern of ascending and descending intervals, which will result in similar animation, but will be based on totally different actual notes and intervals.
Q: Or the same piece of music with completely different visualizations?
A: Of course, because one can invent infinite different ways of visualizing any value (e.g. pitch) that changes in time.
Q: Are there possibly (Line Rider) examples around of the same piece of music but visualized completely differently?
A: If different people decide to visualize the same music it's virtually guaranteed they will come up with different visualizations. Just like different human civilizations will independently come up with different looking scripts and alphabet letters for the same basic sounds.
Q: Can you recreate the music from the visualization?
A: It all depends on how precise and detailed the visualization is. Visualizations can go from the most primitive (a line going roughly up and down in sync with the highs and lows of a melody) to extremely precise -- look at the waveform of a recording in an audio editing software, that's also a visualization of music, and if you have that image, that visualization, you can recreate the original music with far more precision and detail than any standard notation system.
Bonus video link as promised... reading your question reminded me of the Cat Concert, and I wondered how much a pianist who never heard the original could play it back by just seeing (and not hearing) the animation -- i.e. the visualization.
You'll find the original easily on YouTube, but this one from me is even more interesting ;-)

Cheers


MethodNotAllowedHttpException in Laravel while API writing

Question: I am developing APIs using Laravel and I am new to it. I am using following method as route for my api but facing error.
Route in api.php:
Route::post('user/register','UserController@Register')->middleware('auth:api');

Error:
MethodNotAllowedHttpException

Is there any setting or something else which I have missed.
Comment: and how are you accessing the route?
Comment: Aren't  you requesting a `get` request ?
Comment: I am using http://127.0.0.1:8000/user/register to access it using postman and selected post method.
Comment: Try it to access like: 127.0.0.1:8000/user with `POST` method!
Comment: I see the following error then...Sorry, the page you are looking for could not be found.
Comment: Are you trying to create a user using this api?
Comment: yes I am trying to create user
Comment: Are you added any prefix with this route? Make sure there is no any prefix added. If you added it, please use it when you call the route! If possible, post your whole `route.php/web.php/api.php` file here.
Comment: First of all you should dump your routes in the console with php artisan route:list and see how it looks.
Comment: I ran the command php artisan route:list and showed route like api/user/register. I tried to call method by the given url and its now showing InvalidArgumentException
Route [login] not defined.
Answer: Make sure you are using the post url in the postman while making a request
the url you are using seems to be get url i.e  127.0.0.1:8000/user/register
if your route is
Route::post('/user','UserController@Register')->middleware('auth:api');

Use the below url in postman with method as post
127.0.0.1:8000/user
Answer: You should add /api in your url when you trying to access api routes, so it should look like this 127.0.0.1:8000/api/user/register
Comment: This feature is available for those who are already registered. Think about the concept of Super admin and admin.
Comment: ok, so whats the problem then? do you provide user's token when you try to access this route? do you use passport `package`?
Comment: I am facing the same issue still
Comment: show how you trying to access the route, and also do you really need `middleware('auth:api');` on this route? as I guess, this route is for registration, when you send this request you are guest (if I understood correctly) but this middleware only accept authenticated user
Comment: In this case it should show some authentication error rather than methodexception error
Comment: it also depends on your `Exception/Handler.php` . try to `dd()` in `unauthenticated` or `render` method, check if you are accessing it
Comment: remove  `->middleware('auth:api')` from your route and try
Comment: what do you mean "work with that"? you are trying to add authorized middleware to route, which shouldn't has it
Comment: I need to work with middleware. In other words I need to authenticate users before accessing my API.
Comment: in this case, user which trying to register, must be a registered user(if it makes sense)


ubercart invoice generation to allow user to request funds withdrawal

Question: I have a site where user purchases some service and once the service is received by the purchased person, i should allow the service provider to raise a invoice order to request funds.
what are the modules that i should use to achieve this
Answer: If you are implementing the "service" as part of your site, you can attach the "services" to the user by assigning permissions to the "service" to a role, then create a content type, enable it as product and attach a "feature" to a product to enable the role for a limited amount of time (if this is your business model).
This would use CCK (to define the product) + Ubercart (for setting up the shop and attaching Product + feature to product) as well as Permissions (to your "service") and Roles (to apply to the permissions).
I hope this has been of some help!


square of primes above 5

Question: Given that squares of all primes above 5 are either 1 (mod 30) or 19 (mod 30), is this just a curious coincidence, or is there some straight-forward explanation?
My research has not lead me to any explanation, but I do think there is more going on here than just a curious coincidence. Any tips or pointers for learning more about this would be greatly appreciated.
To be sure, not asking for a proof here.
Comment: With regard to the suggestion to close the question, I would request that the question stay, since it was not a request for a proof, as in the linked duplicate. The answers provided here to assist in understand as per the request. Also, I don't think it is fair to tag something as a duplicate when it predates what the question it is asserted as duplicating
Comment: Both of the answers so far have given me new ways of looking at the relation. I am most grateful, and it is definitely not just some curious coincidence.
Answer: In general, as $a^2 \equiv (-a)^2 \bmod p$ for any $a,p$, there are not many squares modulo a fixed residue. In your case, use Chinese Remainder Theorem to reduce the consideration to $\bmod 2$, $\bmod 3$ and $\bmod 5$. Let $p>5$ be a prime :

$2 \not \mid p$, so $p \equiv 1 \bmod 2$, showing $p^2 \equiv 1 \bmod 2$
$3 \not \mid p$, so $p \equiv 1,2 \bmod 3$, both lead us to $p^2 \equiv 1 \bmod 3$
$5 \not \mid p$, and the only remaining residues for squares $\bmod 5$ are $1,4$.

Thus, $p^2 \equiv 1 \bmod 30$ or $p^2 \equiv 19 \bmod 30$ depending on whether $p^2 \equiv 1 \bmod 5$ or $p^2 \equiv 4 \bmod 5$.
Now, if you like you can extend this result to $\bmod \; 120$ using that $p^2 \equiv 1 \mod 8$ for $p>2$.
Answer: Any prime $>3$ can be written as $6n\pm1$
$$(6n\pm1)^2=36n^2\pm12n+1=24n^2+24\frac{n(n\pm1)}2+1\equiv1\pmod{24}\  \ \ \ (1)$$
Any prime $p>3$ can be written as $\equiv\pm1,\pm2\pmod5$
$$\implies p^2\equiv1,4\pmod 5\  \ \  \ (2)$$
Now apply CRT on $(1),(2)$

square of primes above 5


Using nginx to mask ip address of outgoing connections

Question: We have a business requirement to channel all outgoing connections from multiple processing servers through a single IP address.
Our setup is as follows:
We have an nginx server which works as a load balancer for incoming http requests. We then have multiple web servers, which connect to processing servers which in turn connect to our customers databases.
Client --> Loadbalancer --> Web servers --> Process servers --> Database
Client <-- Loadbalancer <-- Web servers <-- Process servers <-- Database
Currently, we provide our customers a list of IP addresses that they should add to their database whitelist. However, as we scale this whitelist will become longer and our customers in turn would need to again update their whitelist respectively.
Desired Setup
To work around this, we would like to channel all outgoing connections through another nginx server, which would mask the IP addresses of our processing servers. In turn, we would now only have one IP address that our customers would whitelist.
Client --> Loadbalancer --> Web servers --> Process servers --> IP Masking --> Database
Client <-- Loadbalancer <-- Web servers <-- Process servers <-- IP Masking <-- Database
Is this possible solely with nginx, if so, what steps would we need to take to achieve this?
Comment: You're looking for a _forward_ proxy. Nginx is a _reverse_ proxy. Get a proper forward proxy such as squid, and this is very easy.
Answer: What you ask is possible with nginx starting from version 1.9.0.
They added tcp (not http) proxy support. Starting from 1.9.13 they also added udp proxying.
Read https://www.nginx.com/resources/admin-guide/tcp-load-balancing/#upstream
and https://nginx.ru/en/docs/stream/ngx_stream_proxy_module.html
The tricky part would be differentiating incoming connections on (IP mask nginx) to decide to which database to connect. In HTTP proxy you can use host name. In tcp proxy you should either listen on different ports or different IP addresses. nginx.conf:
<code>worker_processes  4;

error_log  /var/log/nginx/error.log;

events { worker_connections  1024; }
stream {
        server {
           listen 3307;
           proxy_pass client2.db.dev:3306;
           proxy_buffer_size 16k;
        }
        server {
           listen 3308;
           proxy_pass client1.db.dev:3306;
           proxy_buffer_size 16k;
        }
}
</code>
Comment: But generally nginx is not the best tool for proxying database connections. There are many database-specific proxy. For MySQL it's a ProxySQL, MaxScale SQL or mysql-proxy.
Many use HAProxy for TCP (and SQL) proxying (it has embedded WEB connection state monitoring).
Comment: nginx can reload configuration without interrupting connection, so it's safe to edit it as many times as you like. To make automation easy (just create or remove files), you may use nginx 'include' for directory where you put your upstream configuration: new upstsream -> new config file -> nginx reload.
Comment: I guess it is not the database connection we are proxying, it is the process servers themselves. The idea is that any one of these process servers could potentially connect to the customers database. The connection is via a request made from a node.js server running on the process servers. What we are looking to do is channel all outgoing requests from all of the process servers through a single IP so our customers only need to whiltelist 1 IP address at there end.
Comment: It doesn't matter which kind of  connection to the customer database  your node.js server is using if it's a TCP connection. Then Nginx TCP proxy would work. The only thing you should change on process server is customer database endpoint, which changes from real IP to your 'masking Nginx' IP.
Comment: So in that case I set up nginx on another server. Use IP tables to point my outgoing traffic towards it and provide the customer with the IP of the server running nginx and all should be dandy? In your experience is there much of a traffic bottleneck with this sort of setup?
Comment: Not exactly. You setup Nginx server - yes. Then you change not IP tables, but process server's config to point to Nginx entry point to specific customer (you should have many such points if you have many database connections, they should also be configured on Nginx). What about traffic bottleneck, you may setup several Nginx servers and use either RR dns or configure different process servers with different nginx IPs
Comment: OK I guess that ain't gonna work then because we would need to edit nginx config every time a new database is added which is multiple times per day. I like think your other solution using NAT might be better. We were kinda hoping for something as simple as point all outgoing connections to a single server that masks the IP and be done. Maybe we should get a Network Consultant .
Answer: Another possible solution is using NAT. In this case masking server will be your router with configured network address translation. In this case you don't need to change customer database IP in node.js configuration, but you should change network, possibly routing configuration on all process servers and have one gateway with NAT configured
Comment: Just looked this sort of configuration up and it looks perfect for us. Thank you.


What is $F_{k,\infty}$, i.e., $F$ distribution when the second degree of freedom approaches infinity?

Question: What is $F_{k,\infty}$, i.e., $F$ distribution when the second degree of freedom approaches infinity? I'm wondering if there is a known distribution(such as $\chi_k^2$) that it converges to.
Comment: See this discussed in the following answers:

1. https://stats.stackexchange.com/questions/216053/why-does-the-j-test-yield-a-chi2-distribution/216055#216055

2. https://stats.stackexchange.com/questions/140876/distribution-of-ratio-of-2-chi-squared/140928#140928  (including mention of it following from Slutsky's theorem)

3. https://stats.stackexchange.com/questions/278293/what-do-you-do-if-your-degrees-of-freedom-goes-past-the-end-of-your-tables/278294#278294
Answer: The F-distribution is the distribution of the ratio of two independent scaled chi-squared random variables, so we have the general form $F_{k_1,k_2} \sim (k_2 \chi^2_{k_1})/ (k_1 \chi^2_{k_2})$.  As $k_2 \rightarrow \infty$ we have the limit $\chi^2_{k_2}/k_2 \rightarrow 1$, so if we apply Slutsky's theorem we see that the F-distribution converges to a scaled chi-squared distribution:
$$F_{k_1,k_2} \rightarrow \frac{\chi^2_{k_1}}{k_1}.$$
Note that the scaled chi-squared distribution is an extremely useful distribution in statistical analysis (so much so that it should probably have taken the place of the chi-squared distribution; see discussion here).

Direct Proof: The above heuristic explanation uses the properties of the Snedecor F distribution based on its derivation from chi-squared random variables.  However, it is simple to give a direct proof the above result by taking limits of the density kernel.  The density kernel for the Snedecor F distribution can be written as:
$$\begin{align}
\text{Snedecor-F}(x|k_1,k_2)
&\propto \frac{1}{x} \sqrt{\frac{k_1^{k_1} k_2^{k_2} x^{k_1}}{(k_1x+k_2)^{k_1+k_2}}} \\[6pt]
&\propto x^{k_1/2 - 1} \bigg( \frac{k_2}{k_1x+k_2} \bigg)^{(k_1 + k_2)/2} \\[6pt]
&= x^{k_1/2 - 1} \bigg( 1 + \frac{k_1x}{k_2} \bigg)^{-(k_1 + k_2)/2} \\[6pt]
&= x^{k_1/2 - 1} \bigg( 1 + \frac{k_1+k_2}{k_2} \cdot \frac{k_1x}{2} \cdot \frac{1}{(k_1+k_2)/2} \bigg)^{-(k_1 + k_2)/2}. \\[6pt]
\end{align}$$
Taking $k_2 \rightarrow \infty$ we then obtain the limit:
$$\begin{align}
\text{Snedecor-F}(x|k_1,k_2)
&\propto x^{k_1/2 - 1} \bigg( 1 + \frac{k_1+k_2}{k_2} \cdot \frac{k_1x}{2} \cdot \frac{1}{(k_1+k_2)/2} \bigg)^{-(k_1 + k_2)/2} \\[6pt]
&\rightarrow x^{k_1/2 - 1} \bigg( 1 + \frac{k_1x}{2} \cdot \frac{1}{(k_1+k_2)/2} \bigg)^{-(k_1 + k_2)/2} \\[6pt]
&\rightarrow  x^{k_1/2 - 1} \exp \bigg( - \frac{k_1 x}{2} \bigg) \\[12pt]
&\propto \text{ScaledChiSq}(x|k_1). \\[6pt]
\end{align}$$
As can be seen, in the limit the kernel of the Snedecor F density approaches the kernel of the scaled chi-squared density.  Since convergence of the density kernels implies convergence in distribution, this is sufficient to prove that the Snedecor F distribution converges to the scaled chi-squared distribution.  $\blacksquare$
Comment: Thank you so much! Is there a reference or proof for this?
Comment: @ExcitedSnail A reference for this fact (without proof) would be [Wikipedia](https://en.wikipedia.org/wiki/F-distribution#Properties_and_related_distributions).
Comment: Proof follows from https://en.wikipedia.org/wiki/Slutsky's_theorem
Comment: @Ben Thank you very much! This is very helpful! A last question: why $\frac{\chi^2_{k_2}}{k_2}\rightarrow 1$, it seems not quite intuitive.
Comment: @Glen_b Thank you very much! Still have have some difficulty seeing the convergence to 1.
Comment: @frank Thanks a lot. This is very helpful!
Comment: Consider its mean and variance. More formally, what happens to the left and right limits of $F_n$ the cdf of that scaled chi square r.v. in the sequence as $n\to\infty$
Comment: I have added a direct proof of this result using the density function of the F distribution; this is the simplest method of proof I'm aware of, and it does not require use of the intermediate properties of the distribution.


Server monitoring and trigger tool (pt-stalk)

Question: Is there some equivalent tool to pt-stalk to monitor server load instead of MySQL on Linux machine?
Comment: What, specifically, are you trying to monitor? "server load" is a vague term (it could mean something as simple as load average, or it could mean a multivariate analysis of your system's overall workload)
Answer: To my best knowledge no such tool exists for server level monitoring.
That being said it should not be hard to make one of yourself. For example you can use 'monit' which is lightweight monitoring tool with alarm on load and actions that should resolve this alarm.
What data to collect depends on your personal preferences but i would recommend:

dmesg | tail -n 1000
ps axwwww
vmstat 5 5
any relevant pieces of logs from your application
netstat -antp
ifconfig -a
df
maybe sar
maybe 30 sec of network trafic (e.g. tcpdump)


Redux - Wrap actions inside another action in mapDispatchToProps

Question: I have several actions, that are need to be used with another one action,
more specific i have actions to work with doument and one action to save it, and i dont wont to repeat calling of save document, so i tried to create myself wrapper on the mapDispatchToProps and thunk.
I need to each action I pass to the method performed to thunk actions -
From
function changeAction() {
   return: {
     type: types.CHANGE
   }
}

To
function change() {
   return(dispatch, getState) => {
      dispatch(changeAction())
      saveDocument(getState());
   }
}

I tried to create method to map actions to thunk
export function mapUpdatePresentationsToProps(actions) {
    const mappedActions = {};

    Object.keys(actions).map(action => {
       mappedActions[action] = function() {
          return (dispatch, getState) => {
             dispatch(action)
             dispatch(updatePresentation(getState()))
          }
        }
    })

  return mappedActions;
}

And I always get an error 'Actions must be plain objects. Use custom middleware for async actions.' Am i doing something wrong? I dont know how i can debug them. Will be grateful for any help.
Answer: I guess you need to change:
dispatch(action)

to something like:
dispatch(actions[action]())

Right now it seems that you try to dispatch a string


SCSS: Select root class, then parent class and apply rules to child

Question: Unfortunately I haven't find a better title for this, but code says more than words.
I want the following CSS output:
.team-revolution-top-bar-marquee-is-active .team-revolution-top-bar-content {
    background-color: yellow;
}

Here is the minifed scss code:
.team-revolution-top-bar {
    &-marquee-is-active {
        white-space: nowrap;
        overflow: hidden;
    }

    &-content {
         flex-grow: 1;
         padding: 0.4rem;

        @at-root &-marquee-is-active {
             background-color: yellow;
        }
    }
}

I tried around with & and @at-root but nothing really worked.
Is this possible with SCSS or is there an alternative?
Answer: Then it might be time for an extended silent class.
%teamRevolution-bgC {
  background-color: yellow;
}

.teamRevolution-topBar {
  &-marquee-isActive {
    white-space: nowrap;
    overflow: hidden;

    @extend %teamRevolution-bgC;
  }
  &-content {
    flex-grow: 1;
    padding: 0.4rem;

    @extend %teamRevolution-bgC;
  }
}

.teamRevolution-topBar-marquee-isActive, .teamRevolution-topBar-content {
  background-color: yellow;
}

.teamRevolution-topBar-marquee-isActive {
  white-space: nowrap;
  overflow: hidden;
}
.teamRevolution-topBar-content {
  flex-grow: 1;
  padding: 0.4rem;
}


Error: `path` must be a string

Question: Olá!!! Estou aprendendo R pois preciso fazer dois trabalhos com estatística.
Estou tentando criar um Loop, mas recebo a mensagem de erro " 'path' must be a string. Essa é a sequencia de comandos...
leitura_arquivos_csv <- list.files(path= "D:/MESTRADO/DADOS ILHABELA/DADOS ILHABELA/Trabalho CH - ilhabela presal/bases_orig_finbra_ilha/", all.files = FALSE)
#
#Definindo agora um vetor com o nome dos arquivos "nomes_arquivos" que vai excluir a terminação "csv"
nomes_arquivos <- substr(leitura_arquivos_csv,8,21)

#fazendo o Loop com todos os arquivos
quantidade_arq <-length(leitura_arquivos_csv)
local_gravação <- "D:/MESTRADO/DADOS ILHABELA/DADOS ILHABELA/Trabalho CH - ilhabela presal/bases_orig_finbra_ilha/"
for(i in 1:quantidade_arq){assign(nomes_arquivos[i],read_xlsx(paste(local_gravação,leitura_arquivos_csv, sep ="" )))}

Alguém pode me ajudar?
Answer: O principal erro é tentar fazer tudo na mesma instrução.
Dentro do ciclo for o assign deve ser dividido em cada uma das instruções que contém. Assim é possível ver que falta indexar leitura_arquivos_csv, em cada iteração está a criar com o paste um vetor de nomes.
#
# Definir uma vez "local_gravação" e usá-la sempre
# que for preciso. Não tem a barra final para mais
# tarde poder usar a função file.path()
local_gravação <- "D:/MESTRADO/DADOS ILHABELA/DADOS ILHABELA/Trabalho CH - ilhabela presal/bases_orig_finbra_ilha"
leitura_arquivos_csv <- list.files(path = local_gravação, all.files = FALSE)

#
# Definindo agora um vetor com o nome dos arquivos
# que vai excluir o diretório e a terminação "csv"
nomes_arquivos <- basename(leitura_arquivos_csv)
nomes_arquivos <- tools::file_path_sans_ext(nomes_arquivos)

for(i in seq_along(nomes_arquivos)){
  nome_arq <- file.path(local_gravação, nomes_arquivos[i])
  dados_tmp <- read_xlsx(nome_arq)
  assign(nomes_arquivos[i], dados_tmp)
}

Comment: Agradeço a ajuda, mas ainda há algo errado...
Comment: #Definindo um vetor com os nomes dos arquivos "leitura_arquivos"
leitura_arquivos <- list.files(path= "C:/Users/VAIO/Desktop/FINANCAS/Ilhabela", all.files = FALSE)
#
#Definindo agora um vetor com o nome dos arquivos "nomes_arquivos" que vai excluir a terminação "csv"
#de todos eles;
nomes_arquivos <- substr(leitura_arquivos,8,21)

#####Fazendo o Loop com todos os arquivos########
#
#definido um string para a qtde de arquivos
quantidade_arq <-length(leitura_arquivos)
Comment: # Definir uma vez "local_gravação" e usá-la sempre
# que for preciso. Não tem a barra final para mais
# tarde poder usar a função file.path()
local_gravação <- "C:/Users/VAIO/Desktop/FINANCAS/Ilhabela"
leitura_arquivos <- list.files(path = local_gravação, all.files = FALSE)
# fazendo o Loop "for i"
nomes_arquivos <- basename(leitura_arquivos)
nomes_arquivos <- tools::file_path_sans_ext(nomes_arquivos)

for(i in seq_along(nomes_arquivos)){nome_arq <- file.path(local_gravação, nomes_arquivos[i])
dados_tmp <- read_xlsx(nome_arq)
  assign(nomes_arquivos[i], dados_tmp)}
Comment: Está dando o seguinte erro:
Error: `path` does not exist: 'C:/Users/VAIO/Desktop/FINANCAS/Ilhabela/finbra_municipios2013'
Comment: Rui Barradas, deu certo!!! Muito obrigado!!!
Comment: @JoãoRicardoMorales O que fazer quando [alguém responde](https://stackoverflow.com/help/someone-answers) às suas perguntas.

Error: `path` must be a string


Verificar se existe parâmetro na URL pelo PHP

Question: Galera, é o seguinte...
Preciso verificar se na url existe um parâmetro (source) e pegar o valor que está sendo passado por ele...
Eu testei assim $param = $_GET["source"]; mas se não tiver parâmetro nenhum na url, da um erro Notice: Undefined index: source.
Como faço pra ele só pegar o parâmetro caso exista?
Comment: Caio, conseguiu entender com a minha resposta?
Comment: @LeonardoNegrão sim cara, muito obrigado!
Answer: primeiro verifique se ela existe, assim:
if(isset($_GET['source'])) { //existe source?

$param = $_GET['source'];

}
else { //se não existir source, $param terá outro valor

$param = "";

}


Why are hooks (except hook_help) not working?

Question: <?php
function webformta_init() {
    dsm('hello world');
}

does absolutely nothing.
<?php
   dsm('hello world');

sets an alert message with the text "hello world".
I've tried wrapping this in several hooks. Hook_load, hook_node_load, you name it.
But somehow, oddly, hook_help seems to be working.
function webformta_help($path, $arg) {
  switch ($path) {
    case "admin/help#webformta":
      return '
'.  t("Grades quizzes like a TA. Works with Webform.") .'
';
      break;
  }
}

creates a nice little help link in the module list and outputs the text and everything.
What did I screw up?
Comment: You need to clear the cache after adding new hooks.
Answer: You need to clear the cache after adding new hooks.


Prove that a sequence is increasing (check the idea)

Question:
4.5 A real sequence $\{x_n\}$ satisfies $7x_{n+1}=x_n^3+6$ for $n\ge1$. If $x_1=\frac{1}{2}$, prove that the sequence increases and find its limit. What happens if $x_1=\frac{3}{2}$ or if $x_1=\frac{5}{2}$?

In order to prove, that sequence is increasing, my idea is to take the first derivative of the function $y = (x^3 +6)/7$
Our result is $y' = 3x^2/7$ and this is positive. So our function is increasing function. Is this solution correct?
Are there other approaches that can prove the above statement without using derivatives?
Edited:
I agree, I was wrong. Here are my new arguments:
1) By induction I have proved that $0<x_n<1$.
2) $x_{n+1} - x_n = (x_n^3 + 6)/7 -x_n = x_n^3/7 - x_n + 6/7 $
But I don't know if we can conclude from this that $x_n^3/7 - x_n + 6/7 >0$
Comment: It is true that the derivative is positive, but this does not imply that the sequence is increasing. For example, if $x_{n+1}=x_n^3$, starting by $x_0=1/2$ you get $$\frac{1}{2} , \frac{1}{2^3} , \frac{1}{2^9} , \frac{1}{2^{12}} , \dots$$ which is decreasing.
Comment: Can I ask which book this question is from?
Answer: No, not really.
You're basically correct that the function $y=(x^3+6)/7$ is increasing and the argument is basically correct. However that was not the real question. You were to prove that $x_n$ is an increasing sequence, which means that you have to prove that $x_{n+1} = (x_n^3+6)/7 \ge x_n$.
To solve the problem you should probably not use that approach. You should consider the inequality above which says that we should investigate the sign of $(x^3+6)/7-x$ or $x^3+6-7x$. The trick here is to factor the polynomial. We have $x^3-7x+6 = (x+3)(x-1)(x-2)$. We see that it can only change sign at $x=-3$, $x=1$ and $x=2$. So we have that:
$$x_{n+1} \begin{cases}\lt x_n & \text{if } 1 < x_n < 2\\
\lt x_n & \text{ if } x_n < -3 \\
\ge x_n & \text{ otherwise }\end{cases}$$
This is enough to see that the sequence will increase as long as $x_n<1$. But we see that $(x^3+6)/7<1$ if $0<x<1$ so the recursion formula will never pass or even reach $1$.
To prove that actually $\lim x_n=1$ we observe that $x_n$ is increasing and it's bounded so obviously $x_n$ is convergent, let say $L = \lim x_n$, then it's easy to see that $0 = \lim 7x_{n+1} - x_n^3 - 6 = 7L-L^3-6$. The solutions to that equation is only $L=-3$, $L=2$ and $L=1$, but only $L=1$ fits the requirements.
For $x_1=3/2$ we will with the similar reasoning have that $x_n$ decreases and it turns out that $x_n\to1$. And for $x_1=5/2$ it will increase and $x_n\to\infty$ (we observe that if having a limit it must be one of the above, but increasing from $5/2$ can't be one of them so it can't have a limit and therefor not bounded).
Comment: See my comment above: the argument of the OP is not correct.
Comment: @Crostul And? The question was whether the argument was correct for the problem and my answer was no it's not. However the argument is correct for another question which I pointed out.
Comment: Thank you for comments. Please take a look at my updated solution.
Answer: Given that $x_{n+1} = (x_{n}^3 + 6)/7$, when $x_1 = \frac{1}{2}$ we will find the limit in 3 steps:

$\color{red}{0 < x_n  < 1 \text{ for all $n$.}}$ Note that if $0 < x_n < 1$ then $0 < x_n^3 + 6 < 7$, which in turn implies that $0 < x_{n+1} < 1$. So, starting with $x_1 = \frac{1}{2}$, we will get the entire sequence satisfying  the inequality $0 < x_n  < 1$.
$\color{red}{x_n \text { is increasing. }}$ To show this, it is sufficient to show that if $0 <x_n < 1$ then $x_n < x_{n+1}$. To get this, we subtract $x_n$ from both sides of $x_{n+1} = (x_{n}^3 + 6)/7$ and get:
\begin{eqnarray*}x_{n+1} - x_{n} = \displaystyle\frac{x_{n}^3 + 6 - 7 x_n}{7} =  \displaystyle\frac{(x_n-1)(x_{n}^2 + x_n - 6)}{7} > 0 & \text{ when $0 < x_n < 1$} \end{eqnarray*}
$\color{red}{x_n \text{ converges to 1}. }$ Since the sequence $(x_n)$ is increasing and bounded, it is convergent. Therefore, the limit $l \leq 1$ exists and satisfy: $l = (l^3 + 6)/7$. This gives us the limit as $l = 1$.

Similarly, when $x_1 = \frac{3}{2}$ we can again find it in 3 steps:

$\color{red}{1 < x_n  < 2 \text{ for all $n$.}}$ If $1 < x_n < 2$ then $1 < x_n^3 + 6 < 14$, which in turn implies that $1 < x_{n+1} < 2$. So, starting with $x_1 = \frac{3}{2}$, we will get the entire sequence satisfying  the inequality $1 < x_n  < 2$.
$\color{red}{x_n \text { is decreasing. }}$ To show this, it is sufficient to show that if $1 <x_n < 2$ then $x_n > x_{n+1}$. To get this, we subtract $x_n$ from both sides of $x_{n+1} = (x_{n}^3 + 6)/7$ and get:
\begin{eqnarray*}x_{n+1} - x_{n} = \displaystyle\frac{x_{n}^3 + 6 - 7 x_n}{7} =  \displaystyle\frac{(x_n-1)(x_{n}^2 + x_n - 6)}{7} < 0 & \text{ when $1 < x_n < 2$} \end{eqnarray*}
$\color{red}{x_n \text{ converges to 1}. }$ Since the sequence $(x_n)$ is decreasing and bounded, it is convergent. Therefore, the limit $1 \leq l \leq 1.5$ exists and satisfy: $l = (l^3 + 6)/7$. This gives us the limit as $l = 1$.

Finally, when $x_{1} = \frac{5}{2}$ we can show that the sequence is unbounded above, and increasing. Therefore, limit does not exist on real line. This follows from the fact that
\begin{eqnarray*}x_{n+1} - x_{n} = \displaystyle\frac{x_{n}^3 + 6 - 7 x_n}{7} =  \displaystyle\frac{(x_n-1)(x_{n}^2 + x_n - 6)}{7} >0  & \text{ when $x_n > 2$} \end{eqnarray*}
Also, when $x_n > 2$, the function $\displaystyle\frac{(x_n-1)(x_{n}^2 + x_n - 6)}{7}$ is also increasing in $x_n$. This implies that the difference between $x_{n+1}$ and $x_{n}$ is always greater than or equal to the value:
$\displaystyle\frac{(x_1-1)(x_{1}^2 + x_1 - 6)}{7} = \frac{1.5(2.75)}{7}$. Therefore, the sequence $(x_n)$ is increasing and unbounded.