Table design with postgresql

Question: I am working on an inventory management system. In the back-end we are using POSTGRESQL database. We are having 3 tables:
1. invoice:
   a. invoice_no CHARACTER VARYING(20), //PK stores the invoice no.
   b. invoice_date DATE, //stores the invoice date.
   c. party INT. //FK party.id the id of the party of the invoice.

2. invoice_item:
   a. invoice_no CHARACTER VARYING(20) //FK invoice.invoice_no,
   b. invoice_serial INT, //stores the invoice item serial no.
   c. item INT, //FK item.id stores the id of the item.
   d. quantity INT, //stores the quantity of the item.
   e. discount NUMERIC, //stores the discount given on the item.
   f. tax NUMERIC, //stores the amount of tax applicable.
   g. total NUMERIC. //stores the total amount including tax and reducing discount of the item.
//columns invoice_no and invoice_serial is the PK of this table.

3. inventory:
   a. inventroy_id SERIAL //PK auto generated serial.
   b. purchase_invoice_no CHARACTER VARYING(20), //FK inventroy_item.invoice_no
   c. purchase_invoice_serial INT, //FK invoice_item.invoice_serial.
   d. sales_invoice_no CHARACTER VARYING(20), //FK inventroy_item.invoice_no
   e. sales_invoice_serial INT, //FK invoice_item.invoice_serial.
   f. quanity INT. //stores the quantity of item transacted.
//If the item is in stock then the sales_invoice_no and sales_invoice_serial is null.

All the invoices, sales and purchase, are stored in the invoice table.
When the sales invoice quantity is less than purchase invoice quantity, then a new entry is made in the inventory table with the sales and purchase invoice items and the sales quantity and reducing the quantity in the entry having sales invoice item as null by the amount sold.
The actual data is stored in  partitioned tables of invoice, invoice_item, and inventory based on the year so we have say for year 2015 -> invoice_2015, invoice_item_2015 and inventory_2015 with all the constraints of the parent tables. But this creates a new problem as some items are purchased in 2014 and sold in 2015. As a result when those items invoices are being stored, there is a foreign key violation as the inventory_2014 has the purchase invoice item but the sales invoice item is present in the table invoice_item_2015 but the inventory_2014 can only refer to invoice_item_2014 table.
Can you suggest me a way to overcome this problem or any suggestions on change in the design. Thanks.
Comment: I am using `stored procedures`. But that is not the answer to my question.
Comment: What do you mean by "slower"? What do you mean by "increased"? What queries? Where are indexes? It's hard to talk about performance if we don't have any information.
But not using varchar for PK is usually a good idea.
Comment: Are you using queries or stored procedures? Try stored procedure it will work little faster!!
Comment: "The queries", what queries? And could you please post the results from EXPLAIN ANALYZE of these queries at http://explain.depesz.com ? Without this information, it's next to impossible to help you.
Comment: There is no magic bullet, just ask an interesting question, with all the required information up front, show that you've done your work and respond quickly (I don't see anything particularly wrong with anything you've done thus far). However, understand that sometimes your question won't be answered. See also: http://stackoverflow.com/help/how-to-ask
Comment: How many rows per year for each of those tables? You're probably better off without partitioning.
Comment: @JakubKania my primary problem is that after I started partitioning those tables according to year,  created a new problem as some items are purchased in 2014 and sold in 2015. As a result when those items invoices are being stored, there is a foreign key violation as the inventory_2014 has the purchase invoice item but the sales invoice item is present in the table invoice_item_2015.
Comment: I have modified the question for better understanding.
Comment: @Blip "Urgent" etc... are not useful pieces of text for titles. See first answer and comments on it from http://meta.stackoverflow.com/questions/255196/remove-help-please-from-titles
Comment: @NathanKoop I accept you edit but could you suggest me a way to draw attention from genuine people
Comment: @Blip I haven't used postgresql, nor table partitioning, but if they're seperate tables (per your post), then you'd need to migrate the data to them, so at the end of each year you'd "close 2014" and "open 2015", so you could create audit entries that "sell" your product to yourself on Dec 31st at 11:59pm. However, there may be much more elegant ways to handle this via postgresql.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75301/discussion-between-blip-and-nathan-koop).
Answer: I suggest you drop partitioning in favor of partial indexing and annual clustering.  Partitioning is an exotic solution for exotic problems and not the go-to solution for ordinary problems, at least in PostgreSQL.
If you cannot do this, then the next best would be to have a narrow join table that everything references, which is trigger-maintained.

Table design with postgresql


IsMouseOver trigger for DockPanel not firing unless children are hovered over

Question: This question has been asked a couple of times before, but at this time, none of the answers I've found turned out to be working.
So I have a custom DockPanel with 2 child elements inside, 1 TextBox and 1 Image.
I intended to have the DockPanel change color on hover, so I put a Trigger inside of it. But currently, it only changes color if I hover over the children, whereas a hover over whitespace between elements doesn't do anything.
I've read similar posts which mentioned using isHitTestVisible, but it doesn't do anything.
Short version of my code is the following:
<DockPanel>

    <DockPanel.Style>

        </Style>
    </DockPanel.Style>

    <StackPanel Orientation="Vertical" DockPanel.Dock="Center">

    </StackPanel>
</DockPanel>

Answer: Add this to your dock panel style.
<Trigger Property="DockPanel.IsMouseOver" Value="False">
      <Setter Property="DockPanel.Background" Value="Transparent"/>
</Trigger>


The SE is doing relatively well

Question: I sometimes feel sad at the state of Econ SE, because a lot of the questions we get are homework questions (traffic drops off a cliff when school is out) or vague questions from non-experts. (There are also good questions though, both from experts and non-experts.)
If you would like to feel better by comparison, head on over to Medical Sciences SE, where they have questions like
Are green bones a real thing?
and they also have a question with 17k views and 2 votes.
Seems like small SE's with topics of popular interest have it hard. I wonder if the SE format should be adapted somehow in such cases.
Answer: I don't think we can do much about homework questions, all stacks that deal with difficult science subjects get some of those, there are lot of homework questions on physics.se as well (see how many homework questions they get even during summer). I think outside of outlawing the homework questions there is not much to do about them. Also, personally I do not even mind homework questions that much as long as they follow our homework rules. Some people may come to economics.se for help with homework and then later stay and become regular users, and later contribute after their studies. Maybe we could make the homework standard stricter, although I guess they are already reasonable.
Regarding the vague questions from lay public, I think that is a bigger problem. I think that could be at least partially solved if we would change our rules to require question be based on some references and prior research (at least to news) instead of just encouraging it. That would get rid of all the 'shower/toilet questions' (e.g. I think the worst questions are those when someone gets an idea for some new exotic economic policy/system, likely while having late-night shower or sitting on the toilet) that are just posted here without any effort whatsoever.

The SE is doing relatively well


Probability of Drawing Enough Numbers (Combinatorics)

Question: Maybe you could help me with the following problem.
Given a series of incremental numbers that is split in two, so $s = 1, 2, 3, ..., n_1$, $n_1 + 1, n_1 +2 ,..., n_2$. Also given a integer number $0 < x < n_2$.
Now take a random combination of $x$ numbers out of $s$ (so without replacement and order does not matter).
Two questions:

What is the probability that the random combination contains all numbers between and including $1$ and $n_1$? The combination might include numbers larger than $n_1$.
What is the probability that the random combination contains all numbers between and including $n_1 + 1$ and $n_2$? The combination might include numbers smaller than or equal to $n_1$.

Both probabilities would be ideally expressed in terms of $n_1, n_2$ and $x$.
I hope I expressed the problem clearly, otherwise I can add more information.
Comment: Welcome to math.SE! Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to typeset your math, rather than using backticks.
Comment: Ah, I see you did. :)
Answer: Hints:

How many ways of choosing $x$ numbers without replacement from $n_2$ numbers
How many ways of choosing $n_1$ numbers without replacement from $n_1$ numbers and $x-n_1$ numbers without replacement from $n_2-n_1$ other numbers
The answer to your second question is the same as the answer to your first but replacing $n_1$ by $n_2-n_1$


Drupal Commerce Change Order Weight at Checkout

Question: I am using Commerce FedEx to retrieve quotes at checkout and using a SmartPost setting that requires packages to be over 1lb. to return a quote from FedEx. I need to have the order shipping weight from Commerce Physical Products default to 1lb. for the entire order weight if the order weight is under 1lb. at the time of checkout. I do not want to make all of the products a minimum of 1lb. due to inaccurate quotes if multiple items are ordered so I am looking into a solution with Rules, but cannot seem to get an Action that will allow me to do this.
Example: One product is 0.25lbs. When two are ordered, the shipping weight should be 1lb. at checkout to receive a quote. When six are ordered, the shipping weight should be 1.5lbs.
Answer: You can use HOOK_commerce_fedex_rate_request_alter(&$request, $order) to alter the request before it goes out:
function MYMODULE_commerce_fedex_rate_request_alter(&$request, $order) {
    // Test this value and set it to whatever you'd like.
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Value'] = 1;
    $request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Units'] = 'LBS';
}

Just test the value and update it if you want.
Comment: Thanks for the answer, I was able to write an if statement to get items under 1lb to have the actual amounts. This above will make everything 1lb even if over. There was one adjustment that needed made below, if you update your answer I will accept it.

        `$request['RequestedShipment']['RequestedPackageLineItems'][0]['Weight']['Units'] = 'LB';`


Are there any other tempo descriptors that imply melancholy?

Question: So I got this inspirational idea for composing a piece from a fellow composer:

His life was good, a girlfriend, friends and a nice family; then out of nowhere, he loses the love of his life for another person. Then he prefers to be alone most of the time, losing his good  life (friends and family) gradually. When he remembers, he sometimes lives in a fake happiness, and sometimes he realises the bitter reality.

I decided to have emotional contrast determine the sections of this piece more than modulations. I see 2 vastly different emotions being expressed in this paragraph, those being:

Heartbreak and Melancholy
Happiness

I decided to use minor to represent the heartbreak and melancholy and major to represent the happiness. And, this may be a bit of Chopin influence here, but the heartbreak itself I'm representing with the tension between scale degrees 6 and 5. Scale degree 6 also happens to be the seventh of vii°7 so why not use vii°7 to add more tension than scale degree 6 alone and then resolve it to the tonic minor? And to add even more tension and heartbreak, why not add dynamic changes between forte and piano? So this is basically what the heartbreak moments in my piece look like:
<code>Right Hand: Bb    | A    | Bb    | A    |
Left Hand:  C#°7  | Dm   | C#°7  | Dm   |
Dynamics:   f     | p    | f     | p    |
</code>
At least one of these things holds true in every heartbreak moment in my piece. The heartbreak and melancholy also has a pedaled arpeggio bass. It is currently being written in 4/4, though I'm wondering if I should write it in 12/8. Wait, what would a double dotted half note in 4/4 be in 12/8 assuming that it is still 3.5 beats? Some kind of triplet or what? Oh well, that's a topic for a different question.
As for the happiness, I thought of representing it with not only a move to a major key after wallowing in the minor, but also moving from 4 beats to 3 beats and changing to a faster tempo in a waltz rhythm. So like an Andante to Allegro change.
I know how to get across that the Allegro is to be joyful via marking the tempo. Allegro giocosso is what I would use for that since giocosso literally means joyfully. However, I don't know how I should get across that the Andante is to be melancholic and heartbreaking via tempo. The only tempo descriptor that I know means that the piece is to be melancholic is lamentoso, literally meaning lamenting.
I'm not sure that lamenting is the proper term here though to describe the melancholic Andante. Isn't lamenting like extreme melancholy, like the melancholy a person experiences after the death of someone? In the inspirational idea, it's more like depression than grieving, the melancholy is. I know I could just write Andante and then Molto expressivo, but what if that gets across the wrong emotion? I could see that easily being misinterpreted as peaceful and not melancholic if I just use Molto expressivo for the emotion. So I'm wanting to represent it in the tempo to make sure it doesn't get emotionally misinterpreted.
Is there a different tempo descriptor for melancholy that fits this piece better than lamentoso? Or is Andante lamentoso the best I can do to get across that the Andante is supposed to be melancholic and heartbreaking?
Comment: Lamentoso is Lamenting as you said. Try con dolore. Maybe this is not as strong as u'd want you Tempo Marking. But I think this will do. Maybe It's strong enough, Actually depends on what your Music is Telling.
Comment: Thanks. I didn't know if there was another tempo marking that implies melancholy or not. Con dolore means "in pain" in Italian I think. And melancholy, especially that of losing someone is painful, sometimes even physically. So Andante con dolore for the melancholic minor key sections and Allegro giocoso for the happy major key sections. Yeah, I think that will work.
Comment: Dolore is Sadness in italian, Dolour is sadness in English too.
Comment: I've seen "mesto" in tempo indications before...but it means "sad", not necessarily melancholy. The strict translation would be "malinconico".
Answer: Here are some options. The definitions of these terms seem to overlap a lot. I don't know the nuances:
con dolore: with sorrow.
dolente: doleful, sorrowful.
dolore: grief.
doloroso: sorrowful.
lacrimoso or lagrimoso: tearfully, sadly.
lamentando or lamentoso: lamenting, mournfully.
lugubre: lugubrious, mournful.
malinconico: melancholic
mesto: mournful, sad.
triste: sad; sorrowful.
tristement: sadly.
These terms can be combined with different tempo indications but since this topic is about an Andante indication I have found some interesting YouTube videos with pieces of music where some of these terms are combined with the word Andante:

Edvard Grieg - Peer Gynt Suite No. 1, Op. 46
The Death of Åse (Åses død) - Andante doloroso:

Tedesco Quintette: 2 Andante Mesto:

Dieter Acker (1940-2006) - "Zwischen Tag und Traum" (1988) / II - Misterioso, Andante dolente:

Sconforto: Andante triste (Romanza):

Sonata Nr. 4 in A Minor: 3. Andante lugubre · Paul Lang:

Franz Liszt: Andante lagrimoso - "Harmonies poétiques et religieuses" (audio + sheet music) [Thurzó]:

Saint-Saëns, Introduction et Rondo Capriccioso, op.28
(Andante malinconico; Allegro ma non troppo)


open a lightbox2 containing a flowplayer video from a menu link

Question: Is it possible to make a link from a main menu to open a lightbox2 that will contain a flv video?
I have flowplayer installed but not swf tools
I thought of doing it with javascript but I'm sure there is another way
Answer: Add rel="lightvideo" tag, it will popup the video, It also have the option to set the size of the modal window, for more information see the readme.txt
Google video example

Answer: I think if you just add rel="lightbox" to the link that should do it?
Answer: As was said before add the lightvideo tag to any link with the rel attribute, you can add the size like this.
    rel="lightvideo[width:600px; height:500px;]"
Adding it to a standard drupal menu item is a bit more difficult as you need to narrow down which menu item you want to apply it to.
You could add it to the menu item with jQuery though, something like this:
$('.menu li a').attr('rel', 'lightvideo[width:600px; height:500px;]');

You'll need to narrow it down to the exact menu item you want, that will apply it to all of them.


Exponential decay

Question: I have a new product that was launched and I see a bug spike in enrollments during the initial stages post which it's been declining and now it holding steady. Curve looks like an exponential distribution. Based on this data, I am trying to forecast enrollments for upcoming periods. My data is at a day level.
Can somebody please help with the approach I would need to take?
Answer: If you're ok with your assumption of exponential distribution, your best predictor of enrollment rate is $\hat{\lambda} = n/t$ where $\hat{\lambda}$ is the predictor of enrollment rate, $n$ is the quantity of enrollments for a time period,  $t$ is the related time period (# of days for your case).
With the $\hat{\lambda}$ (such as $42\,/day$) you can forecast whatever you wish such as # of enrollments between day X & Y etc.
You may need to read about probability density, cumulative density functions for the exponential distribution if you're not familiar with them.

Exponential decay


How can I get rid of an abandoned mutex?

Question: Summary:

Is there a way to clear out a mutex if the process that created it is dead and gone?

Details:
I use a mutex to make sure that only one instance of my app runs.
While testing out some new code (to do auto updating) I ran Environment.Exit(0).  While running in debug mode, my mutex was cleaned up fine.
But when I changed the build to be 'Release' then the mutex stays around after the exit call and is marked as abandoned:

I have double checked to make sure that there is not a process still running that this mutex is attached to.
Now every time I run my app, it thinks the mutex is still there and will not launch my app.  (It also crashes because it tries to send a message to the "currently running" instance of the app to show itself.)
I tried to free the mutex like this:
<code>bool createdNew;
string applicationId = "18773:TestStudio";
var singleInstanceMutex = new Mutex(true, applicationId, out createdNew);

singleInstanceMutex.Close();  // Tried ReleaseMutex() too
</code>
but of course that just gets it andthen frees it.
I know I could just reboot, but I am hopping for a better fix in case this ever happens in production.
Is there a way to clear out a mutex if the process that created it is dead and gone?
Comment: According to your screenshot 3 things are still referencing it. Close whatever 3 things still have the handle.
Comment: @Scott Chamberlain - The reference remains, but the process is long gone.  It died in a way that did not free the reference.  Hence my question on how to free up the mutex.
Comment: @Vccano then you have one of two situations. A corrupt OS install, or something has a reference that you don't realize is taking the reference. If it really was gone then the count would be 0, cleanup of handles from failed processes was fixed back in Windows 95 (or 98, I can't remember which). The likely situation is either the program is not really dead yet and something is still keeping it alive when you think it is dead or some other program (IIS, an antivirus, who knows) is picking up the handle and not letting it go.
Comment: Have you tried changing your program to do things the way my code does it, to see if that avoids the problem from occurring?
Answer: Don't know if this actually answers your question, but here's the code I use for this purpose:
<code>  // Mutex object used to determine if there are multiple instances of this program running.
  //  Note that this is a reference to a .Net Mutex object, not the Windows mutex itself.
  private static Mutex _onlyOneInstanceMutex;

  /// <summary>
  /// Method to test that there is not another instance of the program already running on this
  /// machine, or at least in this Terminal Services session or Windows Vista / Windows 7
  /// concurrent sessions session. If there is, a message box-style localized error message is
  /// displayed and the value false is returned. This implies that this method should not be
  /// used in programs that are run as a Windows service.
  ///
  /// This implementation uses a .Net Mutex object in public storage to prevent it from being
  /// garbage-collected. The name of the associated Windows mutex is simply the program name as
  /// provided by the caller. Neither the .Net Mutex object nor the Windows mutex are ever
  /// explicitly released; they remain in existence, perhaps in an "abandoned" state, until the
  /// process that created them terminates.
  /// </summary>
  /// <returns>false if another instance running, otherwise true</returns>
  [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive",
                   Justification = "Not sure if this is correct or not.")]
  public static bool TestOnlyOneInstance(string programName)
  {
     // Funny construct to prevent the Mutex from being garbage collected
     GC.KeepAlive(_onlyOneInstanceMutex);

     // Test if we are the first instance, and if so create the Windows mutex, making it
     //  impossible for subsequent instances to successfully create their mutex
     bool firstInstance;
     _onlyOneInstanceMutex = new Mutex(false, programName, out firstInstance);
     if (firstInstance)
        return true;

     // Display a (possibly localized) error message, then return
     string errorMessage = MLocalizer.GetString("Error1",
           "Another instance of this program is already running on this machine.") +
         "\n" + MLocalizer.GetString("Error2",
                                     "You cannot run two instances at the same time.") +
         "\n" + MLocalizer.GetString("Error3", "Please use the other instance.");
     MessageBox.Show(errorMessage, programName, MessageBoxButtons.OK, MessageBoxIcon.Error);
     return false;
  }
</code>
EDIT:
Only differences I can see in my code and yours is that I specify "initially owned" as false, and I have the funny thing about the garbage collection.
Oh, and I declare the Mutex static.


Cannot carry out aggregate query in play slick

Question: I am trying to write a query that can find that max of rows using the the aggregate function. However I get errors when I try to run the code
Here is my sample code below
def aggregate (): Future[[Person]]  = db.run {

    people.map(_.age).max.result

  }

I am getting this error when i run the code
type mismatch;
 found   : PersonRepository.this.dbConfig.profile.ProfileAction[Option[Int],PersonRepository.this.dbConfig.profile.api.NoStream,slick.dbio.Effect.Read]
    (which expands to)  slick.sql.FixedSqlAction[Option[Int],slick.dbio.NoStream,slick.dbio.Effect.Read]
 required: slick.dbio.DBIOAction[models.Person,slick.dbio.NoStream,Nothing]

Please help take a look and see what's wrong, Thanks
Comment: What error are you getting?
Comment: This is the error am getting    ```type mismatch;
 found   : PersonRepository.this.dbConfig.profile.ProfileAction[Option[Int],PersonRepository.this.dbConfig.profile.api.NoStream,slick.dbio.Effect.Read]
    (which expands to)  slick.sql.FixedSqlAction[Option[Int],slick.dbio.NoStream,slick.dbio.Effect.Read]
 required: slick.dbio.DBIOAction[models.Person,slick.dbio.NoStream,Nothing]```
Answer: Future[[Person]] - i guess this should be Future[Person].
Answer: I later tried this and it worked
def agg (): Future[Option[Int]]  = db.run {
    people.map(_.age).max.result
  }


A geometry test question with an isoceles triangle in it

Question:
$\triangle ABC$ is a triangle.
$$|AE|=|AC|$$
$$AE\perp ED, EH\perp AC$$
$$|EC|=4|EB|$$
$$3|CH|=2|AH|$$
$$|EH|=22\;cm$$
$$|DE|=x\;cm$$
Find $x$.
My solution:
Let $|CH|=2k$. Then $|AH|=3k$, $|AE|=5k$.
By Pythagorean theorem on $\triangle AEH$, $|AE|=\frac{55}2$, $AH=\frac{33}{2}$ and hence $\cos\angle A=\frac 35$.
By law of cosines on $\triangle AEC$, $|EC|=\frac{55}{\sqrt5}$ and hence $|BE|=\frac{55}{4\sqrt5}$.
By half -angle formula $\cos\angle BED=\sin\angle AEC=\cos\frac{\angle A}2=\sqrt{\frac{\cos\angle A +1}{2}}=\frac2{\sqrt 5}.$
Edit: Here I made a mistake. I couldn't solve the question in time.:(
This is a test question sent to me from a student and time allocated for it is 90 seconds. I found my solution too slow. I wonder if somebody can find a faster way.
Thanks in advance.
Comment: It seems that your solution assumes that $\angle BDE$ is a right angle which is not the case, I think.
Comment: @Vasili Ahhh... Thank you.
Answer: Draw $CK\perp AE$
Since $\triangle ABC$ is isosceles $CK=EH=22$
Let $CK$ intersect $AB$ at $L$
then $DE\parallel CL$ ($\perp$ same line)
$\triangle ALK \sim \triangle ADE$ (AAA similarity)
$\frac{LK}{DE}=\frac{AK}{AE}= \frac {3}{5}=\frac{LK}{x}$ and $LK=\frac{3x}{5}$
$\triangle BDE \sim \triangle BLC$ (AAA similarity)
$\frac{BE}{BC}=\frac{DE}{LC}=\frac{1}{5}=\frac {x}{\frac{3x}{5}+22}$
$x=5$


HTML E CSS - Porque As Imagens Não Estão Aparecendo

Question: Boa Noite galera tudo bem? podem me ajudar? a entender porque as fotos não estão aparecendo no site?
 aqui segue css delas.
aqui segue a foto do html com as divs

e aqui segue foto do modelo do site de facul que estou criando para treino. a ideia é por as fotos no mesmo formato da biomedicina rente ao nome do curso colado na borda preta.
o site não envia passa de 2mbs. mesmo assim se puderem me ajudar comecei a mexer faz 14 dias e estou gostando muito e aprendendo todo dia.
Comment: abre a ferramenta de desenvolvedor do navegador e olha se não tem erros
Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena entender [O que é o Stack Overflow](https://pt.meta.stackoverflow.com/q/7256/70) e ler o [Guia de sobrevivência (resumido) do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8089/70).
Answer: Você deixou height:25%; se mudar para px em ou rem vai aparecer. Pode tambem setar um min-height:
   #bio{
    background-image: url("https://vaidebolsa.com.br/wp-content/uploads/2019/12/biomedicina.jpg.webp");
    width:238px;
    background-size:cover;
    background-repeat:no-repeat;
    height:25rem;
   }

Tente utilizar desse jeito que vai aparecer.
Answer: Tenta baixar as imagens e usá-las localmente dentro do projeto ou... na div que está envolvendo essas divs de disciplinas coloca um: style="display: flex; flex-direction: column; align-items: center; justify-content: center;"


Does ukulele chord often use inversions instead?

Question: As a long time guitar player, I'm a bit confused, it seems on ukulele, it's quite common to use inverted chords (i.e. the root note is not necessarily the lowest note, in term of pitch) in substitute of those in root position (in order to simplify fretting I think). Is it true and widely acceptable?
Comment: From the answers:

1) With only 4 strings, ukulele is very limited in fretting patterns, so it's a common practise to use chord inversions to simplify fretting or make certain chords (e.g. extended chords) possible to play;

2) Ukulele has a relatively high pitch range, so the bass note is not as significant as a lower pitch-ranged instrument (e.g. a guitar);

3) Ukulele is rarely used as a solo instrument, it's mostly used in companion with vocal or other instruments, which are typically lower in pitch and defines the bass line, so using inversion doesn't really matter
Answer: Simply put, it has to do with how ukulele is played in common practice. It's similar to guitar in that you strum chords both up and down in rapid succession, the difference being someone had the bright idea to put a higher string as the 4th string, making it sound as if all the chords were up strums. This hides which strums are up and down and overall gives a brighter and more regular sound to it. Since chords aren't always constructed with the root on the top as well as the bottom of the chord, and a ukuleles small range and less strings, inversions start to sound very similar to root position chords. This is also helped by the fact that the ukulele is not often played as a solo instrument compared to being an accompaniment for singing or another ukulele. If you add a bass instrument the inversions don't really matter anymore.
Comment: Thanks Tama. I'm marking this one as the accepted answer because it's most relevant to my question. I'd like to thank other folks for your great answers.
Answer: From personal experience: it's very common on guitar as well, and ukulele is a more limited instrument, no reason to have to use all root position chords.
Reasons:

Voice leading. Inversions can, in essence, allow playing two notes from two chords with a unison or semitone interval between them on the same string. Wow that was a bad explanation. Here you go.
Extended chords. No, this doesn't apply that much to ukulele. But 7/9/11/13 chords are often hard to play on guitar, unless you allow for inversions, which make some of them trivial. In fact, in the larger extended chords, it is common to omit the fifth, and if necessary, omit the root (with the assumption another instrument will be playing it). And on (a 4-string) ukulele, it is impossible to play a complete 5+ tone chord.
Inversions can help you move your hand less. If you are limiting yourself to root inversion only, you will find yourself going all up and down the neck.
Comment: @hillin: When strumming an Am chord on ukulele, the first note played will be an A.  Having the root note of a chord played *first* helps give it some aural dominance even if it's not the *lowest* note in the chord.  My own preferred guitar tuning likewise would play a strummed Am chord as A-E-e-a-c'-e', but the low E is less noticeable than on a standard-tuned guitar playing E-A-e-a-c'-e'.
Comment: Thanks Dawg. I agree that chord inversion is common and useful, and sometimes a must on guitar. But my point here is, for example, if a song uses a chord `Am`, we will most likely to avoid the low E string if we play it in an open position, so it won't become an `Am/E`. However it seems almost all ukulele chord books suggest a 2-0-0-0 fretting for `Am`, which is actually an `Am/C`. It gives me an impression that root-position chords are more respected on guitar than on ukulele.
Comment: @supercat How do you strum so that the first note you hit is not the lowest? (besides upstrokes) Just curious, I'm not a ukulele player.
Comment: @YeDawg: On both a ukulele and my preferred tuning, the lowest-pitch string is second from the edge.  For a uke, the normal tuning is g-c-e-a, while for my preferred tuning it's G-D-d-f-g#-b.  Fingering 2-0-0-0 on a uke thus gives a-c-e-a, and on my "flat finger" tuning, fingering 2-2-2-4-4-5 yields A-E-e-a-c'-e'.
Comment: @supercat: May I ask why do you use such a tuning? From my classical guitarist's point of view it looks pretty convoluted :—). (I do re-tune my guitar in various ways but mostly the bass strings only. And they remain always in order.)
Comment: @supercat that's a peculiar tuning. Do you use it on a typical guitar (i.e. not baritone)? What gauge of strings do you use? And I'm as curious as Ramillies, why do you use such a tuning, besides the brilliant idea to put a higher pitch string on the edge?
Comment: @hillin: I use it with standard-gauge guitars.  My preferred instrument is an Ovation acoustic electric with nylon strings; the fourth string is an extra-heavy third string, and the fifth and sixth strings are swapped.  I mostly play a bass note on one of the bottom two strings plus the top four in either an arpeggio or bass+strum pattern, but chords that use the sixth string will work adequately strumming all six.
Comment: @Ramillies: A movable G chord is x-5-5-6-6-8, movable C is 5-5-5-7-8-8, and open D is x-0-4-4-6-7.  Movable minor, seventh, m7, M7, and Mm7 chords can also all be played without having to reach a finger over the active portion of another string, and without having to reach any finger other than the index finger past the third string.  The keys of G major and B minor both sound great because the D chord spans 2.25 octaves, but no keys are particularly problematic.
Comment: @hillin: On standard tuning, the fourth string has to be wound because it's the root of a D chord.  On my tuning, every chord can be rooted on the fifth or sixth string, so I like having the instrument split as two deep-sounding strings and four harp-like strings.
Comment: @supercat interesting, thanks for the explanation. Still need sometime to understand tho ;)
Answer: Just a little addition to Ye Dawg's answer: I think that the obvious reason is that guitar has 2 strings more. (Note: I'm a classical guitarist, but I've never played ukulele, so take it with a grain of salt.)
Let's have a look at triads (minor/major chords (mostly)). If you play them on the guitar, you will find that you play all three tones on the higher strings in any inversion. But, fingering these three strings, you still have three strings left. That gives you a possibility to add any root whatsoever (try playing a chromatic scale from the lowest E to the next higher E — the farthest you need to go is the 4th fret) and possibly more.
On the contrary, after fingering these three strings, you have only one string left. So there's not a real choice, most likely there will be only one of the tones of the triad within reach, and so you just finger that one. Moreover, if you strum the guitar, you can choose where to start strumming and not strum some of the lower strings. Since on the ukulele, as far as I know, the lowest string is actually not the 4th, but the 3rd, you have to finger it somehow in order to be able to strum the other three without some weirdnesses like muting the string with your left hand.
And if this applies even to triads, then the more complicated chords, like 7ths, will make even more problems, and it looks like you should rejoice when you manage to finger them at least somehow :—).
Comment: Cello also has only four strings, but when cellists play chords they're almost always in root position.
Comment: @leftaroundabout — I think that you don't account for the need of simple, idiomatic fingerings in the first position, with as many open strings as possible. What the most people do when playing guitar (and probably ukulele as well) is just strumming chords, and the basic chords need to be as simple as possible. (These fingerings often have the advantage of sounding more powerful and resonant too.) I think (!) that chords are a pretty advanced topic on a cello, so whoever is going to play them can bear with some more difficult fingerings or moving between positions.
Comment: I guess it's as others stated in their answers, because cello has a low pitch range, in most time it's a bass definer (if there is no contrabass in companion), so whether use root position or inversion matters a lot.
Answer: True, on guitar, most chords - particularly the basic ones - seem to be shown and taught as root position chords. Often eventually played as all sorts of inversions, but root basically. The reason is that the most common triads can be played in E and A shapes, which often come together in pieces played, and use 6th and 5th strings as the root notes, respectively. That leaves 5 or 4 other strings available for other notes, some of which will be octave copies of those already played.
With 4 instead of 6 the uke is somewhat restricted in that field. Playing a shape which puts root on the bottom string leaves 3 others, pretty good. But playing a different shape around the same fret place will leave only a couple of other strings. Notes missing could be found on the bottom string, which then means an inversion is being played. So, it's more convenient for the player to stay around the same few frets and use inversions than to chase up and down the neck - which doesn't sound as good anyway.
Answer: I think the dominant reason is simply that ukulele is higher-pitched. In its register, you scarcely perceive any note as a "bass note", hence there's also not really a strong effect of "inversion".
Indeed, when you're playing with a guitarist or even bassist, what the uke does is completely irrelevant for the question of inversion, because it's always the bass instrument that defines this. Even when no bass notes are actually played, listeners may "mentally add" them.
All of this also holds true for other high-pitched plucked string instruments, like mandolin and balalaika.
Answer: The strings of a ukulele are tuned like the top four strings of a guitar with a capo on the eighth fret, and with the fourth string tuned up an octave.  Most guitar chords are formed by producing either a rooted or inverted form of the chord on the top four strings, as convenient, and if the chord isn't rooted adding a root on either the fifth or sixth string.  Ukulele chords are similar except that if the fifth or sixth string would be needed to play the root, it's omitted instead.
If one had a guitar but couldn't play anything on the bottom two strings, one could use a couple of movable chord shapes to play everything in rooted position, but having all notes of the chord move up and down parallel to the root would generally not sound very good.  If one plays chords in the sequence C-G-D on the top four strings of a guitar, the C would be voiced c'-E'-G'-c'', and the D chord as d-a-d'-f#'; the G chord could be played as g-b-d'-g' or as g-d'-g'-b', but one of those would have to be a transposition of the preceding or following chord.
Further, while guitars may sound fine when played on the tenth or eleventh fret, the smaller size of a soprano ukulele would cause it not to sound good when played in such fashion.  If one needed to play a rooted B chord on a ukukele, the "root" would be pitched higher than almost any melody performed by a non-amplified male vocalist, and many melodies sung by female vocalists, making it unlikely to function as a root.


Erro ao utilizar bibliotecas no PHP

Question: Estou tentando adicionar o seguinte:
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/settings.php';
require_once __DIR__.'/resources.php';
require_once __DIR__.'/utils.php';

use Spire\Settings;
use Spire\Resources;
use Spire\Utils;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Silex\Application;

Porém o servidor me retorna erro onde há o uso da barra invertida ("\"). Qual a configuração necessária para que o servidor reconheça da forma correta?
Comment: Configuração necessária: **(PHP 5 >= 5.3.0)**
Comment: realmente, a versão do php no servidor é a 5.2.17. Não teria como funcionar. Obrigado
Comment: Vou verificar agora a versão do PHP
Answer: O erro se dá devido ao uso de Namespaces no seu código.
Repare no uso da palavra use em seu código. Nessa parte da sua aplicação ela é utilizada para importar o Namespace específico que será utilizado em seu código.
Conforme mencionado pelo Papa Charlie em comentários, o PHP suporta Namespaces a partir da versão 5.3 somente.
Mais informações sobre Namespace:
http://php.net/manual/pt_BR/language.namespaces.php
Answer: Namespaces são suportados a partir da versão 5.3 do php, provavelmente você está utilizando uma versão anterior.

Erro ao utilizar bibliotecas no PHP


Apply CSS Alpha overlay on image

Question: I'm trying to apply an alpha overlay on my image. Right now, it's applying across the whole body of the page, rather than just the image. Help?
http://jsfiddle.net/21ku3o7f/

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.3);
}

Answer: Apply css code

.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.3);
}
.dimmed{
    position: relative;
    display: inline-block;
}
.dimmed img{vertical-align: top;

Answer: This should do the trick: http://jsfiddle.net/21ku3o7f/1/

.dimmed {
  display: inline-block;
  position: relative;
}
.dimmed:after {
  content: " ";
  z-index: 10;
  display: block;
  position: absolute;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.3);
}
.dimmed img {
  display: block;
}

Answer: Try like this: Demo
CSS:
.dimmed:after {
    content:" ";
    z-index: 10;
    display: block;
    position: absolute;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    background: rgba(0, 255, 255, 0.3);
}

/* newly added code */

.dimmed {
    position: relative;
    display:inline-block;
}

Apply CSS Alpha overlay on image


rails google pagespeed optimization issue

Question: I'm running the google pagespeed test on my (test) web made with rails and deployed on heroku.
It shows me a warning about the javascript and css files that are blocking the half top content of the page.
So the main suggestion is to made the javascript files load async, and to put the css files after the  tag. I did it and now the files I changed to async and moved to the end are not shown in the warning, but I still see two files that I don't know how to change:
https://foo.herokuapp.com/assets/application-08af52LotOfnumbersAndLetters.js
https://foo.herokuapp.com/assets/application-08af52LotOfnumbersAndLetters.css

This are the files generated by rails from my assets, they are not loaded by a script or style tag, so as far as I know, I can't move the css or made the js async.
Is there a way to pass the speed test with this files?
Im using rails 184.108.40.206
Edit:
I don't find neither how to set the browser cache with the 'expire' in rails. And that's another warning I see.
Edit 2:
Now I see in console that the rails javascript asset that I don't know to change to async is loading before the materialize.js that I changed to async, so the functions of materialize are not declared when the rails javascript asset loads and calls them, and there is an error.
Edit 3:
It seems that adding a line to the config/initializers/rails_admin.rb it works. If somebody finds the same problem, you only have to add:
config.parent_controller = 'ApplicationController'
I think it is due to: rails_admin do not use application_controller if you do not tell him to do it, so application_controller does not catch the exception of rails_admin.
Answer: It seems that adding a line to the config/initializers/rails_admin.rb it works. If somebody finds the same problem, you only have to add:
config.parent_controller = 'ApplicationController'

I think it is due to:
rails_admin do not use application_controller if you do not tell him to do it, so application_controller does not catch the exception of rails_admin.


Atualizar objeto json em uma coluna varchar

Question: Pessoal estou com um problema no Postgres, eu tenho uma coluna que é no formato varchar mas conforme uma necessidade tenho que colocar um objeto JSON salvo nele
{"value": "value", "value2": "value2"}

É possível atualizar apenas o value2 por exemplo?
Comment: Sua pergunta parece ter alguns problemas e sua experiência aqui no Stack Overflow em Português poderá não ser a que melhor por causa disto. Queremos que você se dê bem aqui e consiga o que quer, mas para isso precisamos que você faça sua parte. Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/101).
Answer: Nas versões mais recentes do Postgres, existem, diversas funções para manipulação de JSON.
Mas considerando que você precisa usar o tipo VARCHAR e atualizar apenas uma parte do JSON na coluna, sugiro a utilização de Expressão Regular.
Veja um exemplo abaixo:
SELECT REGEXP_REPLACE(
   '{"value": "value", "value2": "value2", "value3": "value3"}',
   '(?<="value2": )(null|\d+(\.\d+)?|"([^"]*(\\")?)*")',
   quote_ident('New Value'),
   'g')

No caso do UPDATE, ficaria assim:
UPDATE tabela
SET coluna =
   REGEXP_REPLACE(coluna,
      '(?<="value2": )(null|\d+(\.\d+)?|"([^"]*(\\")?)*")',
      quote_ident('New Value'),
      'g')
WHERE id = 123456

O uso da função quote_identserve apenas para adicionar as aspas. Se for adicionar um valor numérico é só passar o literal direto.
Comment: deu certo daniel! valeu


Let $A$ be an $n \times n$ nonsingular matrix having distinct eigenvalues and $ B$ is a matrix satisfying $AB = BA^{-1}$

Question: Let $A$ be an $n \times  n$ non singular matrix having distinct eigenvalues. If $ B$ is a matrix satisfying $AB = BA^{-1}$ , show that $B^{2}$ is diagonalizable.
I need to show that $B^{2}$ is diagonalizable.
If I prove that $AB^{2} = B^{2}A$ then, it implies that $B^{2}$ is diagonalizable, since it commutes with a diagonal matrix.
But I don't how to prove that $B^{2}$ commute with $A$.
Any hint would be helpful.
Answer: Note that\begin{align}AB^2&=(AB)\left(BA^{-1}\right)A\\&=\left(BA^{-1}\right)(AB)A\\&=B\operatorname{Id}BA\\&=B^2A.\end{align}


Need help understanding Fibonacci Fast Doubling Proof

Question: From this website, http://www.nayuki.io/page/fast-fibonacci-algorithms (fast doubling proof close to the bottom of the page).
I have understood the proof for the most part but I am struggling to see how this part of the proof works especially when the the F(n) function is squared.
\begin{align}
   F(2n+1) &= F(n+1)^2 + F(n)^2. \\
   F(2n) &= F(n) \left[ F(n+1) + F(n-1) \right] \\
   &= F(n) \left[ F(n+1) + (F(n+1) - F(n)) \right] \\
   &= F(n) \left[ 2F(n+1) - F(n) \right]. \\
   F(2n-1) &= F(n)^2 + F(n-1)^2.
  \end{align}
Answer: Start with:
$$F(n+1) = F(n) + F(n-1)$$
Rewrite as:
$$\begin{align} F(n + 1) &= F(n) + F(n-1) \\
                F(n) &= F(n) \end{align}$$
which is:
$$\begin{align}
\begin{bmatrix} F(n+1) \\ F(n)\end{bmatrix}
&=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}
\begin{bmatrix} F(n) \\ F(n-1)\end{bmatrix} \\ &=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^2
\begin{bmatrix} F(n-1) \\ F(n-2)\end{bmatrix} \\ &=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^3
\begin{bmatrix} F(n-1) \\ F(n-3)\end{bmatrix} \\ & \dots \\ &=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n
\begin{bmatrix} F(1) \\ F(0)\end{bmatrix}
\end{align}$$
Taking $F(0) = 0$ and $F(1) = 1$, you get:
$$\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n = \begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}$$
So to use "doubling", we just plug $2n$ into the formula:
$$\begin{align}
\begin{bmatrix} F(2n+1) \\ F(2n)\end{bmatrix}
&=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{2n}
\begin{bmatrix} F(1) \\ F(0)\end{bmatrix}  \\ \\ &=
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{n}
\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{n}
\begin{bmatrix} F(1) \\ F(0)\end{bmatrix}  \\ \\ &=
\begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}
\begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}
\begin{bmatrix} 1 \\ 0 \end{bmatrix}  \\ \\ &=
\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ F(n)F(n+1) + F(n-1)F(n) \end{bmatrix} \\
\\ ~
\\ & \text{And if you want...}
\\ ~
\\ &=
\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ F(n)F(n+1)+ \bigg(F(n+1) - F(n)\bigg)F(n) \end{bmatrix}\\ \\&=
\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ 2F(n+1)F(n) - F(n)^2 \end{bmatrix}
\end{align}$$
Which isn't actually better than matrix exponentiation asymptotically.  And regardless, since the Fibonacci sequence grows exponentially, it will always require exponential time to compute just due to the size of the output.  The matrix or "doubling" approach takes you from $O({\rm exp}~x^2)$ to $O({\rm exp}~x)$ asymptotic calculation time, which isn't nothing, but it still isn't exactly tractable either.
Comment: I think you mean $[a \ c] = M \ [b \ d]$, but I understood your point. Thanks.
Comment: Your answer is largely excellent. I have a problem with the last paragraph - "exponential time to compute due to the size of the output". This is not true, because the bit length of the output is linearly proportional to the value of the input. In other words, $\log_2 F(n) \in O(n)$.
Comment: Thank you, but I can't agree.  Runtime is usually (admittedly loosely) defined in terms the radix-B encoding length of the data structure.  It is that way for trees, graphs, lists, whatever.  For natural numbers, that would be $F(\sum_{k=0}^n c_kB^k) \in O(\exp n)$.  Do you know a reason to make an exception for numbers?
Comment: I see where you're coming from. There are some algorithms whose runtime is described in terms of the value instead of the bit length. For example: [Ford-Fulkerson](https://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm#Complexity), [subset sum (dynamic programming solution)](https://en.wikipedia.org/wiki/Subset_sum_problem#Pseudo-polynomial_time_dynamic_programming_solution). But which convention to use is a matter of opinion and style, as long as the assumptions are stated clearly
Comment: @DanielV Can you please explain how did you get the expression immediately following the sentence: `Taking F(0)=0 and F(1)=1, you get:`?
Comment: @ParagS.Chandakkar Using the same approach above the sentence, you can derive $$\begin{bmatrix} f(n) \\ f(n - 1) \end{bmatrix} = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n \begin{bmatrix} f(0) \\ f(-1) \end{bmatrix}$$  The initial conditions tell you $f(-1) = 1$.  Then just use the property of matrices $$a = M~b \text{ and } c = M~d \text{ iff } \begin{bmatrix}a & c\end{bmatrix} = M \begin{bmatrix} c & d \end{bmatrix}$$
Answer: This follows immediately by looking at the preceding lines. Since the two square matrices are equal, each corresponding entry must be equal. By looking at the $(1,1)$-entry we get $F(2n+1)=F(n+1)^2+F(n)^2$; by looking at either the $(1,2)$- or $(2,1)$-entry we get $F(2n)=F(n)F(n+1)+F(n)F(n-1)$, from which the other lines are just basic manipulations.
Comment: I understand how the final matrix was computed but I do not understand for instance how F(n+1)^2 +F(n)^2 is computed to be F(2n+1). Sorry I am a novice in this area.
Answer: While playing around with the Fibonacci series. I found a way to compute nth Fibonacci number in Log(N) complexity without using matrices.
My method is simpler and intuitive and could be used for self derivation.
I wrote a medium blog regarding this. Thought it would be helpful.
https://medium.com/@ani1998ket/deriving-the-fast-fibonacci-identities-without-matrices-o-log-n-4cd9ce69d9d4
Comment: The coeff pairs that you found is nothing but the coeff matrix raised to some power. So, in essence, you are using the matrix - may be unknowingly.  Nonetheless, its always amazing feeling to discover something!


Help getting rhythm from head to staff

Question: I've recently been composing more directly with MuseScore as opposed to on my guitar and memory via repetition. This, however, is more tricky rhythm-wise, perhaps since I've never been a score reader or writer. Transcribing an audibly simple rhythm, example of first 2 bars of a composition I wrote (that took just about forever) is hard. When doing something from scratch, it's worse as you could forget the rhythmic phrase you had in mind or not know how or if you should divide it into voices.
What would be a good way to practice notating rhythm? Usually, I don't hear subdivisions and just know what to play for how long, and I don't count. Trying to mouth it to an excessively low bpm sometimes works, but with the example I had to play around with durations until I hit it by chance; could've been 13:7 tuplets for all I knew..
Answer: To be honest, as a professional-level keyboard player, I didn't have the faintest idea what the rhythm notation in your Musescore example was supposed to mean. It's completely unreadable, and therefore unplayable by humans.
(Note, the music is fine - it's only the notation that is horrible!)
But from the computer playback in Musescore, it's actually a straightforward "swing" rhythm when you put the beats in the right place:

Unfortunately, I don't have any good advice on how to learn this, but "trial and error" with a notation program is NOT going to teach you how to do it correctly.
Try to find a course on the web (since you need audio examples to listen to and write down) and start right from the beginning. A human teacher would be an even better option.
It might help if you record yourself singing the rhythm, and then try to "count it out" while playing back your singing.
Comment: Part of the problem is almost certainly that OP is playing with slightly swung eighths, and the transcriber is choking on that.  If OP is able to replay it with straight eighths, it might have an easier time with that.  (But in my experience, most computer transcribers aren't yet capable of figuring out what's intended without some guidance.)
Answer: Assuming that the smallest rhythmic subdivision you commonly use is the semiquaver (16th note), the following ideas should really help. Learn to recognise the sound of groups of notes: dotted crotchet, quaver; dotted quaver, semiquaver; semiquaver, quaver, semiquaver; quaver triplets; crotchet triplets, and the various combinations of inserting semiquaver rests into a group of four semiquavers. Type them into MusiScore and play them back until you recognise each of them. That's  really not a lot of patterns to learn, and it will help you think in 'words', rather than 'letters'.
Secondly, if you can place crotchets accurately, move on to quavers. If your idea doesn't sit correctly with quavers try semiquavers. You only have to choose between four to decide where your note should sit. The ability to count '1 e an a'
has gotten me out of more musical scrapes than Batman's Utility Belt could ever do.
Next, work on ties. Work from tied crotchets, then quavers, then semiquavers. At this stage I'll stop short of discussing swing. Best to get this stuff sorted first.
Answer: Actually, 'trying to mouth it to an excessively low bpm' is the most surefire way to both get the rhythm you want AND to improve your proficiency. Eventually, the bpm will no longer be 'excessively low' every time.
If these are rhythms you are spontaneously creating, by ear, in a reasonably established style, then you're very unlikely to come up with something that is '13:7 tuplets'. In fact, most beats are subdivided into 2,3,4,6,8, or perhaps 9 or 12 subdivisions. A feel for which of these is most appropriate will come with practice.
If you find that the rhythm is difficult to notate, you might be trying to notate something that has a lot of rubato (push & pull), but notating it VERY literally the way you hear it. Conventionally, such flexible rhythms won't be perfectly reflected in the notated product, and are instead rendered much more 'squarely' in triplets or sixteenth-notes (semiquavers). The composer or arranger relies upon the musician to render the rubato in a way that is appropriate to the style.
I am making a lot of assumptions here about your intentions and influences, but I hope it's a helpful start.

Help getting rhythm from head to staff


Django Rest Framework: Update and delete current user without providing pk

Question: I know a lot of people already asked about handling with current user but I couldn't find solution so I post this.
What I want to do is to get, put and delete current user without providing pk.
I want to set endpoint like users/my_account
My current code is here
class MyAccountDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserSerializer

    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

And now I can get current user's info but when I try to update or delete the current user,

AssertionError: Expected view MyAccountDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

How can I solve this?
Update
urlpatterns = [

    path('users/my_account', views.MyAccountDetail.as_view()),
]

Comment: are you taking `pk` in url? please post url line calling the view
Comment: @YugandharChaudhari No. I mean I set url like `api/v1/users/my_account`
Comment: please post your `urls.py`
Comment: @YugandharChaudhari I updated.
Answer: In this case, you will need to override get_object() method in your MyAccountDetail view. For example:
from rest_framework.permissions import IsAuthenticated

class MyAccountDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = CustomUser.objects.all()
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        return self.request.user

You need to do that, because by default get_object method looks for lookup_url_kwarg or lookup_field in the URL, and from that it will try to fetch the object using pk or whatever you have configured in lookup_field or lookup_url_kwarg.
FYI, I have added a permission class as well, because without it, self.request.user will be an anonymous user, hence will throw error.


SSH - Getting 'Broken pipe' error when trying to configure multi-hop connection

Question: I have two SSH servers: ServerA that supports key-based authentication, and is accessible from my workstation, and ServerB that only supports password-based auth, and can only be accessed from ServerA. My goal is to SSH into ServerB from my workstation, but I'm getting a very useless error. Here's my ~/.ssh/config file:
Host ServerA
    HostName 10.8.0.1
    User ubuntu
    Port 22
    IdentityFile ~\.ssh\id_server_a.pem

Host ServerB
    ServerAliveInterval 120
    HostName 184.108.40.206
    User myuser
    Port 12221
    ProxyCommand ssh -W %h:%p ServerA

This should work, but when I type in the command ssh ServerB, I get the following error:
/bin/sh: No such file or directory
banner exchange: Connection to UNKNOWN port 65535: Broken pipe

I have tested both SSH connections, as in I'm able to explicitly connect to ServerA with the key, and from ServerA's shell I'm able to connect to ServerB with the port, username and password.
Where does this error originate from (Workstation, ServerA or ServerB) and is there anything I can do to fix it?
Comment: This is tagged `linux` but what is your Workstation?  Specifically, both OS type and OS version.
Comment: (1) Check that /bin/sh Exists on all 3 machines. (2) Execute `ssh -vvvv ....` to get more Detail on what is going on. (3) Why you are giving %h:%p in ProxyCommand ? (4) Check with `ProxyCommand ssh -vvvv ServerA` to connect to Port 22. (5) Check `ProxyCommand ssh -vvvv email@example.com` , to get Debug Data.
Answer: If the client system is a Mac - a Ventura upgrade is likely the cause.
Based on the timing of the OP's question, that seems quite plausible.
Upgrading my Mac to Ventura (MacOS 13.4) broke ssh for me, giving me a very similar error:
Infinite reexec detected; aborting
banner exchange: Connection to UNKNOWN port 65535: Broken pipe

One significant caveat - I'm using a PIV (smartcard) to authenticate
After troubleshooting with IT support the solution turned out to be:

Remove / comment out the PKCS11Provider line in your ~/.ssh/config
Run the following commands:
ssh-add -e /usr/lib/ssh-keychain.dylib
  #Note - above command may produce the error:
  #   'Could not remove card "/usr/lib/ssh-keychain.dylib": agent refused operation'
  #This can be ignored; the file simply has no items to remove
ssh-add -D
killall -9 ssh-agent
ssh-add -s /usr/lib/ssh-keychain.dylib

You should now be able to ssh

 Note: If ssh still fails - The killall should have cleared all cached ssh process/keys/etc.  A reboot will definitely clear any cached data that may be interfering.
Comment: Does this mean we can't use PKCS11Provider anymore?  I also had this problem on Ventura using ssh keys.
Comment: @Angelo - Not exactly.  I just needed to comment out my `PKCS11Provider /usr/lib/ssh-keychain.dylib` line in the .ssh/config.  But the library `/usr/lib/ssh-keychain.dylib` is still being used, just that it's now being loaded via `ssh-add`.  If you had some other lib for the PKCS11Provider, I expect it should still also work using the ssh-add.
Comment: ssh-add means you're adding your PIV to your agent, and not using the PKCS11Provider directive.  I have commented out PKCS11Provider and this does prevent the problem for me, even though I've been using an ssh key.


What are the resources for researching Facebook Connect implementation best practices?

Question: Are there any resources (blog posts, websites, etc) which provide in-depth explanations of functional and technical considerations/requirements when implementing Facebook Connect? I'm looking for documentation other than what Facebook provides.
Answer: facebook latest php sdk tutorial to integrate facebook features in your site
http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
and
http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development/


Softmax overflow

Question: Waiting the next course of Andrew Ng on Coursera, I'm trying to program on Python a classifier with the softmax function on the last layer to have the different probabilities.
However, when I try to use it on the CIFAR-10 dataset (input : (3072, 10000)), I encounter an overflow when it computes the exponentials. Indeed, I have numbers like 5000, 10000 or 25000.
I have already tried two things :

substract a constant to the matrix before compute the exponential but I have big difference between the numbers so, I can't do that.
compute the exponential of the log of the matrix but it still overflowing.

Can somebody help me to avoid this problem ?
Thank you
EDIT : https://github.com/Kentena/softmax/
Comment: Thousands have played aournd the CIFAR10 dataset and NNs. You may have messed up in your code. Can you show it?
Comment: Yes I have updated my post and posted a github repository. However, my code is not commented :/
Answer: Observe that
$$
\frac{e^{x_i}}{\sum_j e^{x_j}} = \frac{e^{-m}}{e^{-m}}\frac{e^{x_i}}{\sum_j e^{x_j}}= \frac{e^{x_i-m}}{\sum_j e^{x_j-m}}
$$
for any constant $m$.
Obviously it is not true that $e^{x_i} = e^{x_i-m}$, but the normalized versions are the same. Your problem is that the $x_i$s are too big, so subtract the same number $m$ from all of them before you take the softmax. Sometimes people set $m$ to be the maximum of all the $x_i$s.

Softmax overflow


Why should ThreadPoolExecutor be used with Retrofit?

Question: I saw android's ThreadPoolExecutor implementation with Retrofit somewhere. I am confused what is a logical need of using this executor with retrofit even if retrofit already provides us mechanism of asynchronous api calls, which will be run in different background threads without affecting other api calls?
Answer: In my case, server is misconfigured and cannot manage simultaneous request. The server developper refuse to fix this problem on her side... For this reason, i add a ThreadPoolExecutor at Retrofit into my application for execute request one by one. Application use multiple Retrofit adapter, this library was not designed for that...


No Drupal Site Found when clearing cache

Question: I installed drush using composer following the instructions here: http://docs.drush.org/en/master/install/
When trying to run drush cc all I get this error:

No Drupal site found, only 'drush' cache was cleared.[warning] 'all'
  cache was cleared. [success]

I added this line:
export PATH="/Applications/MAMP/bin/php/php5.6.2/bin:$PATH"

to my .bash_profile and restarted bash and MAMP. Still no luck. Any ideas?
This is my drush status:
 Drupal version         :  7.36
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :
 Database username      :  root
 Database name          :  srod
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush script           :  /Users/srod/.composer/vendor/drush/drush/drush.php
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/srodsite
 Site path              :  sites/default

I'm running it from Drupal project folder.
Comment: You run it from inside your drupal project folder, right?
Comment: Yes, running it from drupal project folder.
Comment: Please post the output of drush status, if all is correctly set up it should be giving you the appropriate database name. This is usually the case when incorrect values in settings.php
Comment: Added my drush status in my original post
Comment: I can't seem to update the PHP executable... does this have something to do with the issue?
Comment: What if you sudo drush?
Answer: I figured out that you will need a mysql server installed and included in path, even if you are using mysql from AWS RDS.
Comment: This seems sadly correct but it shouldn't be that way
Comment: Thanks for this! I have a Drupal installation where I'm using an RDS instance and didn't bother installing mysql on the server itself. Luckily I found your answer quite quickly and didn't spend too much time running around in circles. The error drush outputs doesn't make any sense.
Answer: For people working on Windows, you need to verify that your PATH Variable for MYSQL is properly set. I had the problem when I had upgraded my WAMP.
Example like this : C:\wamp\bin\mysql\mysql5.6.17\bin
Comment: It's worked for me. I realize the error was from sql once I execute command drush sql-cli and it's return error unrecognized mysql command
Answer: Haven't tried it myself, but maybe you want to try what is mentioned here , and which points to https://www.drupal.org/node/1428638 . Here is a quote from it:

Edit the settings.php file of your drupal installation, and go to the
  database settings entry.
change the host line to:
'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',

Curious to hear if that could help ...
Answer: If you're running inside Drupal root folder, there are two possibilities which may go wrong:

drush cannot find Drupal core files (you don't have index.php or common.inc), check by:
find -maxdepth 2 -name index.php -o -name common.inc

Your PHP CLI doesn't have PDO extension (php -m | grep pdo).
Comment: So how do we fix these things?


_append_dispatcher() missing 1 required positional argument: 'values'

Question: i'm getting this error how to resolve it
I don't know why i'm getting this error
Comment: The message is very clear, you didn't fill the `values` parameter.
Answer: np.append function gets 2 arguments. first argument is input array and second one is values. In mentioned problem, you didn't pass the second argument to np.append function.
details in site


A view to display only nodes related from user field

Question: So I have user accounts and have added some custom fields to the user accounts. One of the fields is 'field_procedures' which is a entity reference to a content type called procedures.
Inside a view now, which is a calendar view, I want to display ONLY the procedure nodes that have been selected in the 'field_procedures' field that match that user. So that I am able to set which procedure nodes that are related to this user and want him to only see the calendar with of that node type he has been selected for.
I can't figure out how to set this up.
Answer: In Views add a relationship to the "Entity Reference: Referenced Entity", then add a contextual filter for UID with a default value taken from the URL.
See also http://codekarate.com/daily-dose-of-drupal/using-views-entity-reference-module-drupal-7
Comment: The only option I have for that field in relationships is.

Entity Reference: Referencing entity
A bridge to the User entity that is referencing Content via field_procedures

seems the Referenced item is available for that field.
Comment: Is your view of the suer table or the node table? It sounds like it is the user table, and it should be the node table.
Comment: So this works for a single entity reference. However the user account has 2 fields that are entity references. If I add another relationship for that other entity reference and a contextual filter with UID for that new reference. Then it displays nothing. It seems that I can display one entity reference or the other but it will not let me display both at the same time. Do you have any ideas on how to fix this?


Imagecache: configure image canvas

Question: I'm using Drupal 7 and I'm trying to create an image style, which resizes and crops an image and adds another image as the background. The latter image is the canvas for this image style. I am using the Imagecache module and so far I tried either adding the canvas image as "Underlay (background)" or as "Overlay (watermark)", but with either of these selections the problem is that the background image and the front image are positioned at x:0, y:0, and the result is not what I want, meaning both image are on top of the other.
Is there a way to define an offset for the image I want to be inside the canvas image? Otherwise, is there another way of doing this?
Please let me know if I didn't express my question clearly.
Thank you!
Comment: Which version of Drupal are you using ?
Comment: Yeah, sorry for that, I'm using Drupal 7
Answer: I assume you are using imagecache_actions module. I enabled imagecache_canvasactions module too that comes with imagecache_actions module.
Once i enable above mentioned modules, i can able to see offset for X & Y while adding Underlay (Background Effect) . See screenshot below. I set offsets to 50 & 40 see the style in action in second image.
Comment: Thanks for your reply. My bad, I thought the offset was related to the background image and not the one in the front. Thank you :)

Imagecache: configure image canvas


How do you define Harmonic Retrogression with regard to intensity?

Question: I was doing some practice problems in the AP Barron's Music Theory book, and one of the practice problems asks: "When harmonies within a phrase move from a strong intensity to a less strong intensity [...] it is called:", and the answer is retrogression.
I'm confused by this definition, as V-I would certainly not be a harmonic retrogression, yet the intensity is decreasing. On the other hand, something like IV-V⁷ would be increasing in intensity, and indeed, typically V⁷ or vii° is the last chord before returning to the tonic.
My question then is: how accurate is the book's definition? Has this sort of definition been corroborated by other music theory texts?
Comment: I'd be curious to hear what they say in the [...] portion of your quote!
Comment: Not enough for an answer: I've not seen such an "intensity" definition of retrogression, and I think your reasoning re. `V I` makes perfect sense. But, as Richard said, the full definition might tell more.
Comment: The part was cut off, but some of it is actually still readable. It said "e.g. a root position V to a root position [...]".
Answer: Interesting. I think the problem lies in a pretty poor definition.
As you've said, there are all kinds of ways to understand "intensity," so it's not hard to come up with examples that seem to defy the definition.
It seems that they mean "intensity" as something like "tendency to resolve towards tonic," but presumably the tonic chord isn't included in this set.
Thus V to IV is a retrogression because IV has a weaker tendency to resolve towards tonic (often explained by its lack of a leading tone) than V does.
Of course, the problem with this understanding of the quote is that it's somewhat circular. To understand what a good progression is, you need to understand chordal tendencies to resolve towards tonic. And to understand chordal tendencies to resolve towards tonic, you need to understand what a good progression is.
It also confuses something like IV moving to vi. This, to me, is something of a retrogression, but I can't define "intensity" in any way to suggest that one should come before the other.
A better approach, in my opinion, is that found in several recent textbooks: that of a "phrase model" or harmonic paradigm of distinct zones (tonic, predominant, dominant), and how those zones function with respect to each other (like dominant not typically moving backwards to predominant, etc.).
Comment: Yeah, that makes sense. I suppose it's not a big deal since I know in practice where each chord should and shouldn't go, and so I don't need a more nebulous definition. I think it might not be totally circular though, as 4-part counterpoint arose out of 2-part counterpoint (I think?) -- that is to say, you could relate everything to voice leading. Though this relationship is probably messy and psychologically, I'd guess we have some weird mix of purely chordal thinking and purely melodic thinking.
Answer: I second @Richard's comment that it's a poor definition. Here is some evidence from other textbooks than AP Barron's.
In Steven G. Laitz's The Complete Musician (which uses the "phrase model" mentioned by @Richard), retrogression is defined as follows:

a backward motion [such as] from D to PD [dominant to predominant] is called a retrogression.1

This is used to introduce the concept of back-relating dominants, in which a dominant chord serves to expand the preceding tonic harmony but does not itself resolve to the tonic. The example given is from Bach's Prelude in Eb Major from The Well-Tempered Clavier, Book 2 (BWV 876), excerpted here:
<code>X: 1
T: Prelude in Eb Major, BWV 876
T: from The Well-Tempered Clavier, Book II
C: Bach
M: 9/8
K: Eb
L: 1/8
%%score (V1 V2) | V3
[V:V1 stem=up] B3 z3 z Ge | {e}d3 z3 z FG | ACE
[V:V2 stem=down] G3 z3 z G2 | F3 z3 y3 | y3
[V:V3 clef=bass] z ED EB,G, E, zz | z B,=A,  B,F,D, B,, zz | F,zz
w: I | V7 | ii7
w: Tonic | BRD | PD
</code>
Aldwell and Schachter, in Harmony and Voice Leading, devotes a brief section to back-relating dominants, but nowhere uses the term "retrogression."2 The Oxford Companion to Music and The Norton/Grove Concise Encyclopedia of Music also do not have entries for "retrogression."

1 Steven G. Laitz, The Complete Musician, 2nd ed. (2008, Oxford University Press), pages 452-53.
2 Edward Aldwell and Carl Schachter, Harmony and Voice Leading, 2nd ed. (1989, Harcourt Brace Jovanovich), pages 146-47.
Comment: It's interesting that those sources don't include the idea of "retrogression." I wonder if it's a relatively new addition to the discourse, perhaps something that appeared along with the interest in analyzing popular music (which uses these types of "retrogressions" all the time)?
Comment: @Richard FWIW, I did a quick search in Google Scholar and found the term used, with an example, in Betty Jean Thomas's 1963 dissertation "[Harmonic materials and treatment of dissonance in the pianoforte music of Frederic Chopin](https://urresearch.rochester.edu/institutionalPublicationPublicView.action?institutionalItemId=5002&versionNumber=1)". See chapter 6, page 194.
Comment: @Richard Also, Google's Ngram Viewer places the first English use (since 1800) of "musical retrogression" in 1860. Based on their chart, it saw its most frequent use around 1915/1925, flourished somewhat in the 1950s and 60s, and has remained in use but tapered off since then.
Comment: @Richard Again with Ngram Viewer, "Back-relating dominant" was unused (in English) between 1800 and 1963, but has generally increased in usage since then.
Comment: @Richard Got it. Sort of. The idea of the back-relating dominant goes back to the Schenkerian idea of the "[divider at the fifth](https://en.wikipedia.org/wiki/Schenkerian_analysis#The_arpeggiation_of_the_bass_and_the_divider_at_the_fifth)". This much I'm confident in. It's not clear to me, however, whether BRD is just the English term adopted for the concept, or whether it's a refinement on the original concept. In either case, my best guess is that the term originates with Aldwell and Schachter, but I can't confirm.
Comment: After all that, you were talking about "retrogression", not "back-relating dominant". Well, at least one of us is enlightened now.
Comment: No, this is all very interesting! The term certainly appeared much earlier than I expected.
Answer: What they are asking you is how retrogression defined as a weaker root movment has contrast to a progression defined as a forward movement of 5 so depending on the key in which the example is and how the enharmonic indifference marks the intervals count will define weather or not the point of is a forward progression or a contrast retrogression with in the bar phrase
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Trying to set a default background picture using Angular.js

Question: I'm new to Angular.js and I'm running into a problem. I'm using ng-repeat to iterate through a list of news items. Each item has a Title and Body, but will have an optional picture url that will be used as the background.
I can get the news item elements with picture URLs to display when there is a url present. See sample code below.

I need to set the    announcement.Url value to a default background picture URL when announcement.Url is NULL or Undefined. Not sure how I can go about this.
Any help would be much appreciated.
Thanks!
Answer:

Anything between {{ and }} is an angular expression (similar to javascript itself as far as a beginner is concerned). You can simply include the || operator (a logical OR) and put the path to your default image in a string after that. If announcement.Url is null or undefined then it will be "falsy" and the latter half of the OR conditional will be used.
Edit: Notice that I escaped the string delimiters (\') because they are already nested inside a string that uses those delimiters.
Comment: Awesome! Thanks Alex. It actually worked without the escaping.
Comment: Oh Angular you sly dog ;)


How to run executable file a.out created in my laptop gcc environment in other laptops?

Question: I have written a program code in c compiled and executed in gcc compiler. I want to share the executable file of program without sharing actual source code. Is there any way to share my program without revealing actual source code so that executable file could run on other computers with gcc compilers??
Comment: Just share the compiled file? I don't understand the question..
Comment: Then it will depand on version of the standard library for your compiler is installed in your OS by default (which you can't rely on, in general). If you install  same Linux version , on two machine then there is a chance your executable run successfully.
Comment: yes. without sharing actual source code(.c file), i want to share compiled file(a.out) compiled in gcc compiler
Comment: Why can't you just do it? Share the binary executable.
Comment: Do you want to run shared `a.out` on old environments (older than the one on where you compiled) ?
Comment: Binary executable created in my gcc environment contains my linux os and my environment information. will it run on other machines with gcc environment??
Comment: Other machine means? Same architecture? If not then you need cross compiler and you have to link library statically.
Comment: same architecture, same linux environment
Answer:
Is there any way to share my program without revealing actual source code so that executable file could run on other computers with gcc compilers?

TL;DR: yes, provided a greater degree of similarity than just having GCC.  One simply copies the binary file and any needed auxiliary files to a compatible system and runs it.

In more detail
It is quite common to distribute compiled binaries without source code, for execution on machines other than the ones on which those binaries were built.  This mode of distribution does present potential compatibility issues (as described below), but so does source distribution.  In broad terms, you simply install (copy) the binaries and any needed supporting files to suitable locations on a compatible system and execute them.  This is the manner of distribution for most commercial software.
Architecture dependence
Compiled binaries are certainly specific to a particular hardware architecture, or in certain special cases to a small, predetermined set of two or more architectures (e.g. old Mac universal binaries).  You will not be able to run a binary on hardware too different from what it was built for, but "architecture" is quite a different thing from CPU model.
For example, there is a very wide range of CPUs that implement the x86_64 architecture.  Most programs targeting that architecture will run on any such CPU.  Indeed, the x86 architecture is similar enough to x86_64 that most programs built for x86 will also run on x86_64 (but not vise versa).  It is possible to introduce finer-grained hardware dependency, but you do not generally get that by default.
Operating system dependence
Furthermore, most binaries are built to run in the context of a host operating system.  You will not be able to run a binary on an operating system too different from the one it was built for.
For example, Linux binaries do not run (directly) on Windows.  Windows binaries do not run (directly) on OS X.  Etc.
Library dependence
Additionally, a program built against shared libraries require a compatible version of each required shared library to be available in the runtime environment.  That does not necessarily have to be exactly the same version against which it was built; that depends on the library, which of its functions and data are used, and whether and how those changed over time.
You can sidestep this issue by linking every needed library statically, up to and including the C standard library, or by distributing shared libraries along with your binary.  It's fairly common to just live with this issue, however, and therefore to support only a subset of all possible environments with your binary distribution(s).
Other
There is a veritable universe of other potential compatibility issues, but it's unlikely that any of them would catch you by surprise with respect to a program that you wrote yourself and want to distribute.  For example, if you use nVidia CUDA in your program then it might require an nVidia GPU, but such a requirement would surely be well known to you.
Answer: Executable are often specific to the environment/machine they were created on. Even if the same processor/hardware is involved, there may be dependencies on libraries that may prevent executables from just running on other machines.
A program that uses only "standard libraries" and that links all libraries statically, does not need any other dependency (in the sense that all the code it need is in the binary itself or into OS libraries that -being part of the system itself- are already on the system).
You have to link the standard library statically. Otherwise it will only work if the version of the standard library for your compiler is installed in your OS by default (which you can't rely on, in general).
Comment: No, that's much too strong.  It is downright *common* to distribute pre-built binaries, including binaries linked against shared libraries.  This does open you up to library compatibility issues, but its not as bad as the execution environment having to have the exact same version of every shared library used.


Laravel scope dynamic

Question: I need to get logged user notifications by scope but it returns App\User::notifications must return a relationship instance.
Code
layout
@auth
    @if(auth::user()->notifications > 0)

            ×

                @foreach (auth::user()->notifications as $notification)

{{$notification->subject}}

                @endforeach

            Success! Indicates a successful or positive action.

    @endif
@endauth

User model
public function notifications() {
  // return $this->hasMany(ProjectBroadcastApplicant::class);
  $notifications = ProjectBroadcastApplicant::where('user_id', $this->id)->get();
  return $notifications;
}

ProjectBroadcastApplicant model
public function user() {
  return $this->belongsTo(User::class);
}

Where did I make mistake?!
Answer: Update your user Model:
public function notifications() {
    return $this->hasMany(ProjectBroadcastApplicant::class);
}

If you want to filter the notification for the user then you can add condition with the relationship definition.
Answer: Solved
I've changed my user model to this
public function notifications() {
  return ProjectBroadcastApplicant::where('user_id', $this->id)->get();
}

and my blade from @if(auth::user()->notifications > 0) to @if(auth::user()->notifications() > 0)
now it's working.
Comment: Yes, you have changed the relationship to function so it will work

Laravel scope dynamic


Could not find or load main class when I add external libraries

Question: Hey I got this problem when running a java program through my cmd.
I use to external libraries : lwjgl.jar and slick-util.jar
when I compile
javac -d bin -sourcepath src -cp ;lib/lwjgl.jar;lib/slick-util.jar src/*.java

everything works fine
but when I try to run it
java -cp bin .;lib/lwjgl.jar;lib/slick-util.jar; Game

I get this error
Error: could not find or load main class .;lib.lwjgl.jar;lib.slick-util.jar;

Answer: Replace the space in the run command classpath with a classpath separator
java -cp bin;.;lib/lwjgl.jar;lib/slick-util.jar; Game
            ^

as an improvement to the run command you could use a classpath wilcards, for example
java -cp ".;bin;lib/*" Game

It is important to use quotes under Windows for this option
Comment: Okay I added the ";" so it's looks like yours above but now i get the following error

`Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path ...`
Comment: That's a different error where the the `LD_LIBRARY_PATH` needs to be set for `lwjgl`. However that is for another post.The JVM is now finding the `Game` class.
Comment: So i opened a new post and the people at stackoverflow solved it [HERE](http://stackoverflow.com/questions/17989345/java-lang-unsatisfiedlinkerror-no-lwjgl-in-java-libary-path-at-java-run)


Find roots of a specific discontinuous trigonometric function

Question: Given the following function $f(x)$ and an arbitrary positive non-prime integer $N$
$ \{ f(x) = \sin(N\pi/x) + \cos(2N\pi/x) + |sin(3N\pi/x)| + |cos(5N\pi/x)| + 1, N \in \mathbb{Z}, x \in \mathbb{R} \}  $
I am looking for any root in the range $2 <= x < N$, I am pretty sure all $f(x)$ are greater than or equal to zero, so the roots are global minima. All the roots are also points of discontinuity and their $x \in \mathbb{Z} $.
Question
Is there any, even numerical way, to go about finding these roots for any arbitrary non-prime N? Or even just point me in the right direction like an algorithm name, I'm a software engineer, and familiar with arbitrary precision libraries like GMP, so I can implement numerical methods if I can understand the math.
Here is a plot of $f(x)$ for $N=517$. It isn't very good, its hard to choose a zoom level which will demonstrate all the features. But you can see I marked a zero at $x=22$, you will notice it looks like there is a zero at $x \approx 26.5$ but it is actually $ f(x) \approx 0.0011 $ if one were to zoom in.
There are many of these "close" to zero points, but none are actually zero, in the range I'm interested in ($ 2<=x<N $), unless 2 conditions I have found are met:

$x \in \mathbb{Z} $
$GCD(x,N) > 1 $

My example $N=517$ the roots are $ x \in \{-2,22,94\} $, we don't care about $-2$ and $GCD(22,517)=11$ and $GCD(94,517) = 47$.
I don't think the GCD observation will help in finding the roots, but I mention it because I think its interesting. And if anyone has an insight as to why this GCD relationship exists but not the main question still feel free to answer.

Here is another plot, in response to @poetasis comment below. I zoomed out to show a little better that all values of $f(x)$ are greater than zero except 3 points which are equal to zero where $ x \in \{-2, 22, 94 \} $ though its only really easy to see $ f(94) = 0 $ at this zoom level.
Also notice the period is not regular or an integer, it gets larger as we move right. The zeroes occur at those M-shaped downward "spikes". The spikes occurring where x is an integer actually touch the zero line, like at $ x = 94 $, the others occurring off an integer like the one around $ x = 147.7 $ can be close but not zero $ f(147.7) = 0.00859 $.
I put in some $x$ and $f(x)$ values of the M-shaped spikes so you can see below. There are other spikes, they all occur on non-integer $x$'s as well and have non-zero $f(x)$
In case its too hard to read, for N=517
$f(22)=0$
$f(38.3)=0.0767$
$f(68.96)=0.0480$
$f(94)=0$
$f(147.7)=0.00859$
Comment: @poestasis - oh I see, convenient fractions of $\pi$ instead of all the reals.
Comment: $$x = \frac{2 N}{4 n - 1} \quad\text{for}\quad N\ne0 \land n \in\mathbb{ Z}$$
Comment: @poetasis, thank your for your comment, but I'm not sure I understand. You say $$ x = \frac{2N}{4n-1} $$ for $$N \neq 0 \wedge n \in \mathbb{Z} $$ Is that supposed to give the x's of the roots?
Comment: Given some non-zero $N$, and any integer $n$, I believe these values will yield integers for the expression. Example, for $\quad N=3\land n=1\rightarrow x=2.\quad$ I believe all the trig terms will be using multiples of $\pi/2$ and the calculations should be relatively easy.
Comment: @poetasis - If you look at a plot of the function though it is not cyclic with a regular period like a simple trig function.
Comment: I'm simply saying that this should provide values of $x$ that provide convenient fractions of $\pi$ for ease of calculations as opposed to points of discontinuity. I should also have mentioned (but you did) $N\in\mathbb{Z}$.
Answer: This will be easier if you substitute $t=\frac{1}{x}$ and graph it as a function of $t$.
Looking at the zeros of the $t$ function, you will see that for each $N$, they form an arithmetic progression whose terms are easily discernible.
For example, here is the graph of $f(t)$ for $N=4$.

It is not difficult to work out that the first zero is always
$$ t_0(N)=\frac{3}{2N} $$
and that the common difference of the sequence of zeroes is
$$ d=\frac{2}{N} $$
So the $k$th zero for $N$ will be
$$ t_k(N)= \frac{3+4k}{2N} $$
The reciprocals of these will be the zeros of $f(x)$.
$$ x_k(N)=\frac{2N}{3+4k} $$
Note that $x_{11}(517)=22$.
Comment: Thank you for your response @John Wayland Bales. Let me clarify my motivation in creating the function, I was trying to make a function to factorize integers. I realize its a pipe dream, alot of people alot smarter than me have thought about it alot longer, but just something to do. I was hoping I could create a function that was differentiable, or at least had some rhyme or reason to it, where the roots or something other aspect I could get the factors for an arbitrary composite integer. Continued in next comment ...
Comment: I started with $$f(x)=sin(\frac{N\pi}{x})$$ which has many zeroes (roots), its integer factors are in the set of roots. But it has many many roots, checking them all is no faster than factoring. So I kept tweaking it until I came up with the function in my original post, which only has roots on integers, and all positive roots of the function have a GCD with N that is non-trivial, and calculating GCD is really fast so essentially if I can find the roots I can factor the integer. But trying to find the roots of a discontinuous function like that is out of my skill range.
Comment: I wish you luck.


How does Oracle database know the global database name and the location of database files merely from ORACLE_HOME and ORACLE_SID?

Question: How does Oracle database know the global database name merely from ORACLE_HOME and ORACLE_SID?
My ORACLE_SID is foosid and my database name is foogdn. In fact, the global database name is foogdn.example.com. This is demonstrated in the shell and sqlplus session below.
$ export ORACLE_SID=foosid
$ export ORACLE_HOME=/home/ora/app/ora/product/12.1.0/dbhome_1
$ "$ORACLE_HOME/bin/sqlplus" / as sysdba

SQL*Plus: Release 126.96.36.199.0 Production on Tue Aug 2 12:20:19 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to an idle instance.

SQL> startup
ORACLE instance started.

Total System Global Area  419430400 bytes
Fixed Size          2925120 bytes
Variable Size         285216192 bytes
Database Buffers      125829120 bytes
Redo Buffers            5459968 bytes
Database mounted.
Database opened.
SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT
SQL> select * from global_name;

GLOBAL_NAME
--------------------------------------------------------------------------------
FOOGDN.EXAMPLE.COM

SQL> select name from v$controlfile;

NAME
--------------------------------------------------------------------------------
/home/ora/app/ora/oradata/foogdn/control01.ctl
/home/ora/app/ora/fast_recovery_area/foogdn/control02.ctl

SQL> select name from v$datafile;

NAME
--------------------------------------------------------------------------------
/home/ora/app/ora/oradata/foogdn/system01.dbf
/home/ora/app/ora/oradata/foogdn/sysaux01.dbf
/home/ora/app/ora/oradata/foogdn/undotbs01.dbf
/home/ora/app/ora/oradata/foogdn/pdbseed/system01.dbf
/home/ora/app/ora/oradata/foogdn/users01.dbf
/home/ora/app/ora/oradata/foogdn/pdbseed/sysaux01.dbf
/home/ora/app/ora/oradata/foogdn/pdborcl/system01.dbf
/home/ora/app/ora/oradata/foogdn/pdborcl/sysaux01.dbf
/home/ora/app/ora/oradata/foogdn/pdborcl/pdborcl_users01.dbf

9 rows selected.

SQL>

Two questions:

How did the database figure out that the GLOBAL_NAME for ORACLE_SID=foosid is foogdn.example.com? The only pieces of clues I provided were ORACLE_SID and ORACLE_HOME and then started the database. Then the database seems to have figured out on its own that the global database name is foogdn.example.com. How did it do that? Where does it store the mappings of ORACLE_SID to GLOBAL_NAME?
How did the databae figure out the location of the database files? Where is this information stored?
Answer: Example.com(logical location of your DB) is the value of db_domain parameter. foogdn is the database's name - value of db_name parameter. Values of db_name and db_doman make up global database name.  Both db_domain and db_name are stored in either or both spfile<SID>.ora and/or init[<SID>].ora files. Moreover, database name is stored in the control file(s) and in the header of each datafile along with DBID.
The basic structure is:
You specify oracle SID (system identifier) which is used to locate an initialization parameter file whether it's a server parameter file (spfile<sid>.ora) or a text initialization parameter file init<sid>.ora. CONTROL_FILES parameter in the IPF(initialization parameter file) points to the location of control file(s) which contains information about data , redo log, and other file's location.
Find out more


if $A \subset B \subset X$ then $\mbox{dist}(x,B) \le \mbox{dist}(x,A)$

Question: Prove that if $A \subset B \subset X$ then $\mbox{dist}(x,B) \le \mbox{dist}(x,A)$.
My attempt (by contradiction) :
Suppose that $\mbox{dist}(x,B) > \mbox{dist}(x,A)$. So we have that:
$(\forall a \in A)(\forall b \in B) \quad d(x,b)>d(x,a)$
Using triangle inequality we have that:
$d(x,b) < d(x,a) + d(a,b)$
So from these two inequalities we have that $(\forall a \in A)(\forall b \in B) \quad d(a,b)>0$ thus $(\forall a \in A)(\forall b \in B) \quad a \neq b$. I suppose that it is conflict, because for any $a \in A$ we have that $a=b$ where $b \in B$.
Does it work? Have you maybe any other idea?
Answer: I think your idea works. But it can also be done in a much simpler way:
$$
\mbox{dist}(x,B)=\inf\{\mbox{dist}(x,b):\ b\in B\}\leq \inf\{\mbox{dist}(x,b):\ b\in A\}=\mbox{dist}(x,A).
$$
The inequality is simply due to the fact that in the right-hand-side we are taking the infimum over a smaller set.
Comment: Of course, I understand your proof but it is only prescribing the definition of dist. Thus, is it possible to prove these inequality with infimum?
Comment: If you don't want to definition of the distance between a point and a set, how do you deduce in your proof that $\mbox{dist}(x,B)>\mbox{dist}(x,A)$ implies that $\mbox{dist}(x,b)>\mbox{dist}(x,a)$ for all $a\in A, b\in B$?