Método SendEmailAsync não é executado

Question: Debugando vi que o método SendEmailAsync do controller Account não é executado e não retorna erro, ele simplesmente é ignorado, todos o paramentos estão corretos userId, code e protocol.
string code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await _userManager.SendEmailAsync(user.Id, "Confirmar sua conta", "Confirme sua conta clicando aqui");

alguém sabe o que pode ser?
Comment: Não coloque foto dos seus códigos, pois caso precisemos testar teremos que redigir tudo do zero, para que possamos reproduzir seu problema copie seu código e coloque-o em um bloco de código clicando em [Editar](https://pt.stackoverflow.com/posts/244487/edit)
Comment: obrigado pela correção.
Answer: Para isso você deve implementar a classe SendEmail que esta assinada com a interface ISendEmail, aproveite e veja a injeção de dependência.
Com isso deve resolver seu problema.
Comment: Resolvi injetando o IIdentityMessageService no AccountController, e resolvendo a dependência com simple injector. Sendo assim, pude usar a classe  EmailService  com o método SendAsync para enviar email de confirmação.
Comment: Se estiver utilizando o novo template do Core é so implementar a classe, se fazendo isso resolveu ótimo. Cavalaria!!!

Método SendEmailAsync não é executado


DevExpress XtraGrid v12.2 GetSelectedRow

Question: am using DevExpress v12.2 to develope my C# application ,
so am using GridControl ToolBox ,the problem is  that there is no proprety to get the selectedrow from the GridContol or even his index .
another problem the SelectionChanged Event does not exist too,
The issue is fixed on the v13.2, but i have to  work with the DevExpress v12.2.
I come here cause i didnt find any solution for this after a long research,
Any suggestion please ?
am using this code, its works when i put the index :
<code>        Client clients = new Client();
        clients = (Client)gridControl1.MainView.GetRow(0); //0 is the index i put manually
        MessageBox.Show(clients.ClientNom);
</code>
So how i get the selectedindex ?, thanks.
Comment: As far as getting the index use gridControl1.GridView.FocusedRowHandle
Comment: What is your datasource? Table or binding list?
Answer: I find it,
the solution is to go to the Desginer of the GridControl and select the event,in my case its RowClick,and Handle from there :
<code>     private void gridView1_RowClick(object sender, RowClickEventArgs e)
    {
        Client clients = new Client();

        clients = (Client)gridControl1.MainView.GetRow(e.RowHandle);
        MessageBox.Show(clients.Email);
    }
</code>
Thanks for your answer AMR.
Ps : V12.2 of DevExpress GetSelected Rows does not exist like proprety
Answer: Happen to be looking at an identical solution to your problem right now.
<code>//Get Selected Rows
int[] selectedRows = DevExpress.XtraGrid.Views.Grid.GetSelectedRows();

//Get the value of the cell you want. Where GridColumn is your DevXpress GridColumn Object
DevExpress.XtraGrid.Views.Grid.GetRowCellValue(selectedRows[0], GridColumn)

//For Entire Row
DevExpress.XtraGrid.Views.Grid.GridView.GetRow(selectedRows[0]);
</code>
(This is in Dev Express v12.1)
Comment: That only give the op one cell value from the row, I believe he wants the whole row as a object.
Comment: Personally I always treat the grid view as a data display device, and always go to the data source to get and changes the data.


In what type of scenarios (other than tuning) would it be helpful to have microtonal perfect pitch?

Question: I have perfect pitch (I can identify the note name of a given pitch in 12-tone equal temperament like a note on a piano), but often I cannot tell how far off is a note from the quantifications in 12TET when it is not significantly (more than a quarter tone) different, especially when tuning. It seems like I can be carried away from the quantification grid of 12TET temporarily, and I think it is because the quantification grid of 12TET has wide gaps so my brain tries to adjust notes I hear and put it on the grid. However, my primary instrument is piano so my focus is not on tuning instruments, although it would be a clear benefit for this scenario.
I suppose that training my brain to recognize pitches of microtonal tuning (like 24-tone TET or something similar) will mitigate this problem, but what other scenarios can a more refined tuning system (i.e. a tuning system with more divisions between an octave) for perfect pitch (i.e. be able to hear a pitch and associate it with one of the tones in that tuning system) be helpful?
Answer: If your primary instrument is piano, then unless you are interested in tuning the piano yourself, or assessing its tuning, then there's no advantage I can see in trying to make your perfect pitch more precise.  If you want to sing, or play some instrument with variable tuning, then it might be of service to work on recognizing different tuning systems.
Answer: Microtonal perfect/absolute pitch comes in handy - if not enjoyable - when it comes to listening to open mike-quality or talent show singing. When evaluating how good that singing sounds, it helps to be able to discern between a C, a flat C, a sharp C, and the quarter tone between C and C sharp (for the matter, I can detect all 4 with my perfect/absolute pitch, although my quarter tone recognition may be 10 or more cents off). It also helps to be able to determine whether the background music and the singing are out of tune by roughly the same amount.
Comment: Why evaluate with absolute pitch rather than relative pitch?
Comment: @awelotta - Evaluating whether the background music and the singing are out of tune by roughly the same amount can be done with relative pitch, but determining whether a note is an in-tune C, a flat C, a sharp C, or actually a quarter tone requires absolute pitch if no defined reference notes are provided.


How to filter a dataframe already containing NaN based on entry conditions?

Question: I am starting with one dataframe and I would like to split it into three dataframes depending conditions placed on entry values. For, df1 I would like to only have Person_X values <0.33. For df2, I would like to only have 0.34<Person_X values<0.65. For df3, I would like to only have Person_X values >0.66. I would like NaN to replace integer values that don't fit the requirements.
So, starting with df:
In [1]: df=pd.DataFrame({'location':[4991, 8870, 2703, 9674],
   ...:                  'Person_1': ['NaN', 0.2,0.5,0.7],
   ...:                  'Person_2':[0.8, 0.45, 'NaN', 0.1]})
   ...: df
Out[1]:
   location Person_1 Person_2
0      4991      NaN      0.8
1      8870      0.2     0.45
2      2703      0.5      NaN
3      9674      0.7      0.1

I would like to have three dataframes that look like:
 df1
   location Person_1 Person_2
0      4991      NaN      NaN
1      8870      0.2     NaN
2      2703      NaN     NaN
3      9674      NaN      0.1

df2
 Out[4]:
   location Person_1 Person_2
0      4991      NaN      NaN
1      8870      NaN     0.45
2      2703      0.5      NaN
3      9674      NaN      NaN

df3
 Out[4]:
   location Person_1 Person_2
0      4991      NaN      0.8
1      8870      NaN      NaN
2      2703      NaN      NaN
3      9674      0.7      NaN

I have tried something like this for each of the requirements, but since df contains NaN already, I am running into issues.
patient_cols=[col for col in df if col.startswith('Person')]
df[patient_cols]=df[patient_cols].applymap(lambda x: np.nan if x>0.33 else x)
df[patient_cols]

Answer: Let's use pd.DataFrame.where:
df=pd.DataFrame({'location':[4991, 8870, 2703, 9674],
   'Person_1': [np.nan, 0.2,0.5,0.7],
                     'Person_2':[0.8, 0.45, np.nan, 0.1]})

#Just incase your NaN are strings as indicated by your original posts.
df=df.replace('NaN', np.nan)

df= df.set_index('location')

df1 = df.where(df<.33).reset_index()
df2 = df.where((df>.34) & (df<.65)).reset_index()
df3 = df.where(df>.66).reset_index()

print(df1)
print('\n')
print(df2)
print('\n')
print(df3)

Output:
   location  Person_1  Person_2
0      4991       NaN       NaN
1      8870       0.2       NaN
2      2703       NaN       NaN
3      9674       NaN       0.1

   location  Person_1  Person_2
0      4991       NaN       NaN
1      8870       NaN      0.45
2      2703       0.5       NaN
3      9674       NaN       NaN

   location  Person_1  Person_2
0      4991       NaN       0.8
1      8870       NaN       NaN
2      2703       NaN       NaN
3      9674       0.7       NaN

Comment: I would add `df=df.replace('NaN', np.nan)` to the beginning, since the OP's initial dataframe doesn't have np.nan values.
Comment: @MrNobody33 That seems wise.


Secured Download Link

Question: Lets say I have a file in my server and I want it to be available for my user. How can I provide them a download link without providing them the real (direct) path of the file?
Comment: Provide an IIS Virtual Path
Comment: can you provide me a sample code or link for tutorial?
Comment: This is nothing in code - it's just configuration of your web-server. In IIS use IIS-Manager to add an VirtualDirectory to your application.
Answer: You need a virtual directory setup in IIS pointing to the directory/path of the file so for instance;

IIS Manager - go to appropriate website and right click, add virtual directory
Add alias of your virtual directory and path (e.g. docs and C:\docs)

Once this configuration is done you will be able to give download links: [http://url.com/docs/file.txt]

Secured Download Link


added ip-based virtual host to sites-available and created symlink to sites-enabled...but new domain times out

Question: I added ip-based virtual host to sites-availble and created symlink to sites-enabled, but new domain times out.
When i navigate to mynewdomain.com it says connection timed out.
NameVirtualHost 22.214.171.124
<VirtualHost 184.108.40.206>
        ServerAdmin webmaster@localhost
        ServerName newdomain.com

        DocumentRoot /var/www/newdomain.com
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None
                Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                Order allow,deny
                Allow from all
        </Directory>

        ErrorLog /var/log/apache2/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog /var/log/apache2/access.log combined
        ServerSignature On

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

Answer: Did you add 184.108.40.206 to your server as a secondary address to one of its network interfaces? On Debian/Ubuntu, you would need to add lines like the following to your /etc/network/interfaces file (making an assumption about the netmask):
auto eth0:12
iface eth0:12 inet static
 address 18.104.22.168
 netmask 255.255.255.0
 network 22.214.171.124
 broadcast 220.127.116.11

And then run ifup eth0:12 as root.
Comment: And add the port at the end of the IP address in apache configuration like: `NameVirtualHost 188.8.131.52:80` and ``
Answer: By navigate to mynewdomain.com I'm going to assume you actual mean newdomain.com which is what is mentioned in your example configuration.
1: That being said, make sure newdomain.com actually set in DNS to resolve to 18.104.22.168 and that the change has propagated through DNS.
2: Make sure to completely restart apache to make sure it picks up the new configuration. Do a restart or even better a stop then start.
Do you see any activity from your client's IP in the access log?


Is there a difference between Cmaj♭7 and Cdominant7 chords?

Question: Is there a difference between Cmaj♭7 and Cdominant7 chords? As far as I can tell they are the same, is one used more commonly than the other?
Comment: FWIW, I have never seen those, only "C7". Where did you find such chord symbols?
Comment: I don't understand downvoting of the question. The chord symbols are indeed wrong, but it doesn't make it a bad question, and the answer corrects the symbols.
Comment: They're simply not chord names as we know them! Dominant isn't often used, as a simple '7' assumes it's dominant.Check answers for 'What are MA7 and MI7 chords'.
Comment: @user1079505, I agree. I see too many downvotes apparently for no other reason than the OP posts a misunderstanding or has trouble wording the question. Questions are posted because the OP doesn't understand something. We have to read through the words and try to understand the problem.
Comment: Thanks for the help. I'm very new to naming chords, "Cmajb7" was just something that stuck with me from a few years ago 'cause it's intuitive to me. But this advice has helped a lot :)
Answer: Technically they are the same thing BUT the spellings Cmaj♭7 and Cdominant7 are not used for chord symbols. if you want a chord that is spelled C-E-G-B♭ you simply write C7. That indicates Root, M3, P5 and m7. If you want C-E-G-B (M7) then you would write Cmaj7, although there are other ways to indicate a major 7th chord, such as ma7, M7 to name a couple.
Answer: I agree with John's explanation, but I would like to point out one important thing, which is probably the cause of the misunderstanding in the question. The symbol Cmajb7 is not only uncommon, but it is actually a contradiction in itself. The maj in the symbol Cmaj7 does not refer to the quality of the triad but it refers to the seventh. So the correct parsing of Cmaj7 is C - maj7, and not Cmaj - 7. I think the question only makes sense if one uses the latter parsing, because then it would make perfect sense to specify what kind of seventh should be added on top of the major triad. However, with the correct parsing - and this is of course just convention - the symbol Cmajb7 is non-sensical, because it says: take a major triad C and add a major flat seventh majb7, which is of course impossible.
So the only common symbol for a C dominant seventh chord is C7, because it is understood that 7 stands for a minor seventh. If we want a major seventh, we need to use maj7, or, alternatively, any of the common symbols that indicate a major seventh chord, such as CΔ7 or CMa7. I personally only use CΔ7 and Cmaj7 because they never cause misunderstandings.
Comment: A lucid explanation. There's lots of confusion with the numbers, but if we consider the number to be more related to the major or minor bit, it makes sense. That's until we encounter Cm6...!
Comment: @Tim: Thanks Tim. Yes, it's all about knowing the conventions, but actually Cm6 and Cmaj7 both makes sense in the same system, because we need 'm' to denote the minor triad, and we just use 'C' to denote the major triad. In that sense it's clear that the 'm' in Cm6 does not refer to the '6'  but to the basic triad.
Comment: Thanks for this answer (+1)  and pointing out the contradiction, something I should have done. @Tim makes a good point, I've wondered in the past why 7 was chosen to mean m7 in chord symbols myself since any other extension, 6, 9, 13 are all major unless flattened. Then again chord symbols are not always an exact science!
Comment: @JohnBelzaguy: That's a good point. I guess nobody knows exactly why things developed that way, but I'd guess that a dominant seventh chord is just so much more common (in traditional folk music and conventional classical music), that it made sense to use a simple symbol for that only seventh chord that was used next to all the triads. Only when jazz started using seventh chords as basic harmonies did it become necessary to use other symbol in addition to '7', and '7' was already taken. When I started out I always used the mixolydian scale as the basis for understanding the naming of tensions.
Comment: @JohnBelzaguy - my guess is usage. By far the most common '7th' chord is dominant, so that gets the simplest label. But, do I feel a question coming on..?
Comment: @Tim and Matt, that was my thought too, you see a dominant chord much more than a maj7 in most styles of music.
Comment: Although only the 7th is different between C7 and CMaj7, and only the third is different between C7 and Cmin7  I still think it's simplest to say that the terms "Major" and "minor" in "CMaj7" and "Cmin7" describe *both* the third and seventh.  I would think writing CMaj7 followed by C7 makes the chord change clearer than CMaj7 followed by Cmaj♭7.  The latter notation might make the desired voice leading clearer, but if 7 and maj7 chords would normally place the 7th in different octaves [which could plausibly be the case with e.g. Fmaj7 and F7 when using standard tuning]...
Comment: ...that would usually because playing them in the same octave would be difficult.  An Fmaj 7 can put the 7th on top with --3210, or for some players 1-3210 or 113210, but playing an F7 with the seventh on top is apt to be difficult with standard tuning.
Comment: @supercat - nowhere mentions guitar, but playing using say, a barred open G shape, it's straightforward to drop the top string down a fret for maj7, then another fret for 7 (dom7). And - 113210 introduces  Bb. Why do we need that?
Answer: The suffix major (Maj7) is referring to the 7th and not to the chord quality.
So there is only C7 (major chord with minor 7th) or Cmaj7 (major chord and major 7th)
But yes, the C7 can have different functions:
In classical music theory the C7 chord has the function of the dominant resolving to the tonic F.
In blues the C7 is the tonic (on C major) and is stable even it has a minor seventh (blue note - also the subdominant isn't notated as F b7 in the Blues and Jazz notation. F7 means here a minor 7th). In classic IV7  is corresponding to F Maj7 in Jazz.
But the symbol is the same - like others comments and answers say.
Comment: C-E-G-Bb is notated as C7 (=major third, minor seventh). Spelling C7 = dominant seventh chord. The chord symbol for C-Eb-G-Bb  is **Cm7** (Spelling:  **C minor seven** (minor third, the 7 is   minor too! but not specified  -  in contrary to the minor chord Cm with major 7th = Cm +7, in this case the seventh is clarified by a natural resp. a sharp sign.
Comment: What would be the convention for naming C-Eb-G-Bb? If I understand correctly, Cmin7 would be C-E-G-Bb, C7
Answer: I think your intention is understood, and the chords would be the same, but you aren't following the chord symbol conventions.
It may help to understand the modifiers in chord symbols by adding parentheses which can be added to group the modifiers with the thing they modify. Normally parentheses will be added only to the chord extensions, but I will add them to all elements, just to illustrate...

Cmaj♭7 and Cdominant7

(Cmaj)(♭7)

Notice the maj modifies the root. The four triad types appended after the root letter: maj, 'min, aug, dim`. Depending on the notation system other symbols can be used, but they are still appended.
the ♭ modifies the 7, all the modifiers after the triad type are prefixed before the number

(Cdominant)(7)
The second chord is obviously meant to mean C dominant seventh chord. But, is the modifier 'dominant' for the triad (Cdominant)(7) or the seventh (C)(dominant7)? The problem is dominant isn't a modifier for either a triad type or a simple interval. It's not a 'dominant' triad. The triad part is major. The interval of a seventh isn't 'dominant'. Technically it's a minor seventh. 'Dominant' refers to the whole chord. Again, the meaning is clear, but that isn't a modifier of only one part of the chord.
The default values of all the elements - the triad type and the extensions - are those of a dominant V13 in a major key. Spelled in C major it would be G B D F A C E. In terms of intervals above the root it would be major third, perfect fifth, minor seventh, major ninth, perfect eleventh, major thirteenth.
That brings us back to...
(Cmaj)(♭7) where the maj is redundant, we know it by default. The ♭ is a bit tricky. Sevenths are minor by default, and in this chord symbols system ♭ means lower by half step, but surely you didn't mean to make a minor seventh a diminished seventh! I'm sure you meant it is lowering a major seventh to minor. But, as sevenths are minor by default, ♭7 is redundant too. You only need to write C7.
Watch out for some confusing points in chord symbols, like...

Cdim7 where dim could apply to both the triad and seventh
sharp and flat modifiers used as shorthand for 'raised' or 'lowered' even when an accidental isn't used in the actual spelling like Bmin7♭5 spelled B D F A with no flat.
sharp isn't used to raise the minor seventh, maj or a Δ get used, parenthesis help readability with things like Cmin(maj7)
alternate possibilities like C7♯5 versus Caug7 versus C7alt or C7sus4 versus C11
Comment: 'Sevenths are minor by default'. That statement is unstable. Unless you mean ' any chord with a bare 7 means that 7th is m7'. It's only diminished 7ths that have that 7th dropped by a tone, which you know.
Comment: @Tim, I mean the number `7` means _minor seventh_, you need to add a modifier to the seven to get major seventh `maj7` or diminished seven `dim7`, or one of the other symbols like `Δ` or `o`. If you look at groupings like this... `Gm7` ...means `(Gm)7` not `G(m7)` that parenthetical grouping is made clear by a case like `(Gm)(Δ7)`. The `m` modifier mean minor _for the triad_ not the `7`. The `7` is understood to always be a minor seventh unless modified. I call that a default value.


Consistency validation for sql server registry keys error on domain user

Question: I am trying to install MSSQL 2012 x64 standalone on clients computer which is in Domain Users group. Only consistency validation for sql server registry keys fails. When i open the event log it says AclPermissionsFacet, The SQL server registry keys from a prior installation.
-I am running the setup with Administrator credentials.
-It is a clean installation.
Answer: I was installing it from external hard drive. I just copied the setup to the desktop. Problem solved.


Installation of Angular failed in Ubuntu 18.04.4 LTS

Question: I am aware that this problem has already been reported before in this forum, but none of the proposed solutions (at least the ones I understood) has worked for me, so I will explain my case in detail.
I could successfully install both NodeJs and Angular CLI, but once there it doesn't recognize the ng command.
It says the command ng was not found, but it can be installed with sudo apt install ng-common.
But when I do so, then each time I use ng it appairs something unexplainable for me:

From there I can only abort the process with ctrl-z.
An odd thing is that the first time I installed it, it allowed me to use ng new and create a project. But then this problem started when I tried ng serve. And from there I have never been able to use the ng command, even though I have uninstalled and installed programs as suggested by various forums. For example, I have already tried:
sudo apt remove ng-common
sudo npm uninstall -g @angular/cli
sudo npm install -g @angular/cli

When I do that, the editor does not appear as in the image any more, but it returns to the state when ng is not recognized.
I have also tried:
sudo apt purge ng-common ng-latin
sudo npm install -g @angular/cli

and it didn't work either.
Those are the versions I have installed:
npm --version: 3.5.2
node --version: v8.10.0
+ @firstname.lastname@example.com
Visual Studio Code: 1.45.1
Chromium 83.0.4103.61 snap
Ubuntu 18.04.4 LTS

Comment: I've had exactly the same problem for 16.04 LTS https://stackoverflow.com/questions/51603464/ng-serve-issue-on-ubuntu-16-04
Answer: Maybe your path doesn't include the location of the global node_modules folder.
Try to find the install location of @angular/cli (possibly in /usr/local/lib/node_modules).
To add this folder to the PATH environment variable, add to your ~/.bashrc:
export PATH="/usr/local/lib/node_modules:$PATH"

After a shell restart you should be able to issue the ng command.
To know which ng are you using, issue the command:
which ng

Comment: Alessandro, I did it as you suggested, but it didn´t work. It still don't recognize the "ng" command.
Comment: Can you find the ng executable using something like `find / -executable -type f -name ng` (you may need sudo)? If there is a match, try running it using the complete path
Answer: This seems an issue that can have several causes. In my case I could solve it by using alias:
alias ng="/home/mario/node_modules/@angular/cli/bin/ng"


How can I hide a nodereference url link for users who have already created a node

Question: I am working on a job listing site and wants users to be able to apply for jobs on the site.
I created 2 content types "Job posting" and "Job Application".
I used the nodereference_url module to add an apply now link on the job posting node that directs the user to the "job Application" form.
This works fine but i would like to make each user to be able to apply for a particular job only once.
Is there a way i can achieve this with my current setup? Is there a different way to go about this that will give me the desired result?
Thank you for the help
Comment: It is a good idea to make the title of your question something that relates to the question itself otherwise it's harder to get answers. For example this question might have title something like "How can I hide a nodereference url link for users who have already created a node". Then people who know things about nodereference url, link hiding, etc. will be more likely to click into your question and possible answer it. The current title of this question is completely unrelated to the actual question so you will likely get less interest from the right people.
Answer: One solution that comes to mind includes using the nodereference_url_create_link function that is included in the Node Reference URL Widget module. From the documentation of the specific function:
/**
 * Helper function for themers to easily create a link.
 *
 * This function should be used in custom themes, rather than making manual
 * links because it first checks a user's access before showing the link. If
 * the user does not have access to create the node then an empty string will
 * be returned.
 *
 * @param $node
 *   The node object that will be referenced.
 * @param $field_name
 *   The name of the Node Reference field.
 * @param $type_name
 *   The name of node type that contains the Node Reference field.
 * @param $attributes
 *   Optional. An array of additional attributes to add to the link.
 */

You can use this in the node.tpl.php file for the Job Posting content type (which should be along the lines of node--job_posting.tpl.php if you're in D7 or node-job_posting.tpl.php for D6). The outline of the process should be as described below:

Hide the field at the top of your template file (you will render it later on if the user did not apply for the specific job).
Check if the user has already created an application node that references to the current posting.

The first step can be easily implemented by writing something along the lines of:
hide($content['YOUR_FIELD_NAME']);

at the top of your template file. Use a dpm($content); first to make sure that you are hiding the right field.
The second step is a bit trickier. The most elegant way that comes to mind is to use the Corresponding Node References module so that when you create a reference from the application to the posting, a corresponding reference from the posting to the application is also created (this can also be useful if you want to show all the applications that were created for a specific posting in the posting's page).
After you have "linked" the posting and the application with CNR, all you need to do is check if the author of the other postings is the logged in user. Specifically, you can use the node reference array in the $node object to get the referencing applications with node_load_multiple and then with a foreach loop compare each $node->uid against the uid of the logged in user.
There is a blog post in Drutácora that describes a similar process and includes relevant code snippets (it's not in English but you should get the basic idea from the code).


Is it possible to record direct from an amp to Audacity?

Question: Recording my bass amp's output via an external microphone results in subpar sound quality. Is it possible to record direct to my computer (I use Audacity for recording audio) from my amp?
Comment: Technically you could, IF you computer provides an Audio Input channel, which many no longer do today. So an audio-interface as mentioned by @Tetsujin is the option. // AND your amp needs to provide a line out. Which amp do you use? // HOW do you record with an external mic at the moment?
Comment: Thank you. // According to the manual there is a Rec out for recording. However, there is a chance to have mismatching voltages/impedances. I'm sure someone else here has more details on it. In principle a stereo cable from Amp to Recording device would do. // In the recording there is both noise (usually mismatch of impedances, or bad levels) and some hollow sound from comb effects. Once peer reviewed, you can find some links here in this tag https://music.stackexchange.com/tags/microphones // But: HOW do you connect the Mic to cour computer at the moment? Is there an input?
Comment: Ok, thanks, almost got it. Which laptop model do you use?
Comment: In your sample, I heard room sound that was not flattering to your tone. If you're going to mic your amp, put the mic a few inches from the speaker. You may have to turn the amp down to avoid overloading the mic or laptop input.
Comment: Yeah, I wish! To have that kind of talent...
Comment: @MS-SPO: Acer Aspire 5
Comment: Have you actually tried this?
Comment: @MS-SPO My amp is a Micro Cube Bass RX; my terrible-sound-quality recording is done by micing that with a Shure microphone. Example of the poor sound quality can be heard here: https://ramblingnotesofageezer.substack.com/p/name-that-tune-bass-riddle-18-bb6
Comment: @MS-SPO: The mic is attached to the laptop with a cable; I start recording in Audacity, and aim the mic at the amp
Comment: @KurtGibson: Thanks for that pointer, Kurt. I'll try it next time. BTW, I still remember the homerun you hit in the world series. Classic!
Answer: Yes, you could record directly to a computer provided it has a line input (a mic input won't work). This input will likely be on an 1/8" jack, which will require an adapter to accommodate an amp's 1/4" line output. Getting levels set properly, without prominent background noise or distortion, could be a challenge. 1/8" connectors are also quite fragile. Catch your foot on the cable just once, and you could easily destroy the input jack.
Why hassle with it? Just buy an audio interface. Keep it simple: buy a USB audio interface with two input channels (even one would do it) . Connect your bass amp's line output (1/4" or XLR) to the interface. Set your levels. Record away. Even a cheap USB audio interface should give you excellent sound quality.
For example: https://www.sweetwater.com/store/detail/ScarSG3--focusrite-scarlett-solo-3rd-gen-usb-audio-interface
Some interfaces (like the Scarlett above) have an instrument input, which changes the input impedance to better match an electric guitar or bass. You could then plug directly into the interface if you want the pure, direct sound of the instrument. Monitoring becomes a bit trickier with this setup, as you'll now have latency (delay) to deal with.
In short: unless you've already blown your music toy budget, there's no reason to record directly into your computer.
Answer: Thanks for answering my detailed comments. Now I can show you more clearly what to do. You need:

a stereo cable, perhaps a y-cable, which splits stereo into two mono lines
an attenuator
perhaps some adapters.

Your external microphone will be replaced/bypassed by this setup.
Manuals: amp , laptop
Direct connection, output from amp
Your amp has a so called line-out (REC-OUT), which is intended to record the signal directly, i.e. bypassing the speaker. The options from the manual also shed some light on the kind of connections you need to make:

The easiest thing you can do is using connctor "4" and draw a stereo cable to a stereo recorder (old fashioned tape, nowadays digital recorder) ... which you probably do not have. So let's look at the computer, next.
About sound quality: the block diagram suggests that you bypass output amp+speaker via REC-OUT. So besides nuances from distortions and accoustics the sound will probably be "almost the same".

Notebook, direct conenction
I assume this is where you attached your external micro:

However, you'll encounter some problems in trying to do so.
Levels
Now, line-output voltage is 1 V, while mics are about 1/1000 of that. So, even if you could plug the cabel in, you'd blow up the amplifier inside your laptop.
Solution? Look for an attenuator, line-out to microphone levels.
Cable for mic-in
Now, the microphone you have most likely is mono: 1 channel, 1 line only. So you need some y-splitter (looks like a Y) as shown above at the Mixer input.
Adapters
Now, also audio connectors follow many standards. So most likely you need some adapters to just make the right mechanical/electrical connections (diameters etc.)
If you have access to a local store which sells all those things, it may be wise to ask for help there.
A word of caution: cheap will be cheap. Almost all Chinese products will fall apart after a few times of using them, especially with cables and adapters.
Comment: Listening through the computer speakers will come with some delay that may or may not interfere with your playing. But ditching one of the stereo channels and the attenuator (what kind exactly, and where would I get one?) are already bad enough ideas.
Comment: Thank you. That's why we are sometimes "picky" here :) // However there's a downside, noted in the block diagram: using REC-OUT will switch off your amps speaker. Because the headset connector is used, while recording via Audacity, you probably can only listen through your computers speakers.
Comment: Wow, this is really "above and beyond" what was expected. Fabulous! I'm going to try to transfer some points to you, if it's possible with as few as I have. BTW, I recorded the bass line from Peggy Lee's (Max Bennett's) "Fever" with the mic right next to the turned-down amp, and the sound quality was sound-years better (light years would be an exaggeration)


how do i get fields value of webform before entering into database?

Question: I want value of a hidden field of webform in custom module so that i could match it with other value from database to validate it
Answer: You can use hook_form_alter to achieve this in your custom module.
/**
 * Implementation of hook_form_alter().
 */

function your_custom_module_name_form_alter(&$form, &$form_state, $form_id) {
  // Add validation for a particular Webform node:
  if ($form_id == 'webform_id') {
    // Simply add the additional validate handler.
    $form['#validate'][] = 'mycustom_extra_validate';

    //$first = array_shift($form['#submit']);
    //array_unshift($form['#submit'], $first, 'mycustom_extra_submit');
  }
}

/**
 * Validation handler for Webform .
 */
function mycustom_extra_validate(&$form, &$form_state) {
  //condition to check validation
}

Answer: I am just giving the example how you can access hidden field in custom module,in my case i have added value to hidden field by doing custom code,you can take reference of below code:
function your_module_form_alter(&$form, &$form_state, $form_id){

 if ($form_id == 'webform_client_form_28') {

  $uid = arg(1);
   if ( arg(0) == 'user' && is_numeric($uid) ) {
       $account = user_load($uid);
       $form['submitted']['user_email']['#value'] = $account->mail;
       $form['submitted']['uid']['#value']=$uid;
   }
 }
}


Trying to access Facebook friendlist, but getting a empty friends list

Question: FB.api('/me', function(response) {
    FB.api(response.id+'/friends', function(response) {
        for (var i=0; i < response.data.length; i++) {
            FB.api('/'+response.data[i].id, function(response) {
            {

            }
            });
        }
    });
});

not able to get any list response.data[i].id the length is zero
Answer: The call to /me/friends will only return the friends which are also using your app, not all friends.
See

https://developers.facebook.com/docs/apps/changelog#v2_0


My new Fender is difficult to tune

Question: I used a cheap Epiphone Les Paul for my first 10 months of learning guitar, however I received a new Fender Stratocaster as a birthday gift recently.
When I tuned my first guitar, it only took one run through to tune perfectly (sometimes with very minor adjustments).
With my new Fender, I seem to have to go over each string 4 or more times to get them right. On the second and third iterations for example I'll find the strings almost a whole step off what I tuned them to on the previous iteration.
Is this normal? If so, has it got something to do with the 6-in-line headstock vs the 3+3 on my Les Paul, or the flat headstock vs the angled one? Maybe it's just the brand of guitar that contributes to this? Or maybe I'm just tuning my Fender incorrectly / inefficiently compared to my newbie tuning of the Les Paul.
Answer: If your strat has the tremolo floating (that is, with the back suspended just above the body - not flat against it - so it can rocked freely in both directions) then the bridge moves slightly as each string is adjusted.  So it may take a few more goes to tune up.  This can be especially so if you've changed all the strings at once or swapped to a different string gauge.
Four or more tweaks for each string is quite a lot though - it may just be that the strings are new and need a little time to settle.
(Incidentally when I had a cheap strat copy I used to have the tremolo springs, in the back, tightened up fully so the tremolo wasn't free floating. Tuning was a lot quicker that way, as well as suiting what I wanted to play.  But most strat owners wouldn't want to do that as it makes the tremolo less useful!)
Comment: IMHO the term is not worth it on a standard strat. My first guitar was a strat copy and things got so much better for me when I locked down the trem. I still play that guitar 22 years later and the trem is still locked down. Loosen the strings and use a screwdriver to take off the large panel on the back. There should be screws going through a metal claw and into the wood near the neck. Tighten those as much as you reasonably can. Put the cover back, tune up, unscrew the trem arm and keep it somewhere safe in case you want it later.
Comment: If taking longer to tune the guitar is a bi-product of the floating bridge then I'm fine with that - can't believe I didn't think of it :-)
Comment: I would say the second paragraph (new strings) could well be the most relevant - even with the floating bridge, the tuning shouldn't be so unstable as to require going over the strings four times. I suggest giving the strings a gentle stretch to help them settle in - put a couple of fingers under each string in turn and pull it away from the fingerboard a few times. Carefully on the thinner strings of course!
Comment: Trem arms are like socks & biros... you cannot just keep them in a drawer & expect them to still be there next time you look ;) [Owner of a 64 Strat & a JP Squier since new.. neither with surviving trems]
Comment: I have tightened the springs on mine so that the trem is locked fairly hard against the body. I can still use it though - only to loosen the strings of course but it's at a happy medium of locked enough to make the tuning easy, vs. loose enough to use the trem.
Comment: Ohh you're probably onto something there, that is a very good point. Is there something I can do to mitigate the bridge movement while I tune the guitar?
Comment: I had mine with the tremolo springs fully tightened, so it was flat and hard against the guitar body and acted more like a solid bridge. BUT I do not recommend this for most people as the tremolo won't work freely that way. I would suggest you stick with it as it is first, and don't try drastic changes to the setup yet. Slight bridge movement is the beauty of having a tremolo!
Answer: There are a few possibilities:

Tremolo - as Andy says
The nuts which hold the tuning pegs in can come loose meaning the peg can flop about in its hole. You'd hope this isn't the case on a new Fender but it's a possibility.
The way the strings are wound over the tunung pegs:  They should be neat with each wind of the string next to the other, as opposed to all crossed over and anarchic. The reason is if it's all crossed and in a knot that allows flexibility (elasticity) in the string and it'll be hard to tune, and also might sound strange
Tight nuts. Yes ma'am. If the grooves in the nut are too tight for th strings you're using, the strings can get causght in the nut with means the tension you're applying with the tuning peg isn't evenly transferred to the string over the fretboard - the bit between the nut and the peg might take more tension until you try to play something, then it evens out and goes out of tune. Again you'd hope this is fine on a new guitar but it might be worth running the relevant string through the grooves in the nut to check it runs free. If it catches or is tight, it might just need lubricating: Graphite powder (dust from sanding a pencil lead) will do the trick.

These others probably hopfully don't apply to a new guitar, but just to be complete:

On a strat, the hex bolts which hold the individual bridges can end up poorly aligned so that the bridge sits crooked. It's possible for them to rest on just one bolt making the whole thing unstable, or even if they're just crooked you can get odd results as the string doens't sit properly in the saddle.
Old/mucky strings - the muck affects the weight of the string and thus the tuning.
Answer: The trem will stay in tune just fine on any Fender model from the Squier affinity on up. 3 straight springs for up to .11 guage strings. Yes you can go all Hendrix on it.
I'm going to take a wild guess and say you have a Mexican standard Stratocaster. The problem is the string trees. They are screwed flat to the headstock, but they should have 1/4" spacers under them. This  creates too much downward pressure and the strings will get struck. Get better string trees or use small nuts as spacers.
To keep a floating trem in tune smack the bar forward before tuning. Make sure your last turn on any tuning peg is up. When the guitar goes out of tune smack the bar forward and  it will jump back into tune.
Cut your strings 2.5" past the tuning post, stick the  end in the hole, one wrap over the cut string end, 2 wraps under. Any more will create slack
Btw-Always tune the guitar to the same tuning and pitch, you want to play slide with an open tuning, use your old guitar. The guitar gets used to a tuning and likes to stay there.

My new Fender is difficult to tune


Differential 2-forms in $\mathbb R^3$.

Question: I have a question regarding differential 2-forms in $\mathbb R^3$.

Consider the $\Phi: \mathbb R^2 \to \mathbb R^3$ given by $\Phi(x,y):= (x,y,0)$

EDIT: The full example is here.

Is it essential that set $A:=[-1,1]\times[-1,1]$, would $[0,1]\times[0,1]$ not work?
Also why is the 2-form $a^2(dx\wedge dy)+b^2(dx\wedge dz)$? I don't understand why $a$ and $b$ have been squared in this formula?

Apologies if this question is completely trivial. Any help would be great!
Comment: Would you please add the reference of this example if any.
Answer: I'm guessing (lacking other information) that the author chose $a^2$ and $b^2$ so that they were both nonnegative. It's just a shorthand way of saying it. It may also be that the author wants things whose derivatives are basically $a$ and $b$ (up to a constant). Hard to know without further context.
As for choosing the set $A$, you could choose any subset of the plane and define the 2-form, but presumably in the lines that follow your excerpt, the author will be doing something with that subset. For instance, it may matter that the subset includes the origin in its interior, and $[0, 1] \times [0, 1]$ wouldn't have that property. Without further information, I can't help you.
But as long as $A$ is a subset of the plane, the function $\omega$ can be defined on $A$.
Comment: Ah I see. Thank you for your help. I've added the rest of the example if that helps add context.
Comment: Yep. Looks as if in this case the $a^2$ was just "something easy to integrate" and the domain was "the first one I thought of", although it forces you, during the antiderivative evaluation, to actually plug in the "bottom" value $(a = -1)$ and check that the sign is such that you get double the answer rather than the two parts cancelling to zero, which is always good practice.

Differential 2-forms in $\mathbb R^3$.


How to specify a library project in proguard

Question: I am using google play services library in my android project. I am not including it as a jar but as a library project in the properties of my project. Now I am getting an error
Unable to execute dex: method ID not in [0, 0xffff]: 65536
To solve this a stackoverflow result to include the library in proguard.
I have included library jar files in proguard by specifying the path of the jar file.
How do I include a library project in proguard.
Please help
Answer: follow the tutorial here to get idea about how to use libraries and exception rules for progouard
http://www.intellicode.in/using-proguard-for-android-project/
Answer: You can't just "include a library project" in ProGuard. You have to add specific rules. The rules for Google Play Services are shown here
-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

These go in your proguard-project.txt file in your project root.
Comment: my problem is that my app exceeded 65536 methods and goole play services library alone has 30k methods or so. The reason I am using google play services library is to implement google maps in my app. I want proguard to strip all unused methods from this library. The above mentioned code is to prevent proguard from stripping right?


Open close  after every 2 records?

Question: I have this code:
 for ($i = 0; $i < count($listings); $i++)
    {
                if ($i != 0 && $i%2 == 0)
                   {
                      $endul .= $arr[$i] . '

';
                   }
                   else
                   {
                      $endul .= $arr[$i];
                   }

And am trying to close a  after 2 records and then re-open for the next 2 records, etc... So far it seems like the code is working "somewhat" properly BUT it's taking the first 3 records and then closing the UL and not just the first 2?
Answer: This is my first StackOverflow post so bear with me :)
The problem is with this condition here:
if ($i != 0 && $i%2 == 0)

If you trace the values of $i as you go through the loop, you'll get the following:
$i = 0 ==> false
$i = 1 ==> false
$i = 2 ==> true
$i = 3 ==> false
$i = 4 ==> true

So it's printing out
    $arr[0] .
    $arr[1] .
    $arr[2] . '

' .
    $arr[3] .
    $arr[4] . '

'

In order to solve this problem, you need to change the if condition
if ($i%1 == 1)

Hope this helps!
Answer: You can try grouping them in chunk first
$group = 2;
$listings = range("A", "Z");

foreach ( array_chunk($listings, 2) as $set ) {
    printf('
%s
', implode(array_map(function ($v) {
        return sprintf('
%s
', $v);
    }, $set)));
}

Or
foreach ( array_chunk($listings, 2) as $set ) {
    printf('
');
    foreach ( $set as $v ) {
        printf('
%s
', $v);
    }
    printf('
');
}

You would get same result

A

B

C

D

E

F

G

H

I

J

 .......

Answer: Well, 0 is the first record and your if statement excludes it specifically. So it won't close until after the third record, which is $i = 2.
Example:
for ($i = 1; $i < 10; $i++) {
    if ($i % 2 == 0) {
        echo '
';
    }
}

This works fine for me.
Comment: when i changed it, it closed the  every record ;(
Comment: doesnt cloe the  until record #4 now ??
Comment: I've edited my response. The code here is minimal and works. If it doesn't work, something is wrong elsewhere.
Comment: i took your if statement inside and that worked???  hmm, not sure why but it did! :)
Answer: Change this line:
$endul .= $arr[$i] . '

';

To this:
$endul .= '

'.$arr[$i];

Comment: Giving me the same 3 records first :(
Comment: Are you iterating over the right array? In the for loop condition you are using `$listings`, but inside the loop you are using `$arr`. Can you post example contents of those two arrays?
Answer: This is Perl or PHP, right?  Maybe tag it with those languages in the future?  Anyway, I suspect your problem is that your array begins with a zero index.
I'm speculating, but let's assume your @arr array contains elements with HTML markup

whatever

line items.
Let's count up your elements:
Element 0 - Do I pass the test? No: add first line item, but don't add close, rule and open.
Element 1 - Do I pass the test? No: add a second line item, but don't add close, rule and open.
Element 2 - Do I pass the test? Yes: add the third line item, and then add close, rule and open.
Element 3 - Do I pass the test? No: add new first line item, but don't add close, rule and open.
Element 4 - Do I pass the test? Yes: add new second line item, and then add close, rule and open.
Element 5 - You know the pattern: we repeat with groups of two line items before closing.
Because this code starts with zero, we have the extra case with zero and two in the first group of items.
The modulus of the index could test for odd instead of even:
if ($i%2 == 1)

And I think that test would build the format the way you want, where you'd add the "record close" markup after each odd element.  I'm assuming you have to logic outside of the loop to do the final close markup.  Of course you're still going to have an extra empty unordered list container in the case of the final element being odd, but maybe add something for that?
Answer: This is the best approach:
    $rows = range(1,10);
        $i=1;
        echo "
";
        foreach($rows as $key=>$row)
        {
            echo "
$row
";
            if($i%2==0)
            {
              echo "

";
            }
            $i++;
        }
       echo "
";

Open close  after every 2 records?


Get block id in block theme template

Question: I'd like to be able to print the block id/number of my custom block in its template. I feel like these must exist because Display Suite has a token for it: [block_content:id].
Like a url to edit a block is, it goes to the edit form: block/17
How do I get that 17 in the twig template? Looking in block.html.twig, I don't see anything about a block's number.
Answer: You find the block_content entity in the template variable elements to get the ID:
block.html.twig:
{{ elements.content['#block_content'].id() }}

Comment: For Drupal 9 it should be `{{elements['#id']}}`
Comment: @yunzen, the id in the top level of the block render element is more likely the id of the block itself, not of the block content entity the question is about.
Comment: yunzen's answer worked perfectly for me

Get block id in block theme template


Google API v3 PHP Sessions lose their data

Question: I am building a Web application that uses the Google API PHP client library. The application allows the user to retrieve analytical data from Google Analytic Accounts. Everything works how it should apart from the following of which I am going to explain.
Step 1
The user selects an account name in the form and submits the form from the accounts.php page. The account id for that account is then saved in a SESSION variable. Once this is done the accounts.php page redirects to the simple.php page using location header.
Step 2
The simple.php page displays a Connect me link which the user then presses to log them into Google in order to retrieve the data from analytics's. This data retrieves all the accounts. These accounts then run through a loop against the account id Session variable (in order to retrieve results for the correct account that the user selected in the accounts.php page).
The problem
The problem is that when Google redirects back to the simple.php page all the session data that I stored before hand in the accounts.php is lost. Even if I store the account id in a cookie. I think the Google PHP client library is wiping my session data somehow in the backend. I have tried so many ideas and all of them dont seem to work. Strangely enough though if I log out, or go back to accounts.php and try again, the Session variable holds its account ID data after the Google redirect. So confused!
I hope I have made that as clear as possible
<?php
session_start();

 /*
if ($_SESSION['test'] != "logged" || $_SESSION['test'] == null) {

header('Location: http://www.xxxx.co.uk/');
die("Redirecting to home page");

}*/

header("Accept-Encoding: gzip");
header("User-Agent: gzip");
require_once 'src/apiClient.php';
require_once 'src/contrib/apiAnalyticsService.php';
$client = new apiClient();
$client -> setApplicationName("Google Analytics PHP Starter Application");

$client -> setClientId('xxxx');
$client -> setClientSecret('xxxx');
$client -> setRedirectUri('http://www.xxxx.co.uk/simple.php');
$client -> setDeveloperKey('xxxx');
$client -> setUseObjects(true);

$service = new apiAnalyticsService($client);

$table = array();

if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
$client -> authenticate();
$_SESSION['token'] = $client -> getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
$client -> setAccessToken($_SESSION['token']);
}

if ($client -> getAccessToken()) {

$accounts = $service -> management_accounts -> listManagementAccounts(array("fields" => "items(id,name)"));
print "Logout";
//$accounts = $service -> management_accounts -> listManagementAccounts();

foreach ($accounts->getItems() as $account) {
    //var_dump($_SESSION['account_number']);
    if ($account -> getId() == $_COOKIE["test"]) {

        echo "
" . $account -> getName() . "
";
        $props = $service -> management_webproperties -> listManagementWebproperties($account -> getId());

        //foreach ($props->getItems() as $property) {

        $profiles = $service -> management_profiles -> listManagementProfiles($account -> getId(), "~all");

        foreach ($profiles -> getItems() as $profile) {
            $counter++;
            $table[$counter]['name'] = $profile -> getName();

            echo "
" . $profile -> getName() . "
";

            /*
             echo "
Profiles
";
             echo "
";
             var_dump($profile);
             echo "
";*/

            // Direct
            $data = $service -> data_ga -> get("ga:" . $profile -> getId(), $_SESSION['startdate'], $_SESSION['enddate'], 'ga:visits', array("segment" => "gaid::-7"));
            // Non Paid
            $data2 = $service -> data_ga -> get("ga:" . $profile -> getId(), $_SESSION['startdate'], $_SESSION['enddate'], 'ga:visits', array("segment" => "gaid::-5"));
            // Paid
            $data3 = $service -> data_ga -> get("ga:" . $profile -> getId(), $_SESSION['startdate'], $_SESSION['enddate'], 'ga:visits', array("segment" => "gaid::-4"));
            // Refferal
            $data4 = $service -> data_ga -> get("ga:" . $profile -> getId(), $_SESSION['startdate'], $_SESSION['enddate'], 'ga:visits', array("segment" => "gaid::-8"));

            /*
             echo "
Non Paid Data
";
             echo "
";

             //var_dump($data);
             echo "
";
             echo "
Paid Data
";
             echo "
";

             //var_dump($data2);
             echo "
";
             echo "
Search Data
";
             echo "
";

             //var_dump($data3);
             echo "
";
             echo "
Referral Data
";
             echo "
";

             //var_dump($data4);
             echo "
";*/

            $results1 = $data -> getTotalsForAllResults();
            $results2 = $data2 -> getTotalsForAllResults();
            $results3 = $data3 -> getTotalsForAllResults();
            $results4 = $data4 -> getTotalsForAllResults();

            foreach ($results1 as $result) {

                echo "Direct Traffic " . $result . "
";
            }
            foreach ($results2 as $result) {
                $table[$counter]['nonpaid'] = $result;
                echo "Non Paid Traffic " . $result . "
";
            }
            foreach ($results3 as $result) {
                echo "Paid Traffic " . $result . "
";
            }
            foreach ($results4 as $result) {
                $table[$counter]['refferal'] = $result;
                echo "Refferal Traffic " . $result . "
";
            }

        }

    } else {

        echo "This is not working";
        var_dump($_COOKIE["test"]);
    }

    $_SESSION['token'] = $client -> getAccessToken();

}

echo "
";

        foreach($table as $data)    {

            $total = $data['nonpaid'] + $data['refferal'];

            echo "
".$data['name']."	".$total."
";

    }

    echo "
";
} else {
$authUrl = $client -> createAuthUrl();
    var_dump($_COOKIE["test"]);
            print "Connect Me!";
}
?>

Comment: Check that the redirect URI you have supplied is within the scope of your session cookie. For example, you specify `'http://www.xxxx.co.uk/simple.php'`, but if you accessed the page originally via `'http://xxxx.co.uk/simple.php'` (no `www.`) then the cookie maybe out of scope.
Comment: @DaveRandom I am not back in work till tommorow, so I will not be able to check, but if your right I may have to hunt you down and give you a big kiss. Just done some small tests my other site and it seems promising.
Comment: Is there any documentation on this issue. I never know that www. affected Sessions
Comment: It's not sessions specifically, it's generally cookies - you might find [this](http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Path) to be worth a read. You can control the properties of the PHP session cookie using [`session_set_cookie_params()`](http://php.net/manual/en/function.session-set-cookie-params.php). It is possible to set the domain to `.xxxx.co.uk` (leading `.`) so it will be available on the root domain and all its subdomains. Let me know how you get on :-)
Comment: @DaveRandom That worked perfectly, I now have a htaccess file that redirects my site to www. So I wont be getting this problem. I would give you a correct answer or vote you if you want to put it as a answer
Answer: Check that the redirect URI you have supplied is within the scope of your session cookie.
For example, you specify 'http://www.xxxx.co.uk/simple.php', but if you accessed the page originally via 'http://xxxx.co.uk/simple.php' (no www.) then the cookie may be out of scope.
This does not only apply to sessions, but also to cookies in general - you might find this to be worth a read. You can control the various properties of the PHP session cookie using the function session_set_cookie_params(). It is possible to set the domain to .xxxx.co.uk (leading .) so it will be available on the root domain and all its subdomains.


How can I add a "::" operator to my VIM syntax highlighting file?

Question: I am using a language embedded inside of Scala that has a :: operator. I would like to modify my scala.vim syntax file to recognize this new operator.
This is what I've tried (the first line works fine, but I don't know how to add the :: operator to it):
syn match   COperator "[&|~><!)(*#%@+/=?:;}{,.\^\-\[\]]"
syn match   COperator "\v::"
syn match   COperator "\v\:\:"
hi link COperator Special

Any advice?
Comment: It looks like that first line pattern will match `::` as it is. It does not limit the number of characters, so `::` will be matched by the presence of the single `:` inside the outer `[]` character class.
Comment: So, why do you want to match `::` explicitly, when you are already highlighting each `:` in it as operator, as @MichaelBerkowski pointed out?
Comment: `":\{2,\}"` Means "matching all series of `:` character if 2 or more". it will match `::` , `:::` , `::::` , `:::::` , …
Comment: @Chris you should add what you did as an answer to the question and except it.
Comment: Hmmm, "::" doesn't change colors. ":" does, ":=" does, but not "::". Does scala.vim override the pattern "::"? What does (syn match scalaOperator ":\{2,\}" "this is not a type) do? (if I comment it out, I get "::" to work, but I'm not familiar enough with regex to pinpoint "::", or Scala to know when "::" shows up).
Comment: Thank you.  By renaming that to `syn match COperator ":\{2,\}"`, I get "::" to syntax highlight as desired.
Comment: @Kazark thanks for poking me, I didn't know if that was kosher to do or not.
Answer: An existing scalaOperator ":\{2,\}" was causing all sequences of : to match (if there are two or more series of :), overriding my own syn match COperator statements.
The solution to get :: to match as a COperator was to simply rename the scalaOperator that matches series of : to a COperator:
syn match COperator ":\{2,\}"

Summary: check for existing match rules that override your own match rules.


Implementation of adding SqlCeParameters in a loop

Question: I'm trying to add into table multiple values from string arrays dateOperation typeOperation bought and sold which have equal array length
This is the core I tried and it works but its not with a loop
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
    SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;

    cmd.Parameters.AddWithValue("@date", dateOperation[0]);
    cmd.Parameters.AddWithValue("@type", typeOperation[0]);
    cmd.Parameters.AddWithValue("@bought", bought[0]);
    cmd.Parameters.AddWithValue("@sold", sold[0]);

    connection.Open();
    cmd.ExecuteNonQuery();
}

But this code snippet with loop isn't guess I'm missing something in the syntax
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
    SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
    cmd.CommandType = CommandType.Text;
    cmd.Connection = connection;

    for (int i = 0; i <= bought.Length; i++)
    {
        cmd.Parameters.AddWithValue("@date", dateOperation[i]);
        cmd.Parameters.AddWithValue("@type", typeOperation[i]);
        cmd.Parameters.AddWithValue("@bought", bought[i]);
        cmd.Parameters.AddWithValue("@sold", sold[i]);
    }

    connection.Open();
    cmd.ExecuteNonQuery();
}

Because sometimes dateOperations , typeOperation , bought and sold are not always the same length of array the code works fine but it gives me an error if the array is less than 4 length the table recieves data fine but the error is screwing my program how to fix it or how to make an exception
"Parameterized query expects a parameter value which was not supplied."
string[] dateOperation = new string[4];
            string[] typeOperation = new string[4];
            string[] bought = new string[4];
            string[] sold = new string[4];

            for (int i = 0; i <= 3; i++)
            {
                if (tb[i].Text != "" && Odate[i].Text != "")
                {
                    dateOperation[i] = Odate[i].Text.ToString();
                    typeOperation[i] = type[i].Text.ToString();
                    bought[i] = tb[i].Text.ToString();
                    sold[i] = BGN[i].Text.ToString();
                }
            }

            string connectionString = @"Data Source=C:\Users\FluksikartoN\Documents\BFDB.sdf;Password=******";
            using (SqlCeConnection connection = new SqlCeConnection(connectionString))
            {

                    SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = connection;
                    cmd.Parameters.AddWithValue("@date", DbType.String);
                    cmd.Parameters.AddWithValue("@type", DbType.String);
                    cmd.Parameters.AddWithValue("@bought", DbType.String);
                    cmd.Parameters.AddWithValue("@sold", DbType.String);
                    connection.Open();
                    for (int i = 0; i < bought.Length; i++)
                    {
                        cmd.Parameters["@date"].Value = dateOperation[i];
                        cmd.Parameters["@type"].Value = typeOperation[i];
                        cmd.Parameters["@bought"].Value = bought[i];
                        cmd.Parameters["@sold"].Value = sold[i];
                        cmd.ExecuteNonQuery();
                    }

Answer: You need to add parameters to the command first (before the loop). Then in the loop set the values of the parameters and execute the command:
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Operations (date, type, bought, sold) VALUES (@date, @type, @bought, @sold)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;

cmd.Parameters.Add("@date", DbType.DateTime);
// other parameters

connection.Open();
for (int i = 0; i <= bought.Length; i++)
{
    cmd.Parameters["@date"].Value = dateOperation[i];
    // other parameters
    cmd.ExecuteNonQuery();
}

Comment: it works fine now but i need just a little more information and ill edit


Utilizando a função lm, do R, para resolver o problema autocorrelação

Question: Estou trabalhando com a função.
lm(y~x)
regressão simples, devido a testes verifiquei autocorrelação, logo a blibliográfia indica uma transformação.Algo parecido com:
Y=B1*(1-p)+B2(X-(p*X[-1]))
Que seria a aplicação da correção P no modelo, sendo que P é conhecido por mim.
Alguém conhece uma técnica de correção de autocorrelação, próximo a função apresentada?
Obrigado
Comment: Se existe autocorrelação nos dados, porque não utilizar o [modelo ARMA](https://en.wikipedia.org/wiki/Autoregressive%E2%80%93moving-average_model)?
Comment: Marcus, é uma seria multivariada e não sei como programar para mais de uma variável explicativa. más é bem possivel ser resolvido com um processo ARIMA 2,1,2
Comment: Então usa um VARIMA (Vector ARIMA). Sugiro não tentar reinventar a roda.
Comment: Como programaria isso no R?
Answer: Se isso for uma serie temporal, o melhor é trabalhar com https://cran.r-project.org/web/views/TimeSeries.html, mas se você realmente quiser fazer isso, então:
crie uma coluna de atrasos (lag) e do valor p
lag<-x
lag<-c(NA,test)
P<-rep.int(p, length(test))
exemplo:
<code>> te<-1:10
> te
 [1]  1  2  3  4  5  6  7  8  9 10
> te<-c(NA,te)
> te
 [1] NA  1  2  3  4  5  6  7  8  9 10
>p<-rep.int(0.3, length(te))
</code>
E fazer fazer a lm para estimar B1 e B2:
<code>lm(y~(1-P)+(X-(P*te))
</code>
Só cuidado, pois todas as colunas deverão ter o mesmo tamanho.


Question on Subgroups and Left Cosets

Question: Here is an unanswered exercise from class notes.

For the group <{$i,-i,1,-1$},*> and a subgroup H where $|H|$ = 2. Find the left cosets of G induced by H. G={$i,-i,1,-1$}
Answer: Besides to another post, you may think of $G$ as one of the subgroups of the quaternions of order $8$ ($Q_8$). Here is the lattice of $Q_8$:

We see that the only possible subset of $G$ of order $2$ is indeed the subgroup $H$. Since $|G|=4$ so $[G:H]=2$. There is nothing to do when we are finding $gH,~g\in G\cap H$. Indeed $$-1H=H, +1H=H$$ So try focusing on $gH,~ g\in (G-H)$ that are: $$+iH, ~-iH$$
Answer: It can be found that H={$1,-1$} is a subset of G and it's found that <{$1,-1$},*> is a subgroup of G. An example of such that is not a subgroup is when $\underset{2}{H}$ = {$1,i$}. Although $\underset{2}{H}$ is a subset of G, it is not closed under the group operation.
Def: Coset - "set composed of all the products obtained by multiplying each element of a subgroup by one element of the group containing the subgroup"
A Subgroup of <{$i,-i,1,-1$},*> is <{$1,-1,*$}>
Left cosets are:
1*{1,-1} = {1,-1}
-1*{1,-1} = {-1,1}
i*{1,-1} = {i,-i}
-i*{1,-1} = {-i,i}
I'm sorry if it's hard to read. I'm not familiar with the formatting.

Question on Subgroups and Left Cosets


Problema com overflow-x e overflow-y no css

Question: Boa tarde, tudo bem?
Eu preciso que uma table fique com scroll no eixo x, caso a largura da table seja maior que a largura do container. Se eu fizer isso, vai funcionar:
overflow-x: auto;
overflow-y: hidden;

Mas eu preciso que o overflow-y seja visible, pois no fim da tabela tem uma select, e quando eu abro a select ela aparece cortada.
Se eu colocar:
overflow-y: visible;

Ele coloca um scroll na vertical também.
Se alguém tiver alguma luz, agradeço desde já.
Comment: Olá! Testei no [JSFiddle](https://jsfiddle.net/ahkayhat/) isso que você deseja fazer, e funcionou. Caso eu esteja errado, por favor esclareça mais sua dúvida.
Comment: Olá, tudo bem? Desculpe, esqueci de esclarecer algumas coisas... estou usando o [chosen select](https://harvesthq.github.io/chosen/). A select padrão funciona normalmente mesmo, já o chosen não dá certo.
Comment: Aqui um exemplo da minha dúvida [JSFiddle](https://jsfiddle.net/rogeralbi/ahkayhat/2/)
Comment: Esse foi o mais perto que cheguei por enquanto, dá uma olhada [JSfiddle](https://jsfiddle.net/rogeralbi/88246m6c/1/) @Lioo
Comment: Certo, vi seu código e está fazendo exatamente o que você quer, não é? Não está mais cortando o `select`. Se não for isso, o que você deseja fazer?
Comment: Era isso mesmo, mas daí ele não respeita o scroll lateral, que eu precisava :/
Comment: Ah, então você deseja que o `select` **não acompanhe** o scroll lateral, é isso? Que suma da tela depois do scroll?
Answer: Se foi o que entendi, você deseja que o select não acompanhe o scroll lateral.
Nesse seu caso, você pode fazer isso removendo o position: absolute; do estilo do select.

$('#select1').chosen();
.wrapper {
  /* colocar tudo dentro de um wrapper*/
  position: relative; /* com posicionamento relativo */
}
#container1{
  position: static; /* Adicionar position static no container com overflow */
  border:1px solid black;
  height:100px;
  overflow-x:auto;
  overflow-y:visible;
}

table {
  width: 2000px; /* adicionar uma largura para mostrar o scroll no eixo x */
}

#select1_chosen {
  /* o chosen cria um #id-do-elemento_chosen */

}
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.6.2/chosen.min.css" rel="stylesheet"/>

          Teste
          Teste2

          Info
          info
          Info
          info
          Info
          info

          Info
          info

      <select name="" id="select1">
          <option value="option 1">Op 1</option>
          <option value="option 2">Op 2</option>
      </select>

Jsfiddle: Exemplo aqui
Comment: Mas daí ele causa o scroll na vertical, e esse era o problema inicial.


Powerapps UpdateIf with multiple conditions

Question: I am trying to use an UpdateIf function in Powerapps to update a record in Sharepoint based on two conditions. However, the second condition seems to be ignored. The function is as below:
UpdateIf('Demo Stock';(PartNumber = ThisItem.Code && Serial = ThisItem.Serial);{ItemStatus: "Available"})

The update happens but there are multiple instances where ParNumber value is the same in the SharePoint List and all instances are being updated insted of only the one where bothe PartNumber and SerialNumber match.
Any ideas why?
Thanks,
Steven
Answer: Did you get this figured out? I'm guessing your issue is the extra ';' you've got in the statement.
Try the following:
UpdateIf('Demo Stock',PartNumber = ThisItem.Code && Serial = ThisItem.Serial,{ItemStatus: "Available"})
I hope that helps! Meanwhile, your question answered mine on how to achieve AND for two conditions (&&). :-)
Lucinda
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead); instead, provide [answers](https://stackoverflow.com/help/how-to-answer) that don't require clarification from the asker.
Answer: Try this:
UpdateIf('Demo Stock';And(PartNumber = ThisItem.Code; Serial = ThisItem.Serial);{ItemStatus: "Available"})


Playing on white notes only

Question: My keyboard has a transpose function which lets me transpose its keys up and down a given number of semitones. This consists of a button with # and a button with b.
So lets say I'm playing a tune where I'm playing B, A#, G#, F#, F, D# C#. How do I use the transpose functionality so as to play this tune on the white notes only. So, the notes B, A#, G# etc will all be playable via white notes. I'd like to do this as quickly and as easy as possible each time I make up a tune with black notes in it. I don't wish to use paper to work it out but an online tool would suffice.
I play the keyboard in order to compose music.
Additionally, how many times do I press the # button in order to play a tune in E Major on only white notes?
Comment: I recommend learning to play with the black keys (in addition to learning how to transpose). Even moderate beginner-level pieces will have accidentals in them, meaning you'll quickly reach a point where being unable to play with black keys will hold you back.
Comment: Firstly, there are many pieces where no amount of transposition will allow you to perform the entire piece using only the white notes (e.g. Paint It Black).  Since you're composing your own music, you can avoid creating such a piece.  I understand you might be composing for a diatonic instrument, but if that's the case, why are you making up tunes "with black notes in it" in the first place?  Please explain!
Comment: If you're ONLY using black notes to make up tunes, they're all in pentatonic - either F#/Gb maj., or D#/Eb min. To play the tunes on white notes only, put a sticker on B and F and avoid those.                Alternatively, do the proper job, and learn your way round so you can eventually play in any key. Advantages well outweigh the disadvantages.
Comment: @Lee Kowalkowski From time to time, a new tune will magically find its way into my head. I might then wish to play it on the keyboard in other to develop it further. However, up to this point it is out of my control whether it has black keys in it or not. Then since I'm not very good on the keyboard, I can transpose to white keys so that I can experiment around my original tune by playing around on only the white notes. Does that make sense?
Comment: +1 This question is also useful for very limited instruments, like the zither, or the monotron in its *major scale* mode.
Comment: Hey, don't judge. This method was good enough for Irving Berlin. He learned to play the piano by ear using the black notes. So he played everything in Gb. He had a special transposing piano so that he could play everything in Gb and have it come out in the right key.
Answer: The buttons
Pressing the # key once will move the transposition up half a step (from a white key to a black key, or between two white keys that don't have a black key between them). So from C to E: C#, D, D#, E, that's 4 steps.
Quickly recognising the transposition required
From the question, it looks like you know about scales and keys. So you probably know that E Major has 4 sharps as a key signature, for example. The note sequence you quoted above is F# Major, which has 6 sharps. The point is, C Major has no sharps or flats, so that means you'd be playing on only white keys (except for the occasional extra accidental).
So to get to C Major, count the number of half-steps (as explained above) from the hard key you're in to get to C. Note that your instrument might not allow you to exceed 6 half-steps, so you might have to go down instead and physically play an octave above. For F# major, you can transpose up or down by 6 half-steps to get to C.
Getting used to transposition
Making heavy use of transposition functions as a beginner can be entertaining and fun, but it's certainly not very good for training your ear and fingers. You will confuse your ear into thinking that a certain key will play a certain note, and instead it's just the transposing. And also you will never learn to play on the black keys.
Comment: Actually, this collection of notes belongs to F# Major, and the note called F in the question is technically E#.
Comment: @Baz There aren't that many key signatures in common use, so in practice it doesn't take much to learn them by rote. If you want the general rule though, look at the circle of fifths.
Comment: @Tim sorry, my bad. That's what happens when you rely only on counting the sharps :P Fixing the answer.
Comment: Thanks for your reply @LS97! Recognising that the sequence of notes is from the scale of B Major does not come naturally to me. Your method would require me to learn the sharps or flats belonging to a key. I'm wondering if there is an easier way.
Comment: @LS97 - if, as you state, this is in B, there would be an E in there.No E. It's in F#,(6#) and because a key will contain one of each letter name, your 'F' will be called E#, technically. It'll be written where E is on the music.So you need to move 6 semitones-either way!!- to get to C.
Answer: Here is a chart for you:

from G flat or F sharp major go up or down 6 half-steps.
from F major go down five half-steps, or up 7.
from E major down four half-steps, or up 8.
from E flat major down three 1/2 steps, or up 9.
from D major down two 1/2 steps, or up 10.
from D flat major down one half-step, or up 11.
from B major up one half-step, or down 11.
from Bb major up 2 half-steps, or down 10.
from A major up 3 half-steps, or down 9.
from Ab major up 4 half-steps, or down 8.
from G major up 5 half-steps, or down 7.
Answer: Ok I've figured out an easy way to do this! So here are the notes I'm playing:
B, A#, G#, F#, F, D# C#
There are two semitone steps here: A# to B and F to F#. So to play on the white keys, A# and F must map to a white key that has no black key to its immediate right. So, via trial and error, you can first map F to E and if that doesn't work you can map it instead to B and see of that works.
In other words, I pressed the # key once (F->E), but I still needed to play a black note in order to play the tune. I then reset the transposition and pressed the b key 6 times (F->B) and now I can play the tune on the white keys!
My guess is that the tune is in Ab Dorian. Am I right?:
Answer: Good idea to configure the keys to C major and A minor ie the white notes saving your self 1000s of hours of practice time. Enjoy!

Playing on white notes only


Quais as vantagens e desvantagens de usar paginação e scroll infinito em sites?

Question: O que o usuário ganha ou perde quando se escolhe um deles? Consequentemente o que proprietário do site tem algum ganho em função da melhor experiência do usuário.
Quando optar por cada um? Existe um tipo de site ou aplicação web que se adéqua melhor?
Entre as desvantagens tem algo que pode dar errado?
Eu sei que o ideal é conduzir estudos com o público alvo. Mas queria saber o que já se concluiu de forma geral sobre o tema.
Quanto mais referências puder fornecer, melhor. Não quero saber o que você gosta ou usa. Procuro informações objetivas de quem entende realmente do assunto.
Comment: Um artigo recente sobre isso: https://speckyboy.com/infinite-scrolling/
Comment: Scroll é fundamental a única desvantagem que vejo é a demora no carregamento de imagens etc. e quando é preciso voltar ao top ou a um sub tema específico.
Comment: O problema de voltar ao topo ou escolher uma nova categoria pode ser sanado com um menu fixo, e também um botão acessível na lateral, indicando "voltar ao topo" - para que o usuário não precise voltar rolando novamente!
Comment: Desta forma terminam os problemas
Comment: A demora é relativo. Só porque tem imagens não significa que é demorado. [Veja a pesquisa de imagens do google, por exemplo](https://www.google.com.br/search?q=teste&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiO1diLrfTRAhXGEZAKHUbGB78Q_AUICSgC&biw=1920&bih=919). Ela é mais rápida que muitos sites, e ela é somente imagens :p
Comment: Para o site ser rápido mesmo com imagens. Deve ser uma otimização e performance
Answer:
O que o usuário ganha ou perde quando se escolhe um deles?
  Consequentemente o que proprietário do site tem algum ganho em função
  da melhor experiência do usuário.

Do ponto de vista do usuário: na paginação ele tem mais controle (ou, ao menos, sensação de controle) sobre o conteúdo, enquanto que na rolagem infinita o usuário tem menos esforço.
Imagine um cenário de um site tipo o Flickr, que contém apenas imagens, e em que o usuário está fazendo uma busca por uma imagem de algo desejado. Em certo momento ele encontra uma de que gosta, mas decide continuar procurando um pouco mais. Na paginação ele tem facilidade de memorizar onde está o item que gostou. Pode ser pela posição de uma barra de rolagem, pode ser pelo número da página, pode até mesmo ser pela posição relativa (número de cliques ou pagedowns dados). Isso já não é tão fácil na rolagem infinita.
Imagine que nesse mesmo cenário, as fotos exibem informações quando o mouse está posicionado sobre elas, que são importantes na decisão do usuário pelo item procurado. Nesse caso, ter de mover o mouse ou mesmo a mão do mouse para o teclado para controlar a rolagem gera mais esforço. Pode parecer pouco, mas dependendo do contexto (se for um profissional que passa o dia usando esse site) pode ser bastante cansativo ou reduzir a produtividade. Nesse sentido a rolagem infinita pode ajudar a reduzir o esforço.
Do ponto de vista do proprietário do site: na paginação ele dá o controle para o usuário, na rolagem infinita o proprietário conduz a experiência. O usuário deve ser sempre o foco de atenção ao se projetar a interação de qualquer produto, mas ainda assim essa decisão pode decorrer da experiência intencionada. Citaram em outras respostas a ideia de aumentar o tempo que a pessoa passa no site, por exemplo. A rolagem infinita gera essa sensação de que há muito mais por se ver, e por isso estimula o usuário permanecer mais tempo. Além disso, se por qualquer motivo não se deseja estimular o usuário a "voltar" (isto é, se deseja dar preferência para que ele veja conteúdo novo ao invés de conteúdo já visto), a rolagem infinita pode ser mais apropriada. Pode ser o caso de sites ou aplicações de notícias, como alternativa ao famoso serviço do tipo Push.
Uma solução híbrida é difícil porque dificulta a percepção de estado do usuário (mesmo que você use uma barra de rolagem, ela vai mudar de proporção conforme mais dados são exibidos) e requer muito mais memória do sistema porque essencialmente você vai ter que manter tudo em memória.

Quando optar por cada um? Existe um tipo de site ou aplicação web que
  se adéqua melhor?

No sentido do que foi discutido, a rolagem infinita talvez seja mais apropriada para sites em que o conteúdo é fugaz, existe em enorme quantidade, ou é gerado por diversas fontes distintas. Nas redes sociais, por exemplo, o conteúdo é produzido por outros usuários, comumente contém imagens, vídeos curtos ou links que são abertos ou "processados" imediatamente (o usuário lê, ri, se ofende ou curte, e passa para o próximo; links são abertos e lidos imediatamente ou guardados em outra aba, independente da paginação).
Caso contrário, provavelmente é melhor utilizar a paginação mesmo. :)

Entre as desvantagens tem algo que pode dar errado?

Na rolagem infinita, do ponto de vista técnico tem a possibilidade do sistema simplesmente não conseguir exibir tudo o que o usuário quer ver. Isso pode ser contornado ao descartar os itens muito antigos lá do começo da rolagem, e é o que geralmente se faz ao meu ver. Na paginação, o problema potencial é desestimular o usuário. Se o resultado de uma busca for muito grande, ele pode não se interessar por usar. O Google é uma situação atípica porque apesar de ele mostrar um bestilhão de resultados o usuário sabe que os primeiros são os mais relevantes (por convenção e por costume, já que essa informação não é necessariamente explícita - isto é, não há um número com a relevância na frente de cada resposta).

Eu sei que o ideal é conduzir estudos com o público alvo. Mas queria
  saber o que já se concluiu de forma geral sobre o tema.

Essa é uma boa pergunta. Mas é difícil ter uma única resposta pra ela, porque depende do domínio de problema. Como vc mesmo aponta, o ideal é conduzir estudos com o público alvo, mas esse público muda dependendo da área. Na área de e-commerce, por exemplo, parece ser condizente com o que eu apontei anteriormente. Há esse estudo muito bem feito e que inclui também uma distinção entre a paginação e o uso de botões "Carregar Mais" (carregamento em partes). O resumo é dado lá no texto mesmo, e é o seguinte (em tradução livre):
"Paginação ainda é a forma mais popular de carregar novos itens em um website porque já existe por padrão em quase todas as plataformas de e-commerce. Entretanto, nossos testes de usabilidade indicaram que botões "Carregar Mais" combinados com lazy-loading (carregamento preguiçoso) tendem a ser uma implementação superior, resultando em uma experiência mais contínua (sem costuras). Nós descobrimos que a rolagem infinita pode ser bastante prejudicial à usabilidade — em particular, na busca por resultados e em dispositivos móveis. Ainda assim, isso não é preto e branco, porque o desempenho de cada método varia de acordo com o contexto da página."
Comment: E estas publicações que são carregadas por demanda através de script são também indexadas por sistemas de buscas? Sei que a paginação é, pois o sistema de busca identifica as várias URLs das páginas, mas sendo esta uma página única, aconteceria também?
Comment: @AndersonCarlosWoss Honestamente eu não sei responder à sua pergunta, colega. :) Não tenho quase nenhuma experiência com SEO. Mas imagino que funcione de maneira similar às indexadas. Afinal, mesmo na paginação as páginas são geradas dinamicamente de acordo com o conteúdo, certo? De todas as formas, eu entendi que o foco da pergunta era UX...
Answer: O que é Scroll Infinito?
Scroll Inifino é uma forma de ter uma página infinita (se você possuir dados para isso, claro). Desta forma, à medida que o usuário chega ao final da página, novos registros serão adicionados automaticamente.
Vantagens

Carrega o conteúdo definido sem necessitar de clicks do usuário;
Não requer reajustes visuais, sendo o mesmo padrão de layout.
O usuário não precisa entender do sistema para saber utilizar o recurso, basta ir ao final da página;
Excelente experiência para dispositivos móveis;
"prisão" do usuário no site.

Desvantagens

Rodapé do site quase não será visto;
Sem filtros para buscas, ou seja, caso queira salvar aquele "estado", poderá ter problemas;
Sensação de "perda de controle" por parte do usuário;
Possíveis problemas de performance por carregar muito conteúdo;

Quando utilizar?
Não existe uma regra para isso. Como você mesmo disse, a melhor forma seria realizar um estudo com o público alvo para definir o melhor cenário.
Dito isto, existem cenários onde o Scroll Infinito é mais utilizado, como em redes sociais, dando assim uma certa "graça" ao navegar pelo Oceano de Informações gerado pelos usuários em uma rede social.
Também é comum ser utilizado para lista de imagens, pois o padrão das informações dá uma sensação de conforto ao usuário quando ele recebe mais informações.
O próprio Google possui duas formas de paginações, o scroll infinito para pesquisas de imagens e a paginação normal para pesquisas Web.
Segundo relatos o mesmo estaria pensando em alterar estas pesquisas para scroll inifito, mas não posso afirmar a veracidade da informação.
E sobre SEO?
O Google afirma que o scroll infinito pode ser utilizado pelo GoogleBot. Porém, deve ser levado alguns fatores na implementação. A lista de recomendações você pode ver no webmastes.googleblog.
Conclusão Pessoal
Eu particularmente acho elegante o uso de scroll infinito, mas em certas ocasiões.
Em redes sociais, lugares onde a paginação não é significante para mim ou para aplicativos mobiles, eu prefiro utilizar algo com o scroll infinito, pois me apresenta uma sensação melhor de usabilidade.
já em tabelas, notícias, blogs, sites institucionais, ou lugares com informações que contenham realmente leituras, eu prefiro ter o controle de conclusão, ou ao menos pensar que tenho esse controle.
Referências:
Bom, eu não sou ninguém para poder falar essas coisas, então abaixo eu listarei algumas referências que me levaram à esta conclusão.

Infinite Scrolling: Let's Get To The Bottom Of This
Complexities of an Infinite Scroller - Google Developers
Infinite Scrolling, Pagination Or "Load More" Buttons? Usability Findings In eCommerce
Infinite Scrolling: Is It Good or Bad for Your Website?
Pavination Vs. Infinite Scroll in Datagrids
Scroll-able website vs infinite scroll website
Answer: Hoje o scroll é uma tendência cada vez maior. Rolar o site não é mais um problema como antigamente - as pessoas estão mais habituadas.
A possibilidade de deixar todos os posts conforme a demanda é uma solução interessante para os usuários, e acredito que sem muita carga na performance. Como o script é acionado apenas no fim da rolagem, teria o mesmo efeito de uma paginação, porém, sem mudar de página. Com isso, o tempo que a pessoa fica na página é maior - você pode se aproveitar disso, para monetizar ou fazer qualquer outra ação desejada.
Não consigo ver nenhum contra a não ser performance, que - dependendo do servidor - pode ter o efeito visual contrário. Se o loading não termina (ou demora muito), o usuário vai ter sérios problemas em continuar navegando.
Comment: O ponto do desempenho ser crítico é bem importante. Eu diria que a percepção de demora é pior na rolagem infinita do que em qualquer outro método, justamente porque o usuário tem menos sensação de controle. Muito bem observado! :) +1
Answer:
Em dispositivos móveis (celulares e tablets)

O ruim da paginação em dispositivos móveis é ter que clicar em botões. Como tais dispositivos são mais baseados em toque e "arrasto do dedo sobre a tela", o scroll infinito torna a navegação mais confortável e agradável (eu diria até mais lúdica).

Como alguns dispositivos móveis podem variar no tamanho de tela — uns maiores e outros menores —, o clique em botões pode ser uma tarefa cansativa e chata, pois além do usuário ter que "mirar" o dedo sobre o botão, quando o tamanho da tela for muito baixo, há risco de errar o toque. Além do que é muito mais confortável arrastar o dedo sem se preocupar em que posição específica da tela isso é feito, ainda mais em relação a pessoas com algum tipo de deficiência, seja visual ou motora. Ou seja, em termos de acessibilidade, o scroll infinito se mostra bem mais adequado em termos de UX nesses dispositivos.

Usando ponteiro (notebooks e desktops)

Creio que o princípio seja o mesmo em relação ao dito na seção "dispositivos móveis" acima.
Usando o mouse wheel se torna bem mais confortável o scroll infinito do que ter que clicar em botões.

Mas também creio que isso seja muito relativo ao público alvo e ao tipo de conteúdo do site. Muitas vezes a paginação se torna melhor porque pela quantidade de botões o usuário tem como saber a quantidade de informações disponíveis, já no scroll infinito não há como saber. O usuário vai rolando a tela e nunca sabe quando vai terminar.

Logo, o scroll infinito se torna melhor:

Quando não há preocupação em saber a quantidade de informações.
Mais confortável de navegar (principalmente em dispositivos baseados em toque).
Quando as informações são atualizações ou uma lista onde o objetivo é mais a visualização e não muito de controle sobre elas.

Paginação:

Quando é importante explicitar a quantidade de informações a exibir ou disponíveis.
Quando se quer ter a possibilidade de selecionar itens em lote para alguma ação específica.
Proporciona melhor organização e controle para o usuário.

Entre as desvantagens tem algo que pode dar errado?

Qualquer coisa pode dar errado tanto nas vantagens quanto nas desvantagens. Confesso que não ficou muito claro esse ponto.

Procuro informações objetivas de quem entende realmente do assunto.

"Mexo" há 20 anos com front-end (12 anos profissionalmente) e essa é a minha opinião e percepção do que tenho visto ao longo do tempo em que as coisas vão mudando de acordo com as atualizações e tecnologias.
Answer: Usar scroll infinito implica assumir que o lado cliente tem bastante memória RAM e placa gráfica, o que não é verdade se for um dispositivo móvel.
O que eu já vi de Facebook dando crash no meu Android não tá escrito. Às vezes, até o Android dá crash!
Seria muito melhor ter um botão híbrido de paginação e/ou scrolling widget bem visível, na tela. Não, na verdade seria melhor nem ter botão: o padrão seria mudar de página, com uma barra de progresso mostrando quanto tempo falta para mudar a página, e, caso eu quisesse frear a paginação, eu seguraria o dedo no LCD.


Prove the inequality $\frac{a^2+1}{b+c}+\frac{b^2+1}{a+c}+\frac{c^2+1}{a+b}\ge 3$

Question:
If $a,b,c\in\mathbb R^+$ prove that:
   $$\frac{a^2+1}{b+c}+\frac{b^2+1}{a+c}+\frac{c^2+1}{a+b}\ge 3$$
Answer: Apply Am-GM to the numerator of each fraction.
You get the statement of Nesbit inequality.
Answer: By Cauchy Schwarz Lemma:
$$\frac{a^2}{b+c}+\frac{b^2}{a+c}+\frac{c^2}{a+b}\geqslant \frac{(a+b+c)^2}{2(a+b+c)}$$
Also By $HM\leqslant AM$
$$\frac 3 {\frac{1}{a+b}+\frac{1}{b+c}+\frac{1}{a+c}}\leqslant \frac{2(a+b+c)}{3}$$
$$\frac{1}{a+b}+\frac{1}{b+c}+\frac{1}{a+c}\geqslant\frac9 {2(a+b+c)}$$
Add both of them. Then apply $AM\geqslant GM$ on RHS
Answer: By C-S and AM-GM we obtain
$$\sum_{cyc}\frac{a^2+1}{b+c}=\sum_{cyc}\frac{a^2}{b+c}+\sum_{cyc}\frac{1}{b+c}\geq$$
$$\geq\frac{(a+b+c)^2}{2(a+b+c)}+\frac{9}{2(a+b+c)}=\frac{1}{2}\left(a+b+c+\frac{9}{a+b+c}\right)\geq$$
$$\geq\frac{1}{2}\cdot2\sqrt{\frac{9(a+b+c)}{a+b+c}}=3.$$
Done!


java2pdf,how to set the height of cell

Question: java project
well,i have to make pdf file.
i use com.lowagie.text.Table and com.lowagie.text.Cell
i put many Cell in one Table. each Cell's width can be assign.but the height cannot.
so the pdf file is not very beautiful.the height really sucks me.anyone can help me ?thanks
Answer: Here you can find an exemple on how to set the heigth of a pdf cell using itext.
you can pass your com.lowagie.text.Cell as a parameter to the pdfCell constructor.

java2pdf,how to set the height of cell


Syntax error, '>' expected in Razor

Question: Ok, so I've been trying to pass multiple models to a View using a Tuple and it's worked like a charm so far. Problem comes when I try this
@model Tuple<Smart_WEB.Models.Room, List<IGrouping<string, Smart_WEB.Models.Song>>, List<IGrouping<string, Smart_WEB.Models.Video>>>

The error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1003: Syntax error, '>' expected
Source Error:
Line 29:
  Line 30:
  Line 31:     public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<Tuple<Smart_WEB.Models.Room {
  Line 32:
  Line 33: #line hidden

And if I were to put something like:
@model Tuple<Smart_WEB.Models.Room, List<IGrouping<string, Smart_WEB.Models.Video>>>

Or
@model Tuple<Smart_WEB.Models.Room, List<IGrouping<string, Smart_WEB.Models.Song>>>

and the respective server side code it works perfectly.
Thanks in advance to anyone who can help me; I'm about to give up on this problem.
Comment: The `@model` differs entirely from your error. Are you sure you're looking at the right view?
Comment: Is the comma actually a comma, not some higher Unicode character that looks like a comma?
Comment: And that's a correct number of angle brackets! Are you spanning model type over 2 lines of text?
Comment: You don't have more than 4 items in your tuple but it seems to be exhibiting similar behavior to the issue with 5 items as described here... http://stackoverflow.com/questions/6098649/asp-net-mvc-3-razor-view-strongly-typed-list-of-tuple-problem
Comment: oops. I was testing something and copied the worng error. Thanks! Already fixed it.
Comment: I'm sure the comma is really a comma, wrote it four times and all four times it gave the same error. Even tried changing the number of item I pass to the Tuple (as seen in the other, working examples) and it appears to fail when there's three or more items that include Lists of IGrouping.
Comment: @stephen given the large number of generic arguments and the handling thereof you may still have a point. OP seems to have some MVC limit.
Answer: As you are basically passing multiple models in your view and MVC is designed to pass one type to one view, I strongly advise you to create a single model that wraps all your entities:
public class ViewModel
{
    public Smart_WEB.Models.Room Room { get; set; }
    public List<IGrouping<string, Smart_WEB.Models.Song>> Songs { get; set; }
    List<IGrouping<string, Smart_WEB.Models.Video>> Videos { get; set; }
}

Then you can set it as model in your view:
@model ViewModel

Comment: A `Tuple<>` _is_ one type, it just happens to be generic. That is fully supported by MVC. I agree that a viewmodel is a more sensible approach, but what OP shows, should just work.
Comment: @Jairo - i don't see this as a workaround... ViewModel is the correct and proper way to use in scenarios such as yours. There are a few disadvantages and limitations with System.Tuple.. One of them is code readability - Model.Item1... Model.Item.. instead ViewModel is self-descriptive.. and other disadvantage is System.Tuple is not going well when you post data back from your View to Action.. i guess, that's not supported...
Comment: Thanks for the advise, appreciate it! but more than using a workaround I would like to know what causes the error.

Syntax error, '>' expected in Razor