Voice parts exercises for blending

Question: Are there any exercises you can do as a singing group to improve the blend between the various voice parts, that's soprano, alto and tenor...? If yes, any recommendation is welcome...
Answer: Some points I want to hit right up front here (and then I'll get very wordy w/ the actual exercises).  As you can tell, this is a subject near & dear to my heart.

Good blend between voice parts is actually (mostly) about good blend between individuals.  Once a person has decided that they'll pay attention to good blend, then they tend to bring that attention and that good blend to whatever voice part they sing.  So any work you'll do on fixing blend between voice parts is really going to boil down to getting individual people to buy into the "let's blend" mentality.
Good blend starts with good listening, so exercises that get you to listen to each other are very important.  So, for example, even if the exercise in question normally is just aimed at having you listen for pitches, you'll find that success in pitch-correction will eventually translate into success in blend-correction, or at least it will translate into opportunities to point out blend issues (e.g. "okay guys, we've fixed those pitches there, but now let's try it again with a consistent tone & resonance, and here's how").
Not only do you need people to be willing to listen & blend, but you'll need some kind of agreement (even if it's unspoken) of what you're blending towards, i.e. how a particular bit is supposed to be sung, especially if it can be expressed in terms of real in-the-room examples that people can hear and follow, right then and there.  For example, should your group sound be more ethereal and choir-like in this particular passage, and so should you all be trying to sing more in a head resonance like what Jane is doing over there?  Or is this actually supposed to be a loud, blatty passage, in which case we all need to add some more nasal resonance here, like this (**sings loudly through nose**)?  Those are just made-up examples, obviously, but hopefully the point is clear.

A couple exercises now.
For simplicity, you can't beat "unison vowels":

Before:  Get the group where they can actually hear each other.  Standing in a tight circle of 4-12 people is ideal.  If your group is too big to do that, then consider breaking them out into smaller groups for this exercise.

Blending really well in a 100-person group isn't really possible (you get the "choir" effect), unless you first break up that group into smaller-level chunks, build blend/agreement at that smaller level, and then bring back that blend/agreement to the larger group.  If someone wants to question this point in a comment on this answer, I'll be happy to add (perhaps elsewhere, cited here) a recorded demonstration of the difference between the blend of a famous barbershop men's chorus and a famous choir, within the same song performance, which illustrates the difference of results I'm talking about.

How:  Have all voice parts sing, in unison, a particular vowel sound (see details on particular vowels below) on the exact same pitch (not octaves), like maybe a middle C (C4) or the A just below that (A3), which will be slightly low for most women and slightly high for most men.  Sustain the singing as long as is necessary (to observe effects, make corrections, etc.); people will probably need to "stagger breathe", i.e. individually sneak a breath and re-join the group singing.
What you're looking for:

You want everyone to listen and correct to get on the same pitch; if they don't do that, then these other blending effects will probably be destroyed.
You want everyone to sing at the ~same volume, where they're conscious of both their own volume level and (more importantly) the group's collective volume level.
You want everyone to pronounce their vowel sound in the same way (e.g. are they all actually singing the exact same "ah" part of the "iih" triphthong ("ah-eh-ee"), or is someone jumping ahead and is holding the "ee" part, which will sound nasty).
You want everyone to be using the same sort of resonance; e.g. (in the nomenclature I was taught) is everyone singing with a clean, light "head" resonance, or is someone resonating nasally/post-nasally, or is someone belting it out with a "mouth resonance".  To get the most mileage out of this exercise, you probably want to mostly use "head" resonance, but you might experiment with other resonances.  But the key is that everyone should be doing that same resonance (= blending), not just doing their own thing.
If you happen to be using a rather pure vowel sound (e.g. "ooo" or "ahh") and a rather clean resonance ("head"), and if people are listening and correcting their pitches, then you should start hearing audible acoustic effects like overtones (will sound like a phantom person singing one octave up, and maybe a fifth above that, too) and beat patterns (= slow oscillations when someone is close but not exactly on pitch... you listen for the beats, correct your pitch, and the beats will slow and then disappear).

Some details & nuances:

About different vowel sounds:

"ooo" will give you natural blend that comes to everyone the most easily (albeit with pretty low volume), it and will let people feel what their "head resonance" feels like, which is important generally and which comes in handy when using other vowel sounds on this exercise.  So use the "ooo" vowel sound kind of like training wheels, to help people get acclimated to this exercise; but probably don't use it as your mainstay vowel sound, and eventually switch to "aaah" instead.
"aaah" will give you more volume so that everyone can hear what's going on; it's still a pretty clean, un-complicated vowel sound (sort of like "ooo"), so it's good to mostly use "aaah" whenever you do this exercise.
"eeee", "iiii" (eye), and other vowel sounds ("you"?) can be useful, but mostly only for pointing out peculiarities that are relevant to those sounds.  For example:  use "eee" to spot & fix bad resonance habits (too much nasal/post-nasal resonance);  use "iiii" (eye) to spot & fix misunderstandings about how to sing diphthongs and triphthongs ("iiii" is an "ah-eh-ee" triphthong, and you want to dwell on the "ah" sound); etc.

If you're a directed group (if someone waves their hands while you sing), or maybe even if you're not, go ahead and direct the entrance, so that the group gets used to attacking the sound in unison (no one early, no one late; vowel sound starts on the directed downbeat; and prior consonant sound comes just before the directed downbeat).

Variations:

You could try the same thing on octaves, e.g. ladies on F4, men on F3.  The way that things lock & blend (pitches, resonance, etc.) won't be quite as pure and simple as with the unison (so start with unisons before you really work on octaves), but you may notice some additional interesting effects (e.g. you could even get "undertones", i.e. phantom voices a fifth lower than the lower pitch on the lower pitch (thus reinforcing it), due to the (distant) beat pattern between the notes of a perfectly-tuned octave).
Given a particular song passage in which you think your group is having blend issues, sing that passage through a couple times, the normal way, with parts and with whatever blend problems people normally bring to that passage.  Then do the "unison vowels exercise" for a bit, to get people using their ears and making corrections.  Then sing that particular song passage again, and see what problems have "fixed themselves".

Just one more exercise (there are many more, but this answer is running long).
Unison vowel to the chord

How:

Start with the "unison vowel" exercise as described above.
Once the group has reached equilibrium in singing the unison vowel (good pitch, volume, everything... good blend, in other words), direct a downbeat, and on that downbeat everyone will change pitch immediately to their particular part of "the chord", i.e. some agreed-in-advance part of a I chord in the key that you're singing.

Your own group's definition of "the chord" may vary, but what's worked for me in the past is: basses drop an octave to the root, altos stay on the exact same note, tenors drop down (a perfect fourth) to the fifth scale tone (the "dominant"), and sopranos jump up (a major third) to the third scale degree (the "mediant").

As in the "unison vowel" exercise, everyone holds their part (stagger-breathing as necessary) while we listen and correct for blend issues.

What you're looking for:

Everything that was described in the "unison vowel" exercise further above.
Further, you're looking for people's volumes to change.  When the group was singing unison before, they had a certain "group volume".  When people break out to individual parts, you're looking for that "group volume" to be maintained at a consistent level, and that generally means that people will need to sing somewhat louder on those individual parts, according to what's referred to as the "unison rule" (which is usually expressed in a reverse form:  "when we come together to sing a unison, we back off on our individual volumes").
Further, you're looking for tuning to get trickier.  Depending on whether your group sticks strictly with "tempered tuning" or allows yourself to wander into "harmonic tuning" territory, you'll find that you can start fiddling with how you tune the chord to get the most resonant sound (e.g. the most "ring", the most audible overtones, etc.).  That'll be especially true for whatever voice part is singing the third scale degree, and slightly less true for whoever's singing the fifth scale degree, and not at all true for whoever's still on the root(s).

I'll just leave it at that for now.  I have another good exercise that involves descending lines that lock into different chords on the way down, but I want to see first how this already-lengthy answer is received before I dive into any of that.
I anticipate that you'll get a bunch of good answers to this question, since different people have different exercises that will have worked for them in the past.  Even if you pick other exercises than the ones listed here, try to make sure that you bring to those other exercises the same fundamental principals I've touched on here, which I would summarize as follows:

Blend starts with listening; you can't blend if you don't know what to listen for.
Blend is about noticing something that needs correcting, and then making that correction.
Blend can encompass not just tone/resonance, but also pitch, volume, attack, and as many other things as you care to add to it.
Comment: @Raphael Gbologah, since I don't have enough reputation points (yet) to comment directly on your question, I'll ask here:  can you possibly add a little bit of information in your question describing what kind of music and what kind of group/ensemble you're thinking of?  E.g. is it a choir of 100 people that sings with orchestras, or a chorale of 16 people that sings early Renaissance a cappella music, or doo-wop group of 5 people that sings covers of heavy metal songs?  Just wondering.
Comment: @Raphael Gbologah, from your comment on [PA System Factors to Consider](http://music.stackexchange.com/q/39098/24580), I'll guess that the group you're asking for is the same worship band you mention, with lead vocals and SAT parts (I guess as backup singers).  Based on that, I just want to point out that there are some types of ensembles and songs on which a blend-y sound is not normally sought. For example, soloists in operas aren't really supposed to blend (they need to stick out individually).  And sometimes rock/praise music can sometimes be like that, too.  So don't blend _too_ much.
Comment: Fixing my erroneous claim of a "fifth below" undertone for the unison octave exercise.  I was mistakenly thinking of how a perfect fifth can produce octave-below undertones, in the some scenarios.  Instead, the biggest harmonics you'll get from a perfect octave will be reinforcement of the lower root tone (because the frequency difference between the octave's two tones also happens to be equal to the frequency of that lower tone).  Oops.
Comment: yes it's the same group of about 20 people...and is a charismatic singing group, hope you get what that means...
Comment: Thanks very much for the answer, will like to know more about the rest of the exercises...@mlibby

Voice parts exercises for blending


Fruity love philter knobs don't work and are dimmed

Question: Ever since something happened (I forget what happened, sorry D:), whenever I try to add a Fruity Love Philter to a channel, the knobs are dimmed and "locked":

When I try to change / drag them, they animate, like the knob spins, but the change doesn't take effect. I've restarted FL and my computer. What happened, and how do I fix this?
EDIT: Just found out if I choose a preset (top-left arrow, Presets) it works, but I still can't change the knobs after that. They are locked to their initial position.
Answer: Whoops...
Just realized I had selected the second tab, so this is expected. I guess if you select a tab, like the second, that tab will stay opened even if you restart.


Quais aplicações para árvores binárias implementadas em vetores?

Question: Conheço a teoria das árvores binárias, já fiz a implementação de uma AVL em C. Entendo o funcionamento e as aplicações dela quando desenvolvida dinâmicamente. Porém, um professor me pediu pra desenvolver uma árvore binária em vetor, fiz ela perfeitamente só que não consigo identificar uma utilidade ou vantagem para este tipo de específico de estrutura.
Comment: Depende de como será implementado, pode ser que nem esteja fazendo uma árvore binária de fato. Pode ser que só esteja simulando a memória com ele e de fato esteja usando ponteiros criados por você para implementar. Eu queria ver essa implementação para ver se ela ainda é uma árvore de fato e se for, se não é só uma camada extra em algo desnecessário.
Comment: Uma das maiores vantagems de um vetor é o acesso direto. Sobre isso, dê uma olhada em Heaps, que são árvores binárias de máximo e mínimo, muito bem implementadas com vetores, devido ao modo como ela se organiza. Se gostar, pesquise por Heapsort, um algoritmo de ordenação utilizando essa estrutura.
Answer: São algumas vantagens:
1) A busca em largura vira uma simples interação sobre o Array
2) Você tem acesso O(1) a qualquer nó da sua árvore ao invés de ter que percorrer sua altura pra chegar.
3) Arrays existem em praticamente todas as linguagens de programação, diferentemente de ponteiros.
Fonte: https://www.quora.com/When-is-it-good-to-represent-a-binary-tree-as-an-array-instead
Com certeza existem outras vantagens/aplicações, então comentem que eu edito na resposta, mas acho que fica claro que tem sim aplicação e um porquê de se utilizar a árvore dessa forma.
Answer: O HeapSort é um caso clássico em que se tem uma árvore binária representada em um vetor.
As vantagens de se usar uma árvore binária representada em um vetor são relativas à performance:

os dados não estão totalmente independentes entre si na memória, então você terá menos cache miss
o processador não precisará navegar do ponteiro até a região de memória contendo o nó, para só então pegar seu valor, portanto você faz menos acessos a memória, o que acarreta em menos processamentos e diminui as chances de mudar os dados que estão em cache
você aloca menos memória e numa região contígua, pois está trabalhando com um vetor de elementos

Existem desvantagens relativas ao uso na representação em vetor também. Remoção/inserção pode se tornar problemático, pois exige manipulação de subárvores.


atomic deployments with Nginx and PHP FPM

Question: I'm trying to get atomic deployments, I don't want to lose/drop any requests.
I deploy the code using Capistrano, classic situation were you have a 'current' dir that is a symlink to
the latest release in the 'release' folder.
I'm using Nginx, PHP 5.5 FPM with Opcache.
Following the idea of just using $realpath_root in Nginx I'm expecting that a simple nginx reload would suffice, but it's not.
With nginx reload it seems that I'm not losing any requests but php-fpm is still executing the code from the previous old dir.
If I do a 'php-fpm reload' then php fpm is reading from the new dir but I can still see that I'm losing some requests:

'recv() failed (104: Connection reset by peer) while reading response header from upstream'

The question is: should I reload PHP FPM or not?
From what I understand  nginx is passing the path to php-fpm and from the nginx debug log I can see that the path passed is the right one but php-fpm still executes the old one.
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script var: "/shop/www/htdocs/current/web"
2014/09/23 17:13:22 [debug] 26234#0: *1742 posix_memalign: 00000000010517A0:4096 @16
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script copy: "SCRIPT_FILENAME"
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script var: "/shop/www/htdocs/ive/releases/20140923124417/web"
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script var: "/app.php"
2014/09/23 17:13:22 [debug] 26234#0: *1742 fastcgi param: "SCRIPT_FILENAME: /shop/www/htdocs/live/releases/20140923124417/web/app.php"
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script copy: "DOCUMENT_ROOT"
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script var: "/shop/www/htdocs/live/releases/20140923124417/web"
2014/09/23 17:13:22 [debug] 26234#0: *1742 fastcgi param: "DOCUMENT_ROOT: /shop/www/htdocs/live/releases/20140923124417/web"
2014/09/23 17:13:22 [debug] 26234#0: *1742 http script copy: "APPLICATION_ENV"

What am I missing? thanks
Answer: It sounds like you have made changes to the default OPcache configuration.
The defaults are:
opcache.validate_timestamps = 1
opcache.revalidate_freq = 2

This specifies whether and for how long OPcache should wait before checking to see if a file on disk has changed. In this case, yes, and after two seconds.
First, try re-enabling this option, as it sounds like you have turned it off.
Comment: why? opcache works with realpath as far as I know.
Comment: checking what opcache contains I can see different paths for the same file, so it shouldn't be the problem... right?
Answer: I also faced that issue then finally I make a solution.
$ curl -sO http://gordalina.github.io/cachetool/downloads/cachetool.phar
$ chmod +x cachetool.phar

You can connect to a automatically guessed fastcgi server (if /var/run/php5-fpm.sock is a file or 127.0.0.1:9000)
apc
  apc:bin:dump             Get a binary dump of files and user variables
  apc:bin:load             Load a binary dump into the APC file and user variables
  apc:cache:clear          Clears APC cache (user, system or all)
  apc:cache:info           Shows APC user & system cache information
  apc:cache:info:file      Shows APC file cache information
  apc:key:delete           Deletes an APC key
  apc:key:exists           Checks if an APC key exists
  apc:key:fetch            Shows the content of an APC key
  apc:key:store            Store an APC key with given value
  apc:sma:info             Show APC shared memory allocation information
opcache
  opcache:configuration    Get configuration information about the cache
  opcache:reset            Resets the contents of the opcode cache
  opcache:status           Show summary information about the opcode cache
  opcache:status:scripts   Show scripts in the opcode cache

Example :
    [root@ip-172-31-5-244 ~]# php cachetool.phar opcache:status
+----------------------+---------------------------------+
| Name                 | Value                           |
+----------------------+---------------------------------+
| Enabled              | Yes                             |
| Cache full           | No                              |
| Restart pending      | No                              |
| Restart in progress  | No                              |
| Memory used          | 42.71 MiB                       |
| Memory free          | 85.29 MiB                       |
| Memory wasted (%)    | 0 b (0%)                        |
| Strings buffer size  | 8 MiB                           |
| Strings memory used  | 5.31 MiB                        |
| Strings memory free  | 2.69 MiB                        |
| Number of strings    | 103847                          |
+----------------------+---------------------------------+
| Cached scripts       | 1261                            |
| Cached keys          | 2748                            |
| Max cached keys      | 7963                            |
| Start time           | Thu, 08 Feb 2018 02:28:56 +0000 |
| Last restart time    | Thu, 08 Feb 2018 03:10:19 +0000 |
| Oom restarts         | 0                               |
| Hash restarts        | 0                               |
| Manual restarts      | 1                               |
| Hits                 | 47839                           |
| Misses               | 1269                            |
| Blacklist misses (%) | 0 (0%)                          |
| Opcache hit rate     | 97.415899649752                 |
+----------------------+---------------------------------+
[root@ip-172-31-5-244 ~]#
[root@ip-172-31-5-244 ~]#
[root@ip-172-31-5-244 ~]# php cachetool.phar opcache:reset
[root@ip-172-31-5-244 ~]#
[root@ip-172-31-5-244 ~]#
[root@ip-172-31-5-244 ~]# php cachetool.phar opcache:status
+----------------------+---------------------------------+
| Name                 | Value                           |
+----------------------+---------------------------------+
| Enabled              | Yes                             |
| Cache full           | No                              |
| Restart pending      | No                              |
| Restart in progress  | No                              |
| Memory used          | 10.43 MiB                       |
| Memory free          | 117.57 MiB                      |
| Memory wasted (%)    | 0 b (0%)                        |
| Strings buffer size  | 8 MiB                           |
| Strings memory used  | 545.69 KiB                      |
| Strings memory free  | 7.47 MiB                        |
| Number of strings    | 103847                          |
+----------------------+---------------------------------+
| Cached scripts       | 0                               |
| Cached keys          | 0                               |
| Max cached keys      | 7963                            |
| Start time           | Thu, 08 Feb 2018 02:28:56 +0000 |
| Last restart time    | Thu, 08 Feb 2018 03:19:00 +0000 |
| Oom restarts         | 0                               |
| Hash restarts        | 0                               |
| Manual restarts      | 2                               |
| Hits                 | 0                               |
| Misses               | 2                               |
| Blacklist misses (%) | 0 (0%)                          |
| Opcache hit rate     | 0                               |
+----------------------+---------------------------------+

You can notice that the memory , cache keys , hits everythings became 0 :-). Its very useful. I also intrigrated it with Ansible easily.
Its application for apcu and others stuffs : Check more there
http://gordalina.github.io/cachetool/


angular 1.6 unable to show scope value in template

Question: I have index.html
Previous

I assigned some values to $scope.errorMsg in registerController so changed
Changed to

In controller when I do console.log It print the value but it is not getting displayed on error.html page.
$scope.errorMsg = data.message;
$location.path("/reg/error");

I am new to Angular, Please let me know if I need to add in more info for my problem
Comment: how can your ng-app and ng-controller values be same. Please create a working demo replicating the issue a fiddle or plnkr. So that it easy to understand what is actually your problem.
Comment: No it's not same App name is myApp and controllers have their own names
Comment: You're changing the `path` as consequence your `scope` is destroyed.. you need to put this  `errorMsg` in `rootScope` in order to provide it in all `controllers`
Comment: you are adding ng logic inside a css class without the actual ng-class directive, you can't do that mate :)
Comment: Do you want to create a Plunkr with the code you have?
Comment: Please provide code in fiddle or Plnkr.
Answer: Try interpolation in the scope of RegisterController:

{{errorMsg}}

Update
A common source of confusion to those new the angular is that scopes and controllers come and go with the wind, and it's not obvious where to place transient data.
Since angular services are singletons, one solution is to implement a service to store transient state - in the OPs case, "errorMsg" - among view changes.
Here's a bare bones singleton service.
app.factory('StateService', function() {
   // A singleton object to stuff transient data
   return { };
});

It's easily passed along to controller instances like so
app.controller('ErrorController', ['$scope', 'StateService', function($scope, states) {
 . . .
});

Here's a plunkr that demonstrates the concept, using your code as a base.
Comment: @user269867 you can't access ```$scope.errorMsg``` at your new location, just try to assign to ```$rootScope.errorMsg``` and then get back to view, or use ```ui-router```
Comment: @MiguelLattuada you're on the right path with OP's problem I think (but a state service would be cleaner than mucking with $rootScope).
Comment: @RamblinRose Thank you for plunkr. I added the template for error inside my index.html and it kinds solve the problem.
Comment: Glad it helped.


Recurrence relation with not constant coefficients

Question: I have this recurrence relation
L^2 G[p]= 2(p-1)(2p-1)G[p-1] + ((p-1)(p-2)+a^2) G[p-2], where L and a are parameters.
Does anyone could help me to find the solution? Thanks
Comment: Try plugging in some values for L, a, G[0], and G[1], and generate a few G[2], G[3], G[4], ... and then look it up on OEIS (a web search will find it). Just guessing here.
Answer: This looks like quite a complicated calculation, especially when no start values are given.
To get some more insight, one could use sympy, Python's symbolic math library to print the formulas for small values of p:
from sympy import symbols

def func_G(p):
    if p == 0:
        return G0
    elif p == 1:
        return G1
    else:
        return (2 * (p - 1) * (2 * p - 1) * func_G(p - 1) + ((p - 1) * (p - 2) + a ** 2) * func_G(p - 2)) / L ** 2

a, L, G0, G1 = symbols('a L G0 G1')
for p in range(8):
    print(p, ':', func_G(p).simplify())

Prints out:
0 : G0
1 : G1
2 : (G0*a**2 + 6*G1)/L**2
3 : (20*G0*a**2 + G1*L**2*(a**2 + 2) + 120*G1)/L**4
4 : (840*G0*a**2 + 42*G1*L**2*(a**2 + 2) + 5040*G1 + L**2*(a**2 + 6)*(G0*a**2 + 6*G1))/L**6
5 : (60480*G0*a**2 + 3024*G1*L**2*(a**2 + 2) + 362880*G1 + 72*L**2*(a**2 + 6)*(G0*a**2 + 6*G1) + L**2*(a**2 + 12)*(20*G0*a**2 + G1*L**2*(a**2 + 2) + 120*G1))/L**8
6 : (G0*L**4*a**6 + 26*G0*L**4*a**4 + 120*G0*L**4*a**2 + 10960*G0*L**2*a**4 + 90720*G0*L**2*a**2 + 6652800*G0*a**2 + 158*G1*L**4*a**4 + 2620*G1*L**4*a**2 + 5040*G1*L**4 + 398400*G1*L**2*a**2 + 1209600*G1*L**2 + 39916800*G1)/L**10
7 : (248*G0*L**4*a**6 + 7488*G0*L**4*a**4 + 38880*G0*L**4*a**2 + 1770240*G0*L**2*a**4 + 15966720*G0*L**2*a**2 + 1037836800*G0*a**2 + G1*L**6*a**6 + 44*G1*L**6*a**4 + 444*G1*L**6*a**2 + 720*G1*L**6 + 28224*G1*L**4*a**4 + 526080*G1*L**4*a**2 + 1088640*G1*L**4 + 62513280*G1*L**2*a**2 + 199584000*G1*L**2 + 6227020800*G1)/L**12

Comment: Hi, thanks for your answer.

Actually this relation comes from a differential equation that I'm trying to solve with Mellin transform and p is in general a complex number.
For example if L=0, the solution is

$G[p]=(-4)^(-p)\frac{\Gamma[1/2-v+p]\Gamma[1/2+v+p]}{\Gamma[1/2-v]\Gamma[1/2+v]\Gamma[1+p]\Gamma[3/2+p]}$, with $v=\sqrt{1/4-a^2}$.

Thanks


POST request working on Postman but not on Expo

Question: I implemented an e-mail OTP verification using Node-JS for an app. When I tested it with Postman, it worked properly and I got the OTP in my email, meaning the logic is probably correct. But when I run the app with Expo Client, I am not getting the email.
Please tell me where the problem might be.
Answer: Since the request worked just fine with postman perhaps this is a CORS issue.
Have you enabled CORS in your application?
https://expressjs.com/en/resources/middleware/cors.html
Install the package then add:
<code>app.use(cors())
</code>
This should make it work just fine with localhost.
If this is not the issue you should probably provide more info on the problem such as error codes returned by your application.


Confused about finding non-brute force way to solve for matrix to the 2019th power

Question: I am attempting to solve this problem, it has four parts. I solved part a (a trivial matrix problem), but the next three parts appear to be a bit confusing to me. I just would like some help getting started so I can see and observe this matrix and come up with a solution.
The Questions Note:
The idea here is NOT to use brute force computation to get $A^{2019}$ matrix, instead use some observations which can significantly reduce computational work and will also give you an insight into such problems.
Obviously this is some huge numbered matrix, but I do not understand what observation will reduce this? My first thought was just to use a calculator and calculate $A^{2019}$ and then just multiply that by each vector. But that appears to be not the point of the question.
$$
Let A = \left[\begin{array}{rrr}
  -4 & -6 & -12 \\
   -2 & -1 & -4 \\
  2 & 3 & 6
 \end{array}\right]
$$
And Let $u$ = [6 5 -3], $v$ = [-2 0 1], and $w$ = [-2 -1 1].
b). Compute $A^{2019}\mathbb v$
Comment: Hint: Is there a simple relationship between $\mathbf v$ and $A\mathbf v$?
Comment: If $p(x)$ is the characteristic polynomial of $A$, then $p(A)=0$. If you divide $x^{2019}=p(x)q(x)+r(x)$, with $r$ of smaller degree than $p$, then $A^{2019}=p(A)q(A)+r(A)=r(A)$.
Comment: Take into account that the quotient $q$ doesn't need to be computed. Only the remainder is necessary. The characteristic polynomial in your case is $-x^3 + x^2 + 2 x$. The remainder can be found by indeterminate coefficients. For example, evaluating the equation $x^{2019}=p(x)q(x)+r(x)$ at the roots of $p$. In your case $0,-1,2$. The remainder becomes, I think, $\frac{2^{2019}-4\cdot (-1)^{2019}}{6}x^2+\frac{2^{2019}+2\cdot(-1)^{2019}}{5}x$.
Comment: So, you only need to compute $A$ and $A^2$ and plug them in there.
Comment: What is $x$ ? Also you can decompose your matrix like this : $A=SJS^{-1}$ where $J$ is a diagonal matrix and then $A^{2019}=A J^{2019} S^{-1}$.
Comment: @Alain There's really no need to diagonalize here.
Comment: @amd Edited and fixed that! My bad
Comment: @Alain my bad fixed that x to an A
Answer: I assume that you're asking about $A^{2019}v$.
To that end, observe that $Av = 2v$ (I'll leave it to you to verify that this is true).
It follows that
$$
A^2v = AAv = A(2v) = 2Av = 4v.
$$
Similarly, $A^3 v = 8v$, and in general we have $A^k v = 2^k v$ for any positive integer $k$.
Comment: Ah, that is an interesting relationship! There are two more parts to this question, but I assume that these will be similarly discovered! Thank you so much


What's a reasonable path for a new singer to take to make it into a choir?

Question: At 53 I've fallen in love with singing. I'm taking two one-hour voice lessons a week. I'd like to someday join a choir. If I work diligently at it how long might that take and what steps might I want to take? (Yes, I'll ask my voice teacher but I'd like other input as well.) My teacher tells me that I have a nice voice and that I'm a first tenor. Apparently male tenors are desirable in choirs but I still need some skill to get there!
There's a chorus at my community college that will take beginners - no audition needed. That chorus does a performance at the end of the 16 week semester. That's an obvious step to take but I'm curious about getting into a choir when an audition is involved.
Comment: The voice is only a part of it. You may well be expected to be able to sightread. This is difficult to answer, not enough info. You could join an amateur choir tomorrow. Or go to open mic sessions.
Comment: Auditioned choirs sometimes have age limits and I'm sorry but you may be considered a bit too old for some.  Don't worry about that too much - there are lots of choirs around so there will always be some who do not take age into consideration.
Answer: First of all, voice lessons is a great start!  Your teacher will teach you proper singing techniques like breath control and voice placement.  You might also want to ask your teacher about sight reading as well, which is not always required, but definitely a skill to have as a choir member.  For an audition, you might actually have to sight read something, so be prepared for that!
I'm not sure of your religious affiliation, but many churches have choirs that you could join.  In my experience, a church choir will hold a very small audition, just to get a feel for your voice and see where you are best suited in the choir.
I would definitely start off small, with some kind of community choir that doesn't require an audition.  You mentioned your community college has one, and that is a wonderful place to start your choir experience!  You could also ask the head of the music department there if they know of any other choirs that you could join.
Another thing I should mention is that it is possible to be in multiple choirs at one time.  The only thing to consider is how open your schedule is compared to each choir's practice times and performances and make sure none of them conflict, which can be very difficult.  Also take into consideration the amount of music you are able to learn in a given time.
I think it is wonderful that you are looking for a choir to join!  Almost every choir needs more tenors, so you've got a leg up on the competition!  Don't be afraid to ask your voice teacher any questions you have about auditions.  I would also suggest going to any music stores and asking them if they know of any choirs in your area, although most music stores are geared more toward instrumentalists.
Finally, I would like to mention that, in the event you are turned down after an audition, do not get discouraged!  Auditions, just like job interviews, can be very stressful, and you might not do your absolute best at every single one.  But, with each audition, you grow stronger as a musician, so just keep that in mind.  And good luck with your search!!
Answer: From what you've told us, the steps you need to take are up to the door of your community college on choir practice night.  From there, all will follow.  You will be singing alongside people who also sing in other choirs, with policies ranging from 'fully inclusive' to 'must have excellent voice and music reading skills'.   With two hours of tuition each week, I suspect you will be way ahead of many of them!   Get going.
As to auditions.  Remember, a choir that holds auditions is looking to recruit suitable members.  They are overjoyed when they find one.  They WANT you to be good.  But that's in the future.  Spend a term in your community choir and find out what choral singing is all about.


Remove Historic Git Commit so It Does Not Appear in "git log -p"

Question: There is some sensitive information that was committed to a repository about a month ago that I'd like to completely remove any trace of.
I'm adept at using git rebase and know I can use this to change the commit, and answers like How to delete a 'git commit' from LOG, like it had never existed show how to just delete a commit using git rebase.
However, the pre-rebased hash of the offending commit is still findable using
git log -p $BAD_SHA

So, even though the commit no longer appears under git log, with the above command someone can still see the sensitive information even though it has been "deleted" using rebase.
Is there a way to essentially completely remove a SHA after it has been rebased, so that it no longer shows up using git log -p $BAD_SHA?

Addendum: I have tried git gc --prune=all --aggressive after rebasing, and this does not solve the problem.  There is no branch either on the local or remote repository that still references the bad hash I want to get rid of.
Comment: Have you tried clearing the reflog?

git reflog expire --expire=now --all
Answer: If the commit is not viewable on any existing branch, garbage collection should take care of it.
git gc --prune=all

Comment: I've tried `git gc --prune=all` and `git gc --prune=all --aggressive`, but the offending SHA still appears in `git log -p $BAD_SHA`.  There is only one branch in this entire repository, both on local and on remote.
Comment: See if this finds any references to it: `git describe --all --contains $BAD_SHA`
Comment: The reflogs also point to commits, so that might have prevented gc from cleaning it up as well.
Comment: Tags also point to commits, so again, unless the tag is deleted, their pointed to commits will hang around as well.
Answer: Turns out, after performing garbage collection with git gc --prune=all --aggressive, I also needed to completely remove the repository locally and then re-clone it.  Now the offending commit does not show up in git log -p $BAD_SHA.
Comment: This should have been done by garbage collection.  Maybe it wasn't eligible yet.


Qual a melhor estratégia para carregar e persistir grandes volumes de dados com Spring?

Question: Estou precisando realizar uma função em um projeto Spring e Hibernate, ao qual devo atualizar algumas informações de todos os registros da minha tabela. A ideia é carregar os registros para a aplicação, processar os dados com base em alguns valores desses registros e depois persisistir toda essa massa de dados.
Os valores a serem atualizados são diferentes para cada registro, e dependem dos dados ja persistidos em cada um.
A tabela contém uns 200 mil registros, e gostaria de saber qual a melhor estratégia para que eu consiga realizar essa carga, processamento e persistencia de dados sem que isso gere gargalos na minha aplicação e banco.
Comment: Você precisa mesmo carregar os cados para a aplicação, processar nela e fazer a atualização? Não daria, por exemplo, para ter uma _procedure_ que faz esta atualização, no máximo sendo chamada pela aplicação?
Comment: Nesse caso não, devido a regra de negócio que devo executar nessa atualização, o que geraria uma query muito complexa. Precisarei usar relações, operações com data, splits, interações...
Answer: O Spring tem uma ferramenta adequada para isto, chamada Spring Batch.
Em uma tradução livre:

Muitas aplicações no ambiente corporativo exigem processamento de dados em massa para realizar operações de negócios em ambientes de missão crítica. Essas operações incluem o processamento automatizado e complexo de grandes volumes de informações processadas na maioria das vezes sem a interação do usuário. Essas operações normalmente incluem aquelas baseadas em eventos (por exemplo, cálculos de fim de mês, avisos, etc), aplicação periódica de regras de negócios complexas processadas repetidamente em cima de um grande volume de dados (por exemplo, determinação de benefícios de seguro, promoções personalizadas) de sistemas internos e externos que, normalmente, requerem formatação, validação e processamento de registros.

Recentemente utilizamos esta ferramenta em um projeto para fazer a migração de dados de um sistema para outro. Carregamos um grande volume de dados por meio de arquivos de dados exportados do banco antigo e realizamos diversos processamentos em cima deles: corrigindo informações, vendo quais informações já existem no banco, pegando imagens de um diretório e movendo para outro, inserindo as informações no banco de dados atual, salvando em um arquivo de log os registros problemáticos, etc.
A princípio ela pode assustar, mas é bem simples de usar.
Comment: Me assustou. Acho que só vou ficar sossegado com ele ao utilizar, ao construir uma aplicação com ele
Answer: Uma outra estrategia seria vc trazer esses dados paginados pra memoria(trazer os dados para o java, para fazer toda a tratativa), depois atualizar eles e logo em seguida fazer um insert em lote em outra tabela. E a tabela antiga vc pode fazer o drop. Esse processo é mais rápido que um update no banco. Caso vc queira fazer esse processo eu recomendo fazer um backup da tabela que será excluída. Caso vc não queira mexer com uma linguagem de programação, existe ferramentas de tratamentos de dados tipo o PENTAHO (Ele faz muito mais coisas que tratamentos de dados). Espero que ajude. :)
Answer: Nesse caso quando tem muitos registros para mostrar na tela, você pode utilizar a paginação que tem o controle de quantos você quer mostrar em um GET
Exemplo de uma aplicação que fiz:
No controller:
<code>@RequestMapping(value = "/page", method = RequestMethod.GET)

    public ResponseEntity<Page<CategoriaDTO>> findAll(
            @RequestParam(value="page", defaultValue="0") Integer page,`insira o código aqui`
            @RequestParam(value="linesPerPAge", defaultValue="24") Integer linesPerPAge,
            @RequestParam(value="orderBy", defaultValue="nome") String orderBy,
            @RequestParam(value="direction", defaultValue="ASC") String direction) {
        Page<Categoria> list = service.findPage(page, linesPerPAge, orderBy, direction);
        Page<CategoriaDTO> listDTO = list.map(obj -> new CategoriaDTO(obj));

        return ResponseEntity.ok().body(listDTO);
    }
</code>
Na Service:
<code>public Page<Categoria> findPage(Integer page, Integer linesPerPAge, String orderBy, String direction){

        PageRequest pageRequest = PageRequest.of(page, linesPerPAge, Direction.valueOf(direction), orderBy);
        return repo.findAll(pageRequest);
    }
</code>
No Repository não é preciso ser feito nada!
Comment: Você fala de carregamento em tela, mas o foco da questão é persistência em _batch_. A ideia do carregamento do AP (em suas palavras) é permitir um processamento dos dados do lado da aplicação, não do SGBD. Então, o que sua resposta acrescenta ao problema fornecido, ou a seu contexto?


failed loading custom repository config /etc/yum.repos.d/kubernetes.repo in CentOS 8

Question: I am add a custom repository config in CentOS 8 like this in my kvm virtual machine like this:
<code>[root@localhost ~]# cat /etc/yum.repos.d/kubernetes.repo
[kubernetes]
   name=Kubernetes
   baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
   enabled=1
   gpgcheck=0
   repo_gpgcheck=0
   gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
       http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
</code>
but when I using this command to install kuberentes component, it shows me like this:
<code>[root@localhost ~]# yum -y install kubelet kubeadm kubectl
Warning: failed loading '/etc/yum.repos.d/kubernetes.repo', skipping.
Last metadata expiration check: 0:37:38 ago on Sun 05 Jul 2020 08:38:19 AM EDT.
No match for argument: kubelet
No match for argument: kubeadm
No match for argument: kubectl
</code>
am I missing something? what should I do to fix this problem?
Answer: I think the problem is that your repo file is not correctly formatted and contains whitespace where there should not be any.
You should re-create the file according to the instructions:
<code>cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF
</code>


Cache-Control Header & Browser Caching IIS7

Question: I am using Google Page Speed on my website in IIS7 and I was wondering how to set
Leverage browser caching - The following resources are missing a cache expiration
Leverage proxy caching - Consider adding a "Cache-Control: public" header to the following resources.
I am using doDynamicCompression in my web.config and little confused how to set these ? Hoping for some help
Note: Reference being used http://www.iis.net/ConfigReference/system.webServer/httpCompression
Answer: I found in a few of my tests, I didn't have to do the httpCompression options, just the urlCompression tags.
<configuration>
  <system.webServer>
    <urlCompression doDynamicCompression="true" />
  </system.webServer>
</configuration>

You can achieve the same by going through the UI, and setting the option there, and it'll write the above to your web.config for you.  This is under Site\Compression "Enable dynamic content compression" (Static option is usually enabled by default).
The same applies for client caching, but IIS appears to only apply this to static content.  This is under Site\HTTP Response Headers\Set Common Headers, and you can enable the web content expiration there.  Or the web.config version:
<system.webServer>
  <staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
  </staticContent>
</system.webServer>

This sets it for 7 days.  When combined, Google's Page Speed FireFox plugin it stops complaining about compression, and browser caching.
Answer: http://technet.microsoft.com/en-us/library/cc770661%28WS.10%29.aspx
Answer: To enable leverage browser caching in ISS server you have to follow these instruction:
1) Login your host 2) Find Web.config 3) Open web.config
    4) Add cacheControlMode given bellow 5) Save web.config and
    check for caching.

<configuration> <system.webServer>
  <staticContent> <clientCache cacheControlMode="UseExpires"
  httpExpires="Tue,19 Jan 2038 03:14:07 GMT"/>
  </staticContent> </system.webServer>
  </configuration>
Comment: Hello there - thank you for your contribution to Server Fault. Please be careful with self-promotion as it's seen as unwanted spam by the community. Linking to your site is fine as long as 1) you provide content here and 2) you disclose your affiliation with the site.


Deletar input dinâmico

Question: Eu estou usando javascript para criar inputs dinamicamente. Crio um input de telefone e email dessa forma.
Eu criei uma função deleteEmail() que deleta o mais recente criado, no entanto quando eu crio outros campos eu perco a referência de qual deletar
O que eu quero saber é como eu deleto esses inputs criados usando JS puro?
 function addEmail(){
    var container = document.getElementById("box");
    var input = document.createElement("input");
    var label = document.createElement("label");
    var btn_delete = document.createElement("button");
    var br = document.createElement("br");

    input.type = "text";
    input.name = "email";

    label.innerText = "Email";
    label.htmlFor = "email";

    btn_delete.type = "button"
    btn_delete.innerText = "Deletar";
    btn_delete.id = "btn-delete";

    container.appendChild(br);

    container.appendChild(btn_delete);
    container.appendChild(input);
    container.appendChild(label);

    document.getElementById("btn-delete").onclick = function () {deleteEmail()};

    function deleteEmail(){
        btn_delete.remove();
        input.remove();
        br.remove();
        label.remove();
    }

}

Aqui tem o fiddle com o código inteiro https://jsfiddle.net/5munzeja/
Answer: Boa noite rodrigo, tudo bem?
O que você pode fazer é guardar estas referências no próprio DOM, seja elas por id, classes ou etc. Isso vai depender muito da forma como você vai trabalhar, e o comportamento que você deseja.
Fiz uma pequena reprodução de algo que você pode tomar como base.

function deletarForm(id){
  const el = document.getElementById(id);
  el.remove()
 }
document.getElementById('btn').addEventListener('click', ()=> {
 const container = document.getElementById('container');
 const newContactField = document.createElement('div');
  const deleteButton = document.createElement('button');
  deleteButton.innerHTML = 'excluir';
  deleteButton.addEventListener('click', () => deletarForm(id));

  const id = `contato-${container.childElementCount}`;
  newContactField.id = id;
  newContactField.innerHTML = `
  <input type="text" placeholder="digite aqui">
    `
  newContactField.appendChild(deleteButton);
container.appendChild(newContactField);

});

<button id='btn'>Adicionar novo contato</button>

Esta é uma das estratégias, é algo bem básico porém vai te servir.
Answer: Na verdade tem vários problemas no seu código, sendo que o primeiro é a criação de id's repetidos. Repare que atribui um id igual a cada botão:
btn_delete.id = "btn-delete";

Que vai fazer com que tenha vários botões na página com id's iguais, o que está errado e em algum caso fará com que a sua página não faça algumas coisas corretamente.
Para além disse você atribui os novos elementos nas variáveis locais input, label, btn_delete e br criadas com var, logo só consegue chegar às ultimas criadas.
A solução mais simples e que torna o html correto é atribuir classes em vez de ids, e alterar a declaração das variáveis que guardam os novos elementos para let:

function addEmail() {
  var container = document.getElementById("box");

  let input = document.createElement("input");  //com let
  let label = document.createElement("label");  //com let
  let btn_delete = document.createElement("button"); //com let
  let br = document.createElement("br"); //com let

  input.type = "text";
  input.name = "email";

  label.innerText = "Email";
  label.htmlFor = "email";

  btn_delete.type = "button"
  btn_delete.innerText = "Deletar";
  btn_delete.classList.add("btn-delete"); //adicionar a classe com classList

  container.appendChild(br);

  container.appendChild(btn_delete);
  container.appendChild(input);
  container.appendChild(label);

  btn_delete.onclick = function() { //handler de click aplicado diretamente
     input.remove();
     label.remove();
     btn_delete.remove();
     br.remove();
  };
}

<button type="button" id="criar-input" onclick="addEmail()">Criar Novo Email</button>

Apenas alterei as linhas de código que tem comentários. A alteração da classe com o classList faz com que o seu html esteja correto, mas o que faz o remover funcionar é o let. Isso acontece devido aos closures que não são aplicados de forma igual ao var e let. Deve dar uma leitura no link dos closures para aprofundar mais sobre esse assunto.
Mantive a atribuição da classe para ser consistente com a lógica que tinha, mas da forma que o código está ela não é necessária para o remover funcionar, e é algo que pode retirar se quiser.
Claro que existem outras alternativas que não fazem uso desse pormenor, mas implicam trocar bem mais coisas no seu exemplo e algumas são mais elaboradas.
Uma alternativa simples é fazer uso de navegação no html, e para o seu exemplo poderia incluir todos os elementos num novo div, e eliminar esse div navegando pelo DOM com closest ou parentElement.

Deletar input dinâmico


Confused about if statement in R: Want to make conditional NA

Question: I am confused about the conditional if statement in R.
What I want:
Let's say there are two variables; Data$Export & Data$Sales,
Only if both Data$Export & Data$Sales for a row has the value '0', I want the row to be removed from the dataset. Or, as I thought, to set any variable in the row to NA, which will consequently be removed with:  "Data <- na.omit(Data) " anyway.
Therefore, I thought of the following construction:
for (i in 1:nrow(Data)) { if ( (Data$Sales[i] == 0) &(Data$Export[i] == 0 ) ) {Data$Sales [i] <- NA }}
Data <- na.omit(Data)

However, this does not work, the error code yields:
missing value where TRUE/FALSE needed
Thank you in advance for any help I may receive.
Comment: Please, try to provide a reproducible example https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: Please, consult `help("if")`. The description of the `cond` parameter in `if(cond) expr` says: *A length-one logical vector that is not NA. Conditions of length greater than one are currently accepted with a warning, but only the first element is used.* `if` is one of the basic control-flow constructs but not meant to work element-wise on a vector. There are vectorized equivalents as shown [here](https://stackoverflow.com/a/47956966/3817004) or `ifelse()`.
Answer: Data2 <- Data[Data$Export !=0 | Data$Sales != 0,]

Or to to set NAs
 Data[Data$Export !=0 | Data$Sales != 0,] <- NA

Answer: I think you don't need to use conditional if statement to do so. Using diamonds data.frame, you can remove rows that have 0 in both variables y and z as below. Thanks to @Moody, @Uwe and the OP comments, it should be | instead of &.
library(dplyr)
diamonds1 <-  diamonds %>%
  dplyr::filter(y!=0 | z!=0)

the same can be applied to your dataframe
data1 <- data %>%
  dplyr::filter(Sales!=0 | Export!=0)

Comment: So in the case there is only one zero the row should be kept, in your case it wouldn't be, OP used & with == because he was describing the rows to remove. To describe the rows to keep you need | with !=. But your answer was accepted so maybe it's what OP wanted after all :).
Comment: I'm seconding @Moody_Mudskipper. According to [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws), `!(A & B) = (!A | !B)`.
Comment: Hello! I ended up using " | " instead of & to obtain the desired result. Thank you all very much for the help.
Comment: You need | not & here to do what OP wants. And I would suggest you use subset rather than filter so you don't need to load dplyr
Comment: @Moody_Mudskipper
Thanks. The OP mentioned "Only if **both** Data$Export & Data$Sales for a row has the value '0'". Also, the OP used **&** in the code in the question. So, I thought & should be used.
Comment: Thanks Anouk. I updated the answer thanks to your comment, @Uwe and Moody_Mudskipper


Git repository based on subfolder of another repo

Question: I have a repo which contains a subdirectory.
I want to turn that subdirectory into a spin off git repo, and then add my own commits onto it.
I also want to be able to merge in changes from the original parent repo as and when they happen, but naturally only the commits which affect files in the subdirectory.
Is this a thing that can be done?
Comment: Do you plan to push changes back to parent repo?
Comment: And basically, if you are speaking not of some 5GB repository, nothing keeps you from using regular git workflow — clone your repo, commit into local master, pull regularly from origin, then merge origin/master into local master, repeat. I see no point of any extra steps here.
Comment: possible duplicate of [Detach subdirectory into separate Git repository](http://stackoverflow.com/questions/359424/detach-subdirectory-into-separate-git-repository)
Answer: This is exactly the situation the git subtree command was designed for. (Note that this is different from the "subtree merge strategy"). You can find out more about git subtree here:

git-subtree.txt (original documentation)
Alternatives To Git Submodule: Git Subtree
Comment: Thanks. I found this link useful: http://makingsoftware.wordpress.com/2013/02/16/using-git-subtrees-for-repository-separation/
Answer: The short answer: This is nontrivial, and I question whether it's worth your while.  I'd consider simply forking the entire repository and only making changes to the subdirectory.
That said, if you really need the subdirectory on its own, two basic options come to mind:

Simply copy the files from the subdirectory into a fresh repository and remove them from the old repository.  You'll lose history, but it's easy.
Create a new repository, add the old repository as a remote, and cherry-pick the commits from the old repository that modify the directory you're interested in.  This keeps history in the new repository, but it gives you a repository that contains a single directory, which you may not want.

Merging changes from the old repository is possible with the second strategy; you can simply cherry-pick commits from the old repository as you see fit.
Comment: I agree it is non trivial. However complexities of the project require it to be so; I want to distribute the subdirectory of as a separate extension. However, that subdirectory is part of the main repo, and subject to revision itself. Copy pasting files won't work. I need to be able to pull in parent changes.
Comment: I believe that cherry-picking could mess up with pushing changes back to parent.


How to test onclick in this object without id

Question: I'm trying to test the on-click on this object but i don't know how to get to i'm, anyone can help me?

Answer: Two intuitive alternatives:
browser.link(:onclick=>"addRemoveSelectedNumber(this);").click

You may have to escape the slashes in this one...
browser.image(:src=>"../../static/images/sec_core/delete.png").click

Answer: Use an XPath expression to find your element.
browser.link(:xpath, "//path/to/my/element/a").click

See: http://wiki.openqa.org/display/WTR/XPath


What is CorLoc which is used to evaluate object detection performance?

Question: I tried to understand this evaluatation method for object detection.
My understanding is, the neural networks will give a bounding box for a target object and CorLoc evaluates only positive images which contain the target class, and counts the percentage of images for IOU > 0.5:
CorLoc = (the boxes that IOU > 0.5) / (all boxes belong to the target class)
e.g. there are 100 bounding boxes for car, but just 60 bounding box's IOU > 0.5, so the corloc is 60/100 = 60%
I found this image where there are three bounding boxes:
red bbox means IOU < 0.5
green box means IOU > 0.5
CorLoc is therefore 2/3 = 66%
But I don't understand why ignore the rightmost motorbike
and why just evaluate CorLoc on traing dataset or something I need to know about corloc?
Answer: The Corloc is to compute the number of the right boxes you have been detected. The formulation is TP/TP+FP. The rightmost bounding box is neither TP or FP but FN. Thus there are only 3 detections(TP+FP) with 2 positive(TP). Corloc=2/3=66%
Answer: I guess Corloc is only about how many of the boxes your network has detected are actually right. So since there is no detection for the rightmost car (the yellow box is the gt) there are only 3 detections in total, two of which are correct(iou > 0.5) and one is wrong.


JPA - manytoone cascading

Question: I've got two entities
ServiceDownload.java
<code>@Entity
public class ServiceDownload implements Serializable {
    private static final long serialVersionUID = -5336424090042137820L;

@Id
@GeneratedValue
private Long id;
@Length(max = 255)
private String description;

private byte[] download;

private String fileName;

@ManyToOne
private Service service;
</code>
Service.java
<code>@Entity
public class Service implements Serializable {
    private static final long serialVersionUID = 4520872456865907866L;

@EmbeddedId
private ServiceId id;

@Length(max = 255)
private String servicename;

@Column(columnDefinition = "text")
private String highlightsText;
@Column(columnDefinition = "text")
private String detailsText;
@Column(columnDefinition = "text")
private String productText;
@Column(columnDefinition = "text")
private String dataText;

@ManyToMany(mappedBy = "services")
private Set<Machine> machines;

@OneToMany(targetEntity = ServiceDownload.class)
private List<ServiceDownload> serviceDownloads;

@OneToOne
private ServicePicture servicePicture;
</code>
When I create a new ServiceDownload Object and try to persists this I recieve a duplicate key exception. It seems that jpa tries to insert a new service object into the service table. How can I disable this behaviour?
Answer: You are using @GeneratedValue annotation for your @Id. According to JPA documentation, you should supply unique identifiers

By default, the application is responsible for supplying and setting entity identifiers (see @Id)

Try using a @SequenceGenerator and a sequence in your database to generate unique identifiers
Comment: @GenereatdValue must be set in my case, because I'm importing data from other databases.
Comment: Ok, then you should implement equals() and hashCode() to avoid inserting again retrieved instances from database

JPA - manytoone cascading


Nix: nixlang syntax how to change an existing set ? Syntax error unexpected '=' , expecting $end

Question: nix repl
nix-repl> test = {"a"=10;}
nix-repl> test.a
nix-repl> 10
nix-repl> test.a=20
error: syntax error, unexpected '=' , expecting $end, at (string):1:7

Expected result:
test = {"a"=20;}

I am currently learning nix and couldn't find the answer after a few minutes of google.
This seems rather simple and I'm sure someone instantly knows this.
Answer: Values in nix are immutable; you can't change the value of test.a, because that would require changing the set. You can only create a new set with a different a value.
nix-repl> test = {"a"=10;}

nix-repl> test // {"a"=20;}
{ a = 20; }

nix-repl> test
{ a = 10; }

nix-repl> test2 = test // {"a"=20;}

nix-repl> test2
{ a = 20; }

The // operator combines two sets, with values on the right-hand side overriding values on the left.
nix-repl> {"a"=10; "b"=20;} // {"a"="changed"; c="30";}
{ a = "changed"; b = 20; c = "30"; }

Comment: Note that you can bind ("assign to") a variable in the repl multiple times, but that only affects the meaning of that name in expressions you enter afterwards.


Match covered graph is 2-connected

Question: Seems to be an easy question, but I can't find the right direction.
Let $G$ connected graph on at least 4 vertices, such that every edge in it, participates in a perfect matching. Prove that $G$ is 2-connected.
Any help will be appreciated.
Thanks in advance.
Answer: Gerry Myerson has shown that $G$ must be $2$-edge-connected. Since you didn't specify which you meant, I'll show that $G$ must be $2$-vertex-connected.
Suppose that $G$ is not $2$-vertex-connected. Then there is a vertex $v$ whose removal disconnects $G$ into components $C_1,\dots,C_n$ for some $n\ge 2$. Fix $k\in\{1,\dots,n\}$, let $e$ be an edge from $v$ to $C_k$, and consider a perfect matching $M$ that includes $e$. $M$ cannot include any other edge incident at $v$, so the other edges of $M$ must lie in the components $C_1,\dots,C_n$. Thus, each of these components except $C_k$ must have an even number of vertices, and $C_k$ must have an odd number of vertices. Now choose $i\in\{1,\dots,n\}\setminus\{k\}$; the same argument shows that $C_k$ must have an even number and $C_i$ an odd number of vertices. This contradiction shows that $G$ must be $2$-vertex-connected.
Comment: I indeed meant vertex connectedness. Interesting approach. Thank you.
Answer: If $G$ has a perfect matching, it has an even number of vertices. Suppose there's an edge $e$ whose removal disconnects $G$. Removing that edge splits $G$ into two pieces. Either each piece has an even number of vertices, or each piece has an odd number of vertices.
If each piece has en even number of vertices, then $e$ can't be part of a matching, since the other edges in the matching must each be wholly in one of the two pieces, so you must get a matching on each of the pieces, but once you've used $e$ each piece has an odd number of veertices.
If each piece has an odd number of vertices, then $e$ must be a part of every matching, and you can't use any edge that meets $e$ at a vertex. For if you use such an edge, that leaves an odd number of vertices in the piece containing that edge, and there's no matching there.
Comment: Although I meant vertex connectedness, it gives another perspective. Thanks.

Match covered graph is 2-connected


AWK to use multiple spaces as delimiter

Question: I am using below command to join two files using first two columns.
awk 'NR==FNR{a[$1,$2]=substr($0,3);next} ($1,$2) in a{print $0, a[$1,$2] > "br0102_3.txt"}' br01.txt br02.txt

Now, by default AWk command uses whitespaces as the separators. But my file may contain single space between two words, e.g.
File 1:
ABCD               TEXT1 TEXT2                     123123112312312312312312312312312312
BCDEFG             TEXT3TEXT4                      133123123123123123123123123125423423
QWERT              TEXT5TEXT6                      123123123123125456678786789698758567

File 2:
ABCD               TEXT1 TEXT2                     12312312312312312312312312312
BCDEFG             TEXT3TEXT4                      31242342342342342342342342343
MNHT               TEXT8 TEXT9                     31242342342342342342342342343

I want the result file as ;
ABCD               TEXT1 TEXT2                     123123112312312312312312312312312312 12312312312312312312312312312
BCDEFG             TEXT3TEXT4                      133123123123123123123123123125423423 31242342342342342342342342343
QWERT              TEXT5TEXT6                      123123123123125456678786789698758567
MNHT               TEXT8 TEXT9                     31242342342342342342342342343

Any hints ?
Answer: awk supports a regular expression as the value of FS so you can specify a regular expression that matches at least two spaces. Something like -F '[[:space:]][[:space:]]+'.
$ awk '{print NF}' File2
4
3
4

$ awk -F '[[:space:]][[:space:]]+' '{print NF}' File2
3
3
3

Comment: great! thats working, now I am using command `awk -F '[[:space:]][[:space:]]+' 'NR==FNR{a[$1,$2]=$3;next} ($1,$2) in a{print $0, a[$1,$2] > "br0102_4.txt"}' br01.txt br02.txt`. But between the concatenation of the records from the two file for any row, I see a Line Feed LF character, any hints on avoiding that ? So the joined rows are split into two rows.
Comment: `print $0, a[$1,$2]` should be outputting the line from the second file followed by `OFS` (space by default) and then the value of `a[$1,$2]` followed by `ORS` (newline by default). Is your first input file perhaps a DOS newline file?
Comment: This helped me parse the output of a system command that always uses at least 2 spaces to delineate columns, so many thanks!
Answer: You are using fixed width fields so you should be using gnu awk FIELDWIDTHS (or similar) to separate the fields, e.g. if the 2nd field is the 15 chars from char 8 to char 23 inclusive in this file:
$ cat file
abc    def ghi        klm
AAAAAAAB C D E F G H IJJJJ
abc       def ghi     klm

$ awk -v FIELDWIDTHS="7 15 4" '{print "<" $2 ">"}' file
<def ghi        >

<   def ghi     >

Any solution that relies on a certain number of spaces between fields will fail when you have 1 or zero spaces between your fields.
If you want to strip leading/trailing blanks from your target field(s):
$ awk -v FIELDWIDTHS="7 15 4" '{gsub(/^\s+|\s+$/,"",$2); print "<" $2 ">"}' file
<def ghi>

<def ghi>

Answer: awk automatically detects multiple spaces if field seperator is set to " "
Thus, this simply works:
awk -F' ' '{ print $2 }'

to get the second column if you have a table like the one mentioned.
Comment: _"Thus, this simply works:"_ it doesn't, does it? You are not telling `awk` to distinguish between single and multiple spaces, namely multiple spaces being the delimiters and single spaces columns being considered as single column instead. You're essentially just printing the second character after any number of spaces, in your example (thus not returning `TEXT1 TEXT2` instead as indicated).

AWK to use multiple spaces as delimiter


How to email the results of a filtered view to a user?

Question: Required functionality (Drupal 7):

User filters a view to desired results
User enters email address in a
webform block
User is emailed the filtered list of results

I'm using Views (7.x-3.14), Webform (7.x-4.14) and Rules (7.x-2.9)
I've looked at a few modules surrounding saving your search results, but nothing I've found seems to help very much. Are there a combination of modules that I might be able to use (Rules, Cron etc.) that will achieve this or do you think I'll need to write something custom?
I'm still learning how to write custom Drupal modules so if anyone can point me in the right direction, that would be appreciated !
Comment: How this action should be triggered, via a link, on submit, something else?
Answer: If your view is a page, should be as easy as grabbing the page url when the form gets submitted and based on the url (if statement) you attach a view that has a filter of "X". (slight chance that it is doable with rules and webform module)
If it's a block, gets a bit more complex. You would have to check what the filter is set to using jQuery, and then pass that variable to a custom module when the form is submitted. Then module triggers x function based on the view filter value that sends e-mail with view x.

Actually, an even more simpler option, have a hidden field of checkboxes (hide it with css) on your webform that has a box for each filter. Then with jQuery you can autocheck option x if filter is set to x.
Now since your webform contains  field of checkboxes with value x, with conditional rules hopefully you can do an if statement on your field of checkboxes and attach view x to your e-mail. (I'm making a lot of assumptions here, as I've never used webform + rules, or maybe I did once... Anyhow, hopefully this will work with Rules)


mat-table from `{foo: {bar: 5, can: 6}, haz: {bar: 7, can: 8}}`?

Question: Goal:
-------------------
|     | foo | haz |
-------------------
| bar | 5   | 7   |
| can | 6   | 8   |
-------------------

It seems like a trivial thing to want… but at second glance it seems quite complicated with all the explicit required:
<ng-container matColumnDef="score">
     Score
     {{user.score}}
</ng-container>

What am I missing here, is there not some simple way of construct a material table from that input?
Comment: Can you be more specific, what exactly are you trying to achieve?
Comment: I am trying to generate a mat-table from this simple nested object.
Comment: There is a fully functioning example of using a simple input object array like that in the web documentation. Have you reviewed that yet?
https://material.angular.io/components/table/overview
Comment: There are no arrays in my examples… and the headers and column headers aren't known ahead of time.
Comment: There is no simple way to construct the table from that input. You would need to parse out the column names with Object.keys(tableObj), then you would need to construct an object for each row and add it to an array. I suppose I could try to throw an example together for you, are you sure you can't structure your table data in a better way?
Answer: This can be done using Object.keys() and Object.reduce() through below code.
private baseData = {
  foo: {bar: 5, can: 6},
  haz: {bar: 7, can: 8}
};

columnNames: string[];
data: any[];

ngOnInit() {
  this.columnNames = [' '].concat(Object.keys(this.baseData));
  const objects = Object.keys(this.baseData).map(key => this.baseData[key]);
  this.data = Object.keys(objects[0]).reduce((acc, k) => {
    const entry = { ' ' : k };
    objects.forEach((o, i) => entry[this.columnNames[i + 1]] = o[k]);
    acc.push(entry);
    return acc;
  }, []);
}

Please have a look at the following StackBlitz.
Answer: Here is a modified stackblitz of the basic example for mat-table:
https://stackblitz.com/edit/angular-cj5c3w
You cannot get around using an array for the data source on a mat-table, but this should do what you wanted. You'll have to check for side effects and edge cases.


How to show that $\int_{0}^{\infty}e^{-x}(x^2+3x+3)\cos(x){\mathrm dx\over (1+x)^3}=1?$

Question: How to show that $(1)$ is
$$\int_{0}^{\infty}e^{-x}(x^2+3x+3)\cos(x){\mathrm dx\over (1+x)^3}=1?\tag1$$
$$x^2+3x+3=\left(x+{3\over 2}\right)^2+{3\over 4}$$
$$\int_{0}^{\infty}e^{-x}\cos(x){\mathrm dx\over (1+x)^3}+\int_{0}^{\infty}e^{-x}\left(x+{3\over 2}\right)^2\cos(x){\mathrm dx\over (1+x)^3}=I_1+I_2\tag2$$
$$(1+x)^{-3}=\sum_{n=0}^{\infty}(-1)^n{n+2\choose n}x^n$$
$$\sum_{n=0}^{\infty}(-1)^n{n+2\choose n}\int_{0}^{\infty}x^{n}e^{-x}\cos(x)\mathrm dx=I_1\tag3$$
$$\sum_{n=0}^{\infty}(-1)^n{n+2\choose n}\int_{0}^{\infty}x^{n}e^{-x}\left(x+{3\over 2}\right)^2\cos(x)\mathrm dx=I_2\tag4$$
Answer: Start with partial fractions:
$$ \frac{x^2+3x+3}{(1+x)^3} = \frac{1}{1+x} + \frac{1}{(1+x)^2} + \frac{1}{(1+x)^3} $$
Now let
$$ J_k = \int_0^\infty e^{-(1+i)x}\frac{dx}{(1+x)^k} $$
Integrating by parts,
$$ J_k = \frac{1-i}{2} - \frac{((1-i)k}{2} J_{k+1} $$
Using this for $k=1$ and $k=2$,  $J_1 + J_2 + J_3$ simplifies to $1 - i/2$.
Your integral is the real part of this, namely $1$.
Comment: Much simpler than my gymnastic !
Answer: What I should do is to consider $$I=\int\frac{e^{-x} \left(x^2+3 x+3\right) \cos (x)}{(x+1)^3}\,dx$$
$$J=\int\frac{e^{-x} \left(x^2+3 x+3\right) \sin (x)}{(x+1)^3}\,dx$$
$$K=I+iJ=\int\frac{e^{(-1+i) x} \left(x^2+3 x+3\right)}{(x+1)^3}\,dx$$ Because of the cube in denominator, let us assume that $$K={e^{(-1+i) x}}\frac {P_n(x)}{(x+1)^2}$$ where $P_n(x)$ is a polynomial of degree $n$. This makes
$$K'=e^{(-1+i) x} \frac{(x+1) P_n'(x)-(1-i) (x+(2+i)) P_n(x)}{(x+1)^3}$$ So, to have an $x^2$ in the numerator of the integrand, we need $n=1$. Let $P_1(x)=a+b x$ and replace in $K'$. This yields to $$x^2+3x+3=(-1+i) b x^2+ ((-1+i) a-(2-i) b)x-(3-i) a+b$$ Comparing coefficients, this leads to $$b=-\frac{1+i}2\qquad a=-1-\frac i2$$ So, we know $K$.
Now, use the bounds and take the real part of it to get your result.
Comment: @123. In practice, you just need to evaluate $K$ for $x=0$ which is $a$
Answer: By partial integration, we have
\begin{align}
&\int_0^{+\infty}\frac{e^{-x}\cos x}{1+x}dx
=\int_0^{+\infty}\frac{e^{-x}}{1+x}d\sin x\\
&=\left.\frac{e^{-x}\sin x}{1+x}\right|_0^{+\infty}
+\int_0^{+\infty}e^{-x}\sin x\left[\frac{1}{1+x}+\frac1{(1+x)^2}\right]dx\\
&=0-\int_0^{+\infty}e^{-x}\left[\frac{1}{1+x}+\frac1{(1+x)^2}\right]d\cos x\\
&=\left.e^{-x}\cos x\left[\frac{1}{1+x}+\frac{1}{(1+x)^2}\right]\right|_0^{+\infty}
-\int_0^{+\infty}e^{-x}\cos x\left[\frac{1}{1+x}+\frac2{(1+x)^2}+\frac2{(1+x)^3}\right]dx\\
&=2-\int_0^{+\infty}e^{-x}\cos x\left[\frac{1}{1+x}+\frac2{(1+x)^2}+\frac2{(1+x)^3}\right]dx,
\end{align}
then
$$
\int_0^{+\infty}e^{-x}\cos x\frac{x^2+3x+3}{(1+x)^3}dx
=\int_0^{+\infty}e^{-x}\cos x\left[\frac{1}{1+x}+\frac1{(1+x)^2}+\frac1{(1+x)^3}\right]dx
=1.
$$


Syntax for set_fact

Question: I have my Ansible inventory file as:
[dev_web:children]
dev_www
dev_auto

[dev_www]
web01_dev    ansible_host=web01-dev.company.com
web02_dev    ansible_host=web02-dev.company.com
web03_dev    ansible_host=web03-dev.company.com

[dev_auto]
auto_dev     ansible_host=auto-dev.company.com

Ansible playbook "/deploys/patch.yml" as:
- name: patch
  hosts: "{{ configs_target | default('test_servers') }}"
  serial: 1
  vars:
    slack_token: 'slack-token'
    slack_channel: 'slack-channel'
  roles:
    - patch

Main Ansible playbook file "/deploys/roles/patch/tasks/main.yml" as:
---
- name: Include vars of patch.yml
  include_vars:
    file: backend_vars.yml
    name: web_servers

- name: set needed facts
  set_fact:
    backend_name: "{{ [cache_mgmt][configs_target]['backend_name'] }}"

Variable file "/deploys/roles/patch/vars/backend_vars.yml" as:
cache_mgmt:
  dev_web:
    backend_name: www_http_be
    backend_hosts: dev_www
  dit_web:
    backend_name: www_http_be
    backend_hosts: dit_www

The run command I execute is:

ansible-playbook /deploys/patch.yml -e '{"configs_target":"dev_web"}'

When I run the playbook, I expect the value of variable to be backend_name: www_http_be. But, it fails with below error.
TASK [patch : set needed facts] *****************************************************************************************
fatal: [web01_dev]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'dev_web'\n\nThe error appears to be in '/deploys/roles/patch/tasks/main.yml': line , column , but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: set needed facts\n  ^ here\n"}

I believe the issue is with the syntax for set_fact. If that is true, what should be the correct form in this case?
Comment: See https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-complex-variable-data => `cache_mgmt[configs_target]['backend_name']` or `cache_mgmt[configs_target].backend_name`
Comment: @Zeitounator, Thanks for the help but none of them worked. I still get the variable `backend_name` not loading with the value `www_http_be`.
Comment: https://gist.github.com/zeitounator/6f5d02c1539b1edd0002d2e20c00113d
Answer: Since the vars are being called from a variable file, we'll have to mention the assigned name as well. The correct syntax is "{{ web_servers['cache_mgmt'][configs_target]['backend_name'] }}"

Syntax for set_fact


How to make "Page specific visibility settings" for blocks more flexible?

Question: My problem is that depending on a running mode my Drupal website might have either regular permalinks, or pretty, aliased ones. And "Page specific visibility settings" for blocks on specific pages (Show on only the listed pages) do not work across the modes.
It would be logical if let's say: node/23 syntax could work in any case, but it seems that it doesn't.
Do I have to change every setting for every block every time I switch permalink structure? Or there is more flexible solution to this?
Comment: Page visibility settings, just like everything else, should always work with the internal path and *not* the alias. Not sure what you are experiencing there...
Comment: Can you be more specific about what you mean by modes? What does that mean 'change permalink structure?" Are you using the Pathauto module?
Comment: I mean that sometimes it's the usual: domain.com/?q=node/23 and sometimes it's domain.com/about-us. "Page specific visibility settings" seem to work only for whatever version I have defined in there: node/23 works only for domain.com/?q=node/23 and about-us only for - domain.com/about-us
Comment: Weird... I'm just doing a redesign for a theme, written by someone else and there are aliases everywhere for blocks in "Page specific visibility settings" section.
Answer: If you need to control block visibility then the Context module is the way to it.
(edit) If you use the Context module you won't have to mess around with these types of things and more importantly neither does Drupal which in fact makes it faster. You can read more about Blocks, Context and Panels, another alternative to Blocks, here.
Answer: Below is a solution that should work for domain.com/?q=node/23 AND domain.com/about-us (as in one of the comments), by using the Rules module.
Part 1: Rules block visibility
Have a look at the Rules block visibility module. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?
Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules intercept the actual URLs your using.
Part 2: Create an appropriate Rules Component
The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

Configuration is done on a per-block basis. To control a block
  visibility using a rule component, go to the block settings page,
  scroll down to the "Rules" tab, and select the Rules component that
  you want to use.
Notice that to be able to be used by this module, a Rules component
  must be constructed in a very specific way. See the next section for
  more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.
By looking at these samples, I was able to create another Rules Component which looks like so:
{ "rules_block_visibility_hide_block_for_user_1" : {
    "LABEL" : "Hide block for user 1",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : "1" } }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

What this Rules Component does is "only" return a boolean (1 or 0), based on the condition if the user's uid is YES or NO equal to 1.
You should be able to import this rule in your own environment. After you do, you should replace the Rules Condition. Which in the example here was about which user is using the site, i.e. if it is YES or NO (a boolean, right?) the user with uid = 1.
With that, we're coming close to an actual answer to your question.
Part 3: Set Block Visibility using the Rules Component
Head over to the "Block" settings for the block(s) you want to hide. At the bottom of its settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "Rules". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.".
So to complete the picture, you just select the Rules Component from Part 2 (which you should have tuned to fit your URL requirements).
Part 4: Further refinements
If you have a lot of such nodes, you may want to also add the Rules URL Argument module to the mix. Have a look at my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?" to get an idea what you can do with that module.
Note: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.


Lowering the action on a bass guitar

Question: I have obtained a rather cheap P-bass imitation bass and, while it plays well in the lower register, about the 9th fret the action starts to rise and after the 12th fret it's in to the "wow, this actually getting harder to fret" territory.
How do I approach troubleshooting why the action is high? How do I go about adjusting the bass to lower the action?
Comment: Wish I could accept multiples on this one guys. Between the three answers I got: a technique to check for bowing, figured out it was bowed, and a good link on truss rod adjustments. Now to straighten this guy out...
Answer: Definitely check that the neck is not bowed first.  If it is, truss-rod adjustments can fix a lot of problems in limited ways.  Too much of a bow, and no amount of truss-rod adjustment will fix it.  If everything looks fine there, then you have two things to consider, action wise: height of the nut, and height of the bridge.
If your instrument plays fine at the first position, but the action is too high above the twelfth fret, then just lowering the action at the bridge might not be enough.  It could make the action too low at the head.  You would then have to raise the string height at the nut.  this would require a new nut, as the slots cut into the current nut are too.
Also, after adjusting the action, you will need to check the intonation to make sure the string length is still right for the fret spacing. (even a millimeter off can make playing in the higher positions sound out of tune compared to the lower positions).
If you feel confident that you can make these adjustments, then take a stab.  You can also find a reputable repair shop in your area and take it there, but if all you want is a playable bass, you might end up spending more time/money on repairs and adjustments that the bass is actually worth, depending on what is wrong.
Answer: First of all, I would check whether the neck is straight.
Place a ruler against the frets (the edge of the ruler against the frets) and if there is any space between any of the frets and the ruler, the neck is not entirely straight. If there is no access to any sort of truss rod adjustment, then you will probably have to put up with the high action. If there is a bow in the neck, the action will appear higher at higher frets. If you lower the saddles in order to fix that high action, you will get fret buzz at the lower frets.
If the frets are straight, try adjusting the action at the bridge. Nearly all basses have a setting somewhere on the saddles that allows height adjustment. Once you have them a comfortable height, or the lowest you can without any buzzing, you will need to check, and possibly, fix the intonation.
Tune the guitar to pitch using a tuner. Play the 12th fret harmonic on the string, and then the 12th fret note. In short, the rule is:

If the fretted note is higher (sharper) than the harmonic, then the length of the string needs to be lengthened. If the harmonic note is sharper, then the length of the string needs to be shortened.

The way you adjust string length depends on the type of saddle, but most cheapo basses usually have a Phillips screw of some sort that you can adjust.
There might be a problem with the nut, but I don't know a lot regarding them.
In this case, I would usually recommend the instrument be taken to a guitar tech. They usually do a fantastic job on fixing the instrument's little niggles straight (and your bowed neck if necessary), you will be able to hear and feel the difference when you get it back. Depending on the service, it may be a tad pricey (£40/$64) but as you say the bass is pretty cheap, so it shouldn't hurt too much anyway. You can always fix further issues yourself, but whenever I happen to acquire an instrument I always like to have it perfect and go from there.
Hope this helps :)
Answer: It sounds like the neck is not straight. Ensure it is bolted or otherwise attached to the body, and then check up at the nut for an allen wrench slot. Many necks have an adjustable tension (truss) rod. ( see: http://www.tunemybass.com/bass_setup/adjusting_neck_relief.html )
When done improperly, this can break the neck, so...don't break the neck.
Comment: Just to add to this - A good way to check if the neck is too bowed is to put the bottom of the guitar on your foot, and look down the neck from above the headstock.
Comment: I wouldn't recommend messing with the truss rod without the oversight of someone who knows what they are doing. You won't break the neck unless you tighten the everlovin' bejeezus out of it, but you can warp it with less tension if you don't know what you're doing.
Comment: I agree: READ UP on the subject a little first. The above link I gave was just a basic intro.
Answer: A few comments on the above:

Don't be afraid to make a minor truss rod adjustment, BUT... Always make absolutely certain you have the correct size wrench and it is fully seated in the nut. If not, you can easily break the truss rod nut. Never make a single adjustment over 1/8-1/4 turn. After every truss rod adjustment let the instrument "settle-in" a day before making another adjustment.
Capo at the first fret and fret a string at the 15th. The string is a dead-straight line from which you can check for any curvature in the neck.
If the action at the 1st fret is good, saddles are bottomed out, the neck is straight and the action remains ridiculously high you may need to shim the neck. If so, use a true wood shim that is cut to fit the full neck pocket - don't do a half_*ss thing like using a pick, credit card sliver, etc. as a shim. (The reasons for this can be found online, but let's cut to it and say shortcuts can ruin your neck).

Try only as much as you really know how to do. After that, get your instrument to a luthier or competent guitar-tech.

Lowering the action on a bass guitar


Definir id da array() php

Question: Tenho a seguinte array()
Array
(
    [camposdb] => Array
        (
            [51] => Array
                (
                    [0] => cpf_cnpj
                    [1] => nome_razaosocial
                    [2] => cod_cliente
                    [3] => cod_contrato
                    [4] => mensagem
                    [5] => mensagem
                    [6] => mensagem
                )

            [60] => Array
                (
                    [0] => celular
                    [1] => nome_razaosocial
                    [2] => nome_razaosocial
                    [3] => cod_contrato
                    [4] => mensagem
                    [5] => mensagem
                    [6] => telefone_r_1
                )

        )

)

No meu form, seleciono os registros do banco de dados, e coloco os inputs dessa forma: camposdb[$row_fetch['id']][] que me trazem o resultado acima.
O que eu preciso fazer é o seguinte...
UPDATE tabela SET (cpf_cnpj, nome_razaosocial....) WHERE id = 51

.
A pergunta é: Como eu faço para definir que 51 e 60 são ids sendo que eles são dinâmicos?
$id = $campodb[0][???]

Answer: Para buscar as chaves do seu array do exemplo acima utilize o array_keys para extrair as duas chaves que são os id que precisa:

$array = array(
    "camposdb" => array(
        51 => array(
        ),
        60 => array(
        )
    )
);

$id = array_keys($array['camposdb']);
echo $id[0]; //51
echo $id[1]; //60

Nesse exemplo ilustra bem e soluciona a duvida da busca da chave array.
Após edição, para fazer uma busca dinâmica (entendi assim), utilize um foreach para pegar as chaves e depois dentro você consegue pegar as informações de cada chave, onde variável $key é o id do banco:
foreach(array_keys($array['camposdb']) as $key)
{
    $dados = $array['camposdb'][$key];
}

Exemplo
Comment: @AndréBaill eu segui o exemplo passado logo acima, e agora eu não entendi como os seus dados vem, então uma edição na sua pergunta ajudaria entender...
Comment: Ok, deu certinho, era bem isso mesmo que eu precisava @VirgilioNovic, muito obrigado!
Comment: Meus dados vem do $_POST, neste caso o nome dos campos são: camposdb[][]
Comment: Editei minha questão, talvez compreenda um pouco melhor :)
Comment: Neste caso, eu posso colocar $array = $_POST; ?:
Comment: @AndréBaill para pegar as chaves que podem ser dinâmicas ou não os dois códigos estão ai como exemplo do array que você passou. A função `array_keys` pega as chaves que no caso é **51** e **60** com essas chaves dentro do `array` principal eu faço `array['camposdb'][$key]` que são todas as informações do id selecionado. No exemplo do for a variável dados vai pegar todas as informações de cada id.
Comment: Sim pode. sem problemas @AndréBaill ...

Definir id da array() php


What is the exit code after a php exception?

Question: I'm working with a program that runs a command-line PHP script. The PHP script has been throwing exceptions, but the program has been seeing exit code 0 (and not checking for exceptions).

Do PHP scripts actually return a different exit code and the program is just getting the wrong exit code somehow?
Or do they really return exit code 0 with an exception?
Or do they not return an exit code at all?
Comment: Why don't you check that on your own with a simple example script?
Comment: @NicoHaase A simple script like what? If you have an idea, please just post an answer like Philipp did. I made this question because I'm at the end of my rope and don't know what to do.
Comment: The manual http://php.net/manual/en/function.exit.php states: *"The status 0 is used to terminate the program **successfully.**"* - So why would an exception be of any use?
Comment: @FunkFortyNiner The script was throwing exceptions because it wasn't terminating successfully
Comment: @Miryafa Oh, I see. 10-4 :-)
Answer: In case of a exception, the return status code is 255. You could simply test this inside your bash with a simple script.
exc.php
<?php throw new Exception();

and run
php exc.php
echo $? //prints 255

However, you should keep in mind, this is only valid, if you don't define your own exception handler. In case you define your own handler, you have to return the return code manually inside the exception handler.
exc2.php
<?php
set_exception_handler(function() {});
throw new Exception();

returns status code 0. If you want an status code, use exit
<?php
set_exception_handler(function() {
    exit(42);
});
throw new Exception("","","");

now the script returns the status code 42


Software for multiple logistic regression analysis

Question: Which free and easy to use statistical software can I use to perform a multiple logistic regression analysis?
Answer: JASP. It is a graphical user interface that is pretty user-friendly and runs the R programming language underneath. There are lots of tutorials online for this and a dedicated community that keeps it running.
Comment: Thank you! I will try this.


Execute bash script on multiple input files, ignoring other input variables

Question: I'm using Mac's Automator to perform a bash script on files that are dropped onto a droplet. Inputs are gathered from Automator actions and are passed to a bash script as arguments. The script works with a single input file, but I'm having trouble handling multiple files.
My ultimate goal is to accept several dropped video files, prompt for a number, and extract that number of frames from each video file (using FFmpeg).
I can loop through inputs by using the special variable $@, like so:
for f in "$@"; do
    # perform an action
done

However, my script also prompts the user for text input that I don't want included in this loop.
I can access each input file individually by using $1, $2, etc. But I'd like to use a loop instead of referencing each file individually. Also, the quantity of input files is unpredictable and I'm not sure how to distinguish between input files and input text.
How can I loop through only the file inputs without including the text input?
Here is a description of my current workflow:

Get Specified Movies

one.mov
  two.mov

Set Value of Variable (accepts input)

source_files

Ask For Text (ignores input)

Enter a Number:

Set Value of Variable (accepts input)

number

Get Value of Variable (ignores input)

source_files

Get Value of Variable (accepts input)

number

Run Shell Script (accepts input, pass "as arguments")
#/bin/bash

for f in "$@"; do
    echo $f
done

OUTPUT:

/folder/one.mov
  /folder/two.mov
  8

I was hoping to have one variable set to the multiple inputs (so I could loop through it) and another variable set to the number, but it doesn't seem to work that way.
How can I loop through each input file without referencing the text input?
Comment: Ah. I misunderstood that. Then yes, the given answer is appropriate or look into real argument parsing in the script. Something like [Bash FAQ 035](http://mywiki.wooledge.org/BashFAQ/035).
Comment: Are you just trying to find out how to test whether a given argument is an existing file?
Comment: That might be a solution. Do you think that's the best way? My ultimate goal is to accept several video files dropped onto a droplet, prompt for a number, and extract that number of frames from each video. I was hoping to have one variable set to the multiple inputs (so I could loop through it) and another variable set to the number, but it doesn't seem to work that way.
Comment: How many text input variables do you have? Only _number_?
Comment: @MarioZannone Yes, just one: *number*.
Comment: It can work that way if you stop using multiple scripts for this and/or use exported variables instead of arguments for communication between the scripts. That being said do you need the files as arguments at all? Wouldn't a directory of files to operate on be simpler?
Comment: @EtanReisner That sounds promising. What do you mean by "using multiple scripts"? How does one use "exported variables"? Processing files in a directory might be a solution. I was hoping to eventually handle any number of dropped items: a single video file, multiple video files, an entire directory. But I'm not quite there yet.
Comment: Your problem is that you have one script (I assume) which takes all the input and then calls another script with those values (from variables). Just stop using a second script and you have the values you need split into variables you can use directly, no?
Comment: @EtanReisner The inputs are gathered from Automator actions (`Get Specified Movies` and `Ask For Text`) and are passed to a bash script as arguments (`Run Shell Script`).
Answer: Just change the order of the args: get value of variable number first,
then get value of variable source_files,
so that number will be the first parameter,
then:
echo number: $1
for f in "${@:2}"; do
    echo file: $f
done

Comment: Technically there's no need for `shift` here. You can use `"${@:2}"` instead. Look for `offset` in the [Shell Parameter Expansion](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion) section of the bash reference manual.
Comment: Nice and simple. I guess I was making things more complicated than I needed to. `shift` is helpful. Thanks!
Comment: @EtanReisner Hey, that's cool thanks. That way I don't need to destructively manipulate the original set of inputs. I appreciate the reference link, too.
Comment: @EtanReisner Agreed! I modified the sample code according to your suggestion.


Check if the entity is new from the entity insert hook

Question: I have a custom content type, when I create a new content of this type via the admin ui I want be redirect to the edit page of the new node (not to the view page by default)
So, from an alter form hook, it's not possible because I don't know yet the node ID of the future node. From hook_entity_presave() it's the same: I don't know yet the node ID of the future node. From hook_entity_insert() hook, I have the node ID, but I don't know how can I check the entity is just created.
From hook_entity_insert(), is it possible to know if the entity is just created?
Answer: hook_entity_insert() is invoked only when an entity is created, not updated. That is evident from the method invoking it, EntityStorageBase::doPostSave().
  // Allow code to run after saving.
  $entity->postSave($this, $update);
  $this->invokeHook($update ? 'update' : 'insert', $entity);

hook_entity_update() is invoked for an entity being updated; otherwise hook_entity_insert() is invoked.
See also the description for the $update parameter passed to EntityStorageBase::doPostSave().

bool $update: Specifies whether the entity is being updated or created.