Struggle improvising guitar with other musicians / band / jam session

Question: I can write decent original guitar / keys melodies in my own time. But when I'm with other musicians I'm lost in a jam session (unrehearsed).
I have a handful of times been lucky enough to produce some brief amazing moments in a jam session on guitar but the rest are just a mess or boring.
I can improvise melodies vocally on the fly quite easily. Does this mean I'm a singer at heart, is this just lack of technique and theory or is this the reason why it can take years for a band to write an album.
I like to hear the music and then in my own time explore the guitar for the right sound to fit it well. But with naivety comes quite original content, I'm concerned that learning scales like the back of my hand may be detrimental to originality. A few of my friends know theory backwards and can play for 30 minutes sold and sound decent (which I would like to be able to do) but they rarely play any melodies that tickle my musical lemming.
I often play songs to friends with a good theory and they are always breaking down my chords and analysing them, to understand why what I do works well.
Comment: I don't have a full answer, but a tip: Playing along with songs you like can be very helpful. First, learning a song by just listening to it and playing along will improve your ability to translate what you hear in your head to what comes out of your guitar (which is very useful when improvising). The fact that you can sing melodies is a good sign, you just need to practice translating what's in your head to your guitar. Second, jamming along with songs you like will give you more practice in a relaxed environment.
Comment: I'm not sure what you're asking. Could you clarify exactly what your question is?
Comment: If your friends are anything like me, I bet that whenever they play (I suspect improvise) for 30 minutes straight, they "rarely play any melodies that tickle **their** musical lemming(s)."
Answer: So you can produce some musical putput which pleases you, fairly regularly. More easily, when you have the luxury of time, and not so much under the pressure of the moment in a jam session.
It's pretty much the same skill, you just have to be further along the road to have it on tap instantaneously.
You say you can improvise melodies vocally on the fly quite easily. This doesn't mean you are a singer necessarily, but it does mean you are an improvisor. The process of improvisation must occur in the mind first. The implementation of getting it out through an instrument is another process. You can do this more successfully with your voice because then you don't have the limitations of instrumental technique getting in the way. It's the same for everyone -- there is a more direct connection between the voice and the mind.
Getting to the point where you can produce the sound you hear on your instrument is, in my opinion, the heart of improvisation. And a life's work. But it is a learned skill, and you might be surprised at how quickly you can make progress with some dedicated effort.
To return to your reflection on vocal output -- which is quite telling -- think about the process you went through to learn how to talk. It was pure trial and error in the beginning and, as you got better at it, you may have had more or less formal training later. It's much the same, IMHO, with music. The art of expressing yourself comes from doing it. Whether it's jam sessions or jam tracks, or playing along with records, you need practice in becoming more fluent at what you already do. As your vocabulary and understanding increases, you may benefit from more focused training in specific areas. Or it may be that as you become able to do on your instrument what you can do with your voice, you find that is exactly what you want.
BTW -- earning scales, or anything else that you do along the road to better implementing the throughput of your ideas will not hamper your originality -- quite the reverse -- you will find that the new ideas and sounds you uncover will stimulate your personal creative process, but that process will remain your own.
Answer: I play in multiple jams weekly, which I do because it is such a challenge.
It's important to have a decent idea of the various standard chord changes that are particular to the styles of music you like. For the blues it's pretty easy, as they're typically I, IV, V chords, or their alternates, which repeat in various ways. Throwing in 7th and 9th chords colors them. Rock will have a larger (or smaller amount of) variety, depending on the songs. Country and jazz can be even wider ranges of chords. The important issue is you have to be able to do those patterns without thinking, so you can listen to what's going on around you and think ahead to what you want to play when it's your turn to step out.

"I'm concerned that learning scales like the back of my hand may be detrimental to originality."

You do know that the majority of good players do know scales, and the licks we all play incorporate sections of those scales, right? People might not know the names of the scales, but that's only of secondary importance, because being able to play the notes is the important thing. Being able to play the common scales like major, relative minor, dorian, lydian, mixolydian, plus pentatonic and "blues", will carry you a lot farther than not knowing any of them and originality is better expressed by knowing your scales and knowing when to apply them, than by having absolutely no clue and fumbling around.
Jam at home with your favorite songs and learn the basic melody so you can play it over the solo space. Then start expanding on it by playing embellishments and harmonies. This isn't so much so you can play that same melody in a jam, it's so you can learn where your fingers need to go when you hear a pattern or melody in your head as you're playing in the jam.
Practice alternate fingerings for scales in the style too. When a song is going fast and furious, you need to be able to grab the notes wherever you hear them, not just because your fingers are in a certain place on the neck. That will help your comfort level and let you concentrate on getting the melody out of your head.
Don't try to be a star when you're up there. My attitude is it's all about the song, making it come alive and taking it somewhere as a group. It's not about my ability to solo, it's about my ability to fit into the song and help it breathe. I lock onto the drummer and bass to form a good back line behind the singer, and when I'm signaled then I say my bit, then STFU and slide back into rhythm. The singer should be calling the solos and breaks so pay attention and be ready.
Perhaps the hardest thing to learn is to relax and be comfortable. The jams I go to welcome people of all experience levels. I hadn't played in about 25 years when I started again, so I was really rusty and was very self-conscious. The leaders of the jams I go to remember what it was like and put together sets that work for everyone. In the beginning I was nervous to the point of feeling sick. Now I'm one of their regular work-horses; On some nights they call me up set after set to help others who are new or inexperienced. And, we're not just playing blues now; Two weeks ago we did an extended version of Billy Cobham's Stratus, which I didn't catch the name when they called it, and then recognized the riff, told myself I could do this, and ten minutes later we were laughing after having had so much fun.
Part of being comfortable is knowing your guitar and how to get a variety of sounds from it quickly. I have a Strat I love, so it's my go-to guitar, and if I want something darker and nastier sounding I'll take a T3 semi-hollow body. Strats are endemic but too many people play only on the middle pickup, so know the sound of the other settings if that's what you play.
Amps. Some jams don't let you bring your own. I don't play at those, because the fingers, guitar and amp make the sound. I've had jam leaders turn the amp down so low it was inaudible on stage, and after having that happen multiple times before I'd even played a note, I found other places to go. Have a rig you can drop on stage in a minute and have powered up and be ready to go in three. Be tuned, and very quietly noodle around and listen to the song suggestions. In short, be ready to go.
So, hang in there, find a place that soothes your heart, relax, learn to transfer your melodies to your fingers, be humble and listen to the others on the stage, then put your heart into it.
I'll be standing to the side during jams and have non-musicians ask how the heck do we do it, do we practice together, do we learn all the songs, etc. I laugh because to me it's so simple, we just listen and make it about the song and the rest just happens. Invariably though, they are amazed we can figure it out on the fly and walk off shaking their heads.
Answer: This is an old question, but something jumped out at me in this question that I wanted to address

I can improvise melodies vocally on the fly quite easily. Does this mean I'm a singer at heart, is this just lack of technique and theory or is this the reason why it can take years for a band to write an album.

What this shows is not being a "natural singer" but a lack of training in audiation: the ability to translate melodies from the mind onto an instrument.  Singing comes naturally, most people can make their voice reproduce a melody fairly easily, but doing the same on an instrument requires practice.  Thinking this shows a natural deficit is an error, it's almost like saying "I can speak very well but I can't write.   Am I just a natural speaker?"  Everyone is a natural speaker.  Writing is a skill that must be learnt.
To help with both composition and soloing, you should develop this aural skill to the point that any melody you can sing, you can also play.  This skill can be honed by practice. To train it, you should try to work out simple melodies by ear, such as twinkle twinkle little star, happy birthday etc. and work your way up from there.  If you already read music regularly, then sight singing can be a useful skill (trying to sing from music without "cheating" by playing an instrument first), but if not, then this isn't necessary, just another way to achieve the same goal.
It is impossible to overstate how important this skill is for a musician, especially if you are trying to write or improvise.
Learning scales, learning theory etc. are all also very beneficial, but until your audiation skills are at the same level, then there is a divorce between your theoretical mind on the one hand, and your musical ear on the other hand.  That is to say, you will never know how your theory sounds until you play it, and you will never know the theory behind the notes you're singing (because you don't know what they are).  The strength and power of theory comes from the way it augments and refines your musical ear: if it's kept separate then it's mostly wasted.

I like to hear the music and then in my own time explore the guitar for the right sound to fit it well. But with naivety comes quite original content, I'm concerned that learning scales like the back of my hand may be detrimental to originality. A few of my friends know theory backwards and can play for 30 minutes sold and sound decent (which I would like to be able to do) but they rarely play any melodies that tickle my musical lemming.

What you're describing here can be caused by learning basic music theory, and then relying on that instead of audiation.  This reflects a "paint by numbers" approach to music theory, where you play from a preselected set of notes, not really knowing how they're going to sound.  It's not a bad idea to have this to fall back on, especially as a beginner, but unless the proper time is spent refining the ear then it'll sound as you described.
Answer: If in doubt, play the tune.  The original tune of the song you're playing.  Play it beautifully!   The audience (if any) will love that.
Don't show off.  Improvise an alternative tune using fewer, longer notes.  As you say, no-one except other guitarists are interested in scale-playing. (And they only pretend to be interested, while waiting for it to be their turn.)
Don't worry too much about improvising. It's fun, but it's a minor requirement in most musicians' careers.  Learn to play the classic riffs and how to accompany effectively.  Learn to read music, so you can do shows and cabaret gigs.  Learn tasteful acoustic playing, you might get to meet and work with a beautiful lady who ends up doing your laundry!  You might even get some paid gigs!
I note that you can 'improvise melodies vocally on the fly' but they rarely 'tickle my musical lemming'.  Is this a band or a zoo?
Answer: Try listening attentively to the rhythm the drummer play. He lays down the general rhythm and you expand upon his ideas. If he plays a general 4/4 beat try soloing with this in mind. It also helps if you practice with a metronome as it will teach you some great skills on how to play in time.
Also you and your band mates may find worth in playing slowly at first but concentrating on playing in time. As you grow as a band you can work on playing faster. It is a team effort though.


Missing node_reference warning

Question:
User warning: The following module is missing from the file system:
  node_reference. For information about how
  to fix this, see the
  documentation page. in trigger_error() (line 1138 of
  /[localdevetc/drupalrootetc]/docroot/includes/bootstrap.inc). =>

This error usually occurs when module files are removed without a module being disabled and uninstalled first. Typically it's corrected by simply re-downloading the module files and then uninstalling it. The problem is that there doesn't seem to be a module called node_reference for Drupal 7. I tried drush dl node_reference and got:

No release history was found for the requested project
  (node_reference).
  Could not download requested project(s).

Any ideas?
Answer: node_reference is just a sub-module of the References module; that's why you can't download it using Drush. Instead, download the References module.
drush dl references

Comment: Thanks! I was about to say that I found it in my git history, as a sub-module of references, as you suggested, and was able to checkout an old commit that still contained the sub-module files, copy them to my desktop and then move them into my the latest version. I already had references.

Missing node_reference warning


Is Amazon s3 required if am using Cloudfront for files

Question: I am planning to host a website in Amazon Ec2 instant. I got some basics from the docs.
But I have few confusions.
If am using cloudfront for CDN, do i really need to server files from s3? The site am hosting is
build on Drupal. Does it have any performance difference?
Answer: You don't have to use S3 as the origin for a CloudFront distribution, you can specify an arbitrary HTTP server. There are some limitations however; from the CloudFront documentation:

A custom origin is an HTTP server, for example, a web server. The HTTP server can be an Amazon EC2 instance or an HTTP server that you manage privately. When you use a custom origin, you specify the DNS name of the server, along with the HTTP and HTTPS ports and the protocol that you want CloudFront to use when fetching objects from your origin.
Most CloudFront features are supported when you use a custom origin with the following exceptions:

Streaming distributions—Not supported.

Private content—Although you can use a signed URL to distribute content from a custom origin, for CloudFront to access the custom origin, the origin must remain publicly accessible. For more information, see Serving Private Content through CloudFront.


|slice filter does not work with special characters

Question: I try to use the slice filter in order to limit a link to a specific amount of characters. The field that I render is a link field and my code is the following:
<code>{% set title_text = title|render|striptags %}
<span>
     {{ title_text|length > 65 ?
         title_text|slice(0,65)  :
         title_text|striptags}}
</span>
</code>
Unforturnately some characters like the apostrophe are not rendered appropriately.
So instead of rendering "I've learned", they render "I& #039;ve learned"
Answer: Actually the culprit is <code>|striptags</code>

The problem with using twig's |striptags is double encoding of html entities,
  not markup, so & becomes & and then & – Berdir
source: How do I get the raw field value in a twig template?

If your setup relies on you running striptags last, you will need to do this all of this magic in a preprocess function with php setting a variable here and then printing your formatted variable on twig.


Probability at least 2 flips are tails

Question: I would like to do this the direct ways

a fair coin is tossed 3 times, find $P(\text{at least 2 flips were tails})$

Doing this directly,
$$P(\text{at least 2 flips were tails}) = P(\text{2 tails}) + P(\text{3 tails})$$
Is the answer:

$$ = (0.5)^2 + (0.5)^3$$

But the text says the probability should be $(1/2)$ which isnt in agreement with my answer?
Comment: There's more than one way to flip two tails in three flips.
Comment: To get exactly two tails you need to have one of TTH, THT, HTT. Each has probability 1/8. So the probability of exactly two tails is not 1/4 but 3/8.
Answer: We use the concept of Binomial distribution here. Let $n=3$ be the number of trials, $k $ be the number of successful trials (here, getting a tail), $p=0.5$, the probability of getting a tail and $X $, a random variables determining the number of successes.
We thus need to find $P (X=2) + P (X=3)$. Thus, $$P_{\text {req}} = P (X=2)+P (X=3) $$ $$= \binom{3}{2}(0.5)^2 (0.5)^{3-2} + \binom {3}{3}(0.5)^3$$ $$ =\frac {3}{8}+\frac {1}{8} = 0.5$$ Hope it helps.
Answer: Here is the sample space:
$\Omega = \left\{HHH, HHT, HTH, \color{red}{HTT}, THH, \color{red}{THT},\color{red}{TTH}, \color{red}{TTT}\right\}$
All the eight outcomes are equally likely to occur. In four out of eight of them (the ones that are colored red), we see at least two tails. Therefore, the probability of getting at least two tails is $\frac{4}{8} = 0.5$.
Answer: From $3$ fair coin flips, if you don't have at least two tails, you have at least two heads. Since these two states are clearly equal in probability and exclude any other possibility, they must each have probability of $\frac 12$.
Answer: Probability (exactly one tail) $=\dbinom{3}{1}\left(\dfrac{1}{2}\right)^1\left(\dfrac{1}{2}\right)^2=\dfrac{3}{8}$
Probability (no tail) $=\left(\dfrac{1}{2}\right)^3=\dfrac{1}{8}$
Required probability
$=1-\dfrac{3}{8}-\dfrac{1}{8}=\dfrac{1}{2}$

Probability at least 2 flips are tails


Eclipse Juno does not Mark Occurrences after using "Open declaration"

Question: I have Eclipse Juno Service Release 2 for Java and Android development, And I'm having difficulties in the Mark Occurrences feature.
The feature works perfectly until I press Cmd + Click to Open method/class declaration, Then it stops working in the file I navigated from. I have to close the file and open it again in order for the Mark occurrences to work properly.
Is there a way to fix the marking without closing and opening the file every time i use the open declaration feature?
Comment: Have you tried it on the current version?
Comment: Yes I have, and it works fine but last time I updated I had problems with the workspace and I had to create a new one, so I just need to resolve this for now until I'm ready for updating
Answer: As a temporary fix, I could navigate from the page that has the error to any other app and navigate back to it (Cmd + Tab twice), the occurrences work like that.
I have searched for a fix inside Juno, but the only fix i found is to update to the newer version of Eclipse.


Law of sines on SAS triangles?

Question: Is there any difference between using SSA or SAS for law of sines? Are they the same?
For example, assuming Capital letters are angles, opposite legs are lower case
If A= 28 degrees, b =14 and c =9(note that we do not know where the leg belong, do not refer to image for actual problem) , how do we know SAS or SSA triangle? Can we use law of signs to solve this "special case triangle" how would we begin to solve?
Comment: It's SAS. Two sides and the angle in between. The steps for this are all over the internet. You start with the law of cosines. The picture you provided is a right-triangle however, and you mention 'legs'.
Comment: So I am still unfamiliar with this concept, I need to start with law of cosines? I can't use sines?
Comment: https://en.wikipedia.org/wiki/Law_of_cosines
Comment: You can only use law of sines if you know (or can find) an angle and the side opposite of it. If this were actually a right triangle then yes, as you know c and C.
Answer: You should probably remove the image since it conflicts with the info you have provided.
To determine if you have SSA and SAS as options you need to pick a corner and move around the triangle checking for known values. Direction doesn't matter, its a good idea to check both directions until you get the hang of it.
SSA means that you know the lengths of two consecutive sides and the angle that follows the second side.
SAS means you know the values of two sides and the angle they form together. In the case of your example, you know the values of sides b and c as well as the value of the angle that connects them so it is SAS.

Law of sines on SAS triangles?


A question about the conjugation

Question: I'm studying something about the Conjugation and my reference propose to prove that the property of being topologically mixing is preserved by conjugation.
Obviously the definition of topologically mixing is clear while about the conjugation I have that:
Give two metric spaces $X,Y$ and $f:X\rightarrow X$, $h:Y\rightarrow Y$ we can say that $f$ and $h$ are conjugate if there exists a homeomorphism $\theta:X\rightarrow Y$ such that $\theta\circ f=h\circ \theta$.($f\sim h$)
Shortly which I have to prove is: given X and Y two metric spaces and the two applications $f:X\rightarrow X$ and $h:Y\rightarrow Y$, $f$ is conjugated with $h$ by $\theta$ then $f$ is topologically mixing $\iff$ $h$ is too.
TOPOLOGICALLY MIXING: A function $f$ is topologically mixing if $\forall A,B$ open and not empty set $\exists n\in \mathbf{N}$ such that: $f^{a}(A)\cap B\not=\emptyset,\ \forall a\ge n.$
Comment: You should edit your question to include the definition of " topologically mixing".
Comment: Thanks you very much! Done!
Answer: First show by induction that from $\theta f = h \theta$ it follows that
$$\forall n \in \Bbb N: \theta f^n = h^n \theta\tag{1}$$
and from that
$$\forall n \in \Bbb N: f^n \theta^{-1} = \theta^{-1} h^n \tag{2}$$
Now, if $h$ is top. mixing, let $U,V$ be non-empty open in $X$. Then $\theta[U], \theta[V]$ are non-empty open in $Y$ (homeomorphisms are open maps) so we have some $n \in \Bbb N$ such that
$$h^n[\theta[U]]\cap \theta[V]\neq \emptyset$$
but applying $(1)$ we have
$$\emptyset \neq \theta[f^n[U]] \cap \theta[V] =\theta[f^n[U] \cap V]$$
so $f^n[U] \cap V \neq \emptyset$.
The other direction ($f$ top. mixing then $h$ too) follows by lifting $U,V \subseteq Y$ to $X$ by using the mixing property of $f$ on the open sets $\theta^{-1}[U]$ and $\theta^{-1}[V] \subseteq X$ plus $(2)$, quite in the same way.
Comment: Perfect! Thanks you very much for the complete explication!
Comment: But what LIFING mean?
Comment: @HashiramaSenju typo for "lifting".

A question about the conjugation


How do I send my output to the Rails console?

Question: I'm using Rails 5 and Ruby 2.4.  I would like to capture the output from an error, print it on my console, and so I have in one of my app/service classes
rescue => e
  error = e
  msg = "#{e.message}\n"
  e.backtrace.each { |line|
    msg = "#{msg}\n#{line}"
  }
  logger.error msg
  raise e
end

but I'm getting the below error
NameError: undefined local variable or method `logger' for #<RunCrawlersService:0x007fd14c2f1e10>
    from /Users/nataliab/Documents/workspace/myproject/app/services/run_mycustom_service.rb:34:in `rescue in block (2 levels) in run_all_crawlers'
    from /Users/nataliab/Documents/workspace/myproject/app/services/run_mycustom_service.rb:16:in `block (2 levels) in run_all_crawlers'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:348:in `run_task'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:337:in `block (3 levels) in create_worker'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `loop'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:320:in `block (2 levels) in create_worker'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `catch'
    from /Users/nataliab/.rvm/gems/ruby-2.4.0/gems/concurrent-ruby-1.0.5/lib/concurrent/executor/ruby_thread_pool_executor.rb:319:in `block in create_worker'

How do I properly send my output to the console?
Comment: Though accepted answer solves your problem, you can give a try to [pry](https://github.com/pry/pry) for debugging your application.
Answer: You want to use Rails.logger:
rescue => e
  Rails.logger.error "#{e.message}\n"
  e.backtrace.each { |line| Rails.logger.error "#{msg}\n#{line}" }
  raise e
end

Comment: You can use __any__ logger (e.g. pure Ruby `Logger` or `Log4r::Logger`), Rails logger is just the most popular solution.


In Rails, how would you create a DB entry asynchronously using fetch?

Question: What I want to achieve
When the user clicks on the thumbs up, in the database join table likes(user_id, project_id), an entry is created to reflect the users upvote on the project. The count is updated unless the user has already upvoted the project before.
I was hoping a simple JS fetch request would do. Unfortunately, it results in a 500 error.
home.html.erb

...
    143
...

application.js
...
document.addEventListener('turbolinks:load', () => {
...

  const upvote = () => {
    document.querySelectorAll('.tag.upvotes').forEach((tag) => {
      tag.addEventListener('click', (e) => {
        const project_id = e.target.closest('.card').dataset.projectId;
        fetch(`projects/${project_id}/like/`, {
          method: 'post'
        })
        .then(response => response.json())
        .then(data => {
          console.log('Success:', data);
        })
        .catch((error) => {
          console.error('Error:', error);
        });
      });
    });
  }

  upvote();

});

routes.rb
Rails.application.routes.draw do
  ...
  post 'projects/:id/like', to: 'projects#like'
end

projects_controller.rb
class ProjectsController < ApplicationController
  ...

  def like
    @project = Project.find(params[:id])
    @like = Like.create(user: current_user, project: @project) unless Like.where(user: current_user, project: @project)
    render json: Like.where(project: @project).count.to_json
  end
end

Comment: Could you try "fetch(`/projects/${project_id}/like/`" ... With an extra slash before the projects on the fetch?
Comment: Hi jad, the issue seems to lie with the line starting with `render ...`. How would I return a simple string (in the controller) and how would I handle it with fetch (in the JS file)?
Comment: What output do you get by calling the URL directly in the browser? (Can you add it to the question?)
Answer: Well, your JSON response would return an error. You're basically writing something like this 2.to_json
Create a proper JSON like:
{ number_of_linkes: Like.where(project: @project).count }.to_json

then in the JS code write data.number_of_likes


Noetherian PI rings are fully bounded

Question: Can any one give me a precise reference for justifying that Noetherian PI rings are fully bounded. Thanks a lot.
Answer: There appears to be a full proof in this article by a pupil of Hajarnavis (see Proposition 5.3). In case the link dies, here's an improvised citation:

Bellamy, Gwyn. Localization in P.I. rings (Supervised by C.R. Hajarnavis) (2006).

I haven't proofread the whole thing, but it seems OK.

Noetherian PI rings are fully bounded


how to use order by field as well sort by id

Question: i have the lot of data and i have to short data that has on Approval and Approval data with
short id descending.
Like the following query:
 $query = "select * from event ORDER BY FIELD(status, 'Approval') desc";

But when new data added in event table. as when new data added in table its status is on Approval. and when i show the data .data is not sorted with event id descending.
I am confused how to use both order by field and order by id descending please help
Thanks and Regards
Comment: `ORDER BY FIELD(status, 'Approval') desc, id` ?
Comment: thanks @dfsq  i use as query  select * from event ORDER BY FIELD(status, 'Approval') desc,event_id desc
Answer: You can do as following if you want the Approval to appear first and then by descending order of id
select * from event
ORDER BY FIELD(status, 'Approval') desc ,event_id desc

Here is a real time example
mysql> select idusers from users where status = 'paid' order by idusers desc limit 1 ;
+---------+
| idusers |
+---------+
|  150949 |
+---------+
1 row in set (0.00 sec)

Above is to get the most recent paid user
mysql> select idusers,status from users order by field (status,'paid')desc ,
        idusers desc limit 3;
+---------+--------+
| idusers | status |
+---------+--------+
|  150949 | paid   |
|  150948 | paid   |
|  150947 | paid   |
+---------+--------+

In the above the most recent is the first row followed by others.
Comment: not work it show first status=active than short data for approval
Comment: Did you have `FIELD(status, 'Approval') desc` ?


Como instalar plugins em contas separadas?

Question: Tenho:

um servidor FTP com CPanel a correr sobre WHMCS
três bases de dados MySQL ligadas a utilizadores diferentes
três contas de WordPress associadas às bases de dados atrás assinaladas

Como instalar um plugin separadamente, e ligar a instalação deste mesmo plugin às três contas de WordPress?
Pretendo fazer isto porque vou ter pela frente um projecto de grandes dimensões, e preciso de poder actualizar numa só localização o plugin, que pretendo ligar com as várias contas, de modo a facilitar, a nível de arquitectura, a actualização do mesmo
Alguém forneceu-me esta solução no Stack Overflow em inglês. contudo, preciso de saber se isto move os ficheiros originais apagando-os, e se sim, qual o comando para copiar os ficheiros, de forma não destrutiva
// Set WP_CONTENT_DIR to the full local path of this directory (no trailing slash), e.g.
define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content' );
// Set WP_CONTENT_URL to the full URI of this directory (no trailing slash), e.g.
define( 'WP_CONTENT_URL', 'http://example/blog/wp-content');
// Set WP_PLUGIN_DIR to the full local path of this directory (no trailing slash), e.g.
define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content/plugins' );
// Set WP_PLUGIN_URL to the full URI of this directory (no trailing slash), e.g.
define( 'WP_PLUGIN_URL', 'http://example/blog/wp-content/plugins');
// If you have compability issues with plugins Set PLUGINDIR to the full local path of this directory (no trailing slash), e.g.
define( 'PLUGINDIR', $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-content/plugins' );

Comment: Não seria melhor montar os três em um ambiente mulsite? assim um plugin ativado na rede fica disponível para todos, e os usuários recebem acesso aos sites que vc determina. veja [aqui](http://codex.wordpress.org/Create_A_Network) como proceder
Comment: eu conheço o multisite. a questão é que o obJectivo é fazer milhares de threads para tipos diferentes de site. e não se pretende que fiquem numa só instalação, por outras questões relacionadas com arquitectura de sistema.
Comment: de qualquer das formas mesmo que um network, vou ter de criar múltiplas iterações do meu proJecto, de modo que criar uma só instalação não resolve o problema das actualizações do plugin, que tem de ser feitas a partir de uma só localização. mesmo assim obrigado :)
Comment: Oi, Tiago, não precisa marcar sua edição no texto, cada post tem um histórico que dá pra conferir quem editou o quê. Adicionei marcadores de comentário no seu código pra facilitar a leitura, normalmente ninguém edita código numa pergunta, mas como o problema não é esse, achei que facilitava a leitura.
Answer: Encontro duas maneiras para realizar isso. A primeira delas é automatizando a atualização de plugins quando tiver atualizações disponíveis. A configuração é realizada via filter, e pode inclusive limitar-se apenas a alguns plugins:
function auto_update_specific_plugins ( $update, $item ) {
    // Array of plugin slugs to always auto-update
    $plugins = array (
        'akismet',
        'buddypress',
    );
    if ( in_array( $item->slug, $plugins ) ) {
        return true; // Always update plugins in this array
    } else {
        return $update; // Else, use the normal API response to decide whether to update or not
    }
}
add_filter( 'auto_update_plugin', 'auto_update_specific_plugins', 10, 2 );

Aqui temos a documentação do Codex, que contém inclusive mais sugestões.
Se for necessário ter um controle da atualização, recomendo a utilização de serviços de gerenciamento (todos pagos):

ManageWP
InfiniteWP

Ambas soluções são bem completas, e tem features bastante interessantes.
Comment: a transposição do algoritmo proposto pode ser ainda assim interessante, para automatizar o update desse plugin, caso o update seJa feito a partir de uma quarta conta de wordpress, que vai disponibilizar o plugin as três restantes, que depois vão ser replicadas em milhares de contas de wordpress, a partir de um script
Comment: Felipe, ficou parecendo que sugere colocar aquele código no `wp-config.php`...
Comment: obrigado pela resposta. não resolve o meu problema, pelo seguinte. não pretendo ter um gestor de wordpress; o update tem de ser feito numa só instalação do plugin feita à parte, que é disponibilizada automaticamente para todas as contas do serviço. se tiver um milhão de utilizadores, não posso fazer o update nesses utilizadores todos separadamente, pois isso vai-me gerar um volume elevado de tráfego intenso. aquilo que pretendo é ter uma só instalação do plugin, e poder actualizá-la separadamente, de modo a ficar disponível a partir de uma só localização para todas as contas
Comment: Entendi. No caso a atualização não seria pelo Painel do `wordpress` e sim diretamente via FTP. Nesse caso realmente minha resposta não ajuda.
Comment: @TiagoMoraisMorgado faz sentido. Vou manter a resposta pois pode servir de ajuda caso alguém venha a pesquisar sobre o assunto. Mas vou pesquisar sobre esse seu modelo.
Comment: muito obrigado por se colocar na pele de outros utilizadores. é sempre bom ver pessoas cordeais e generosas, com o seu tipo de atitude. capazes a repensarem a solução de um problema desta natureza, mantendo ao mesmo tempo um interesse pela salvaguarda de outros utilizadores. continuação de um bom dia. votos de uma excelente semana
Comment: Tem razão, na verdade pode até causar conflitos. Era pra ter mostrado o exemplo no `wp-config` e através do `filter`. Edito assim que possível.
Answer: Uma técnica é modificar condicionalmente constantes no wp-config.php. Dá pra ter uma única base de arquivos do WordPress com um único wp-config.php e servir vários domínios, cada um com seu banco de dados separado.
define( 'DB_USER', 'user' );
define( 'DB_PASSWORD', 'pass' );
define( 'DB_HOST', 'localhost' );
define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', '' );

if ( $_SERVER['HTTP_HOST']=='www.example.com' ) {
    define( 'DB_NAME', 'www_db' );
    define( 'WP_CONTENT_DIR', '/com.example/wp-content/www' );
    define( 'WP_CONTENT_URL', 'http://www.example.com/wp-content/www');
}
elseif ( $_SERVER['HTTP_HOST']=='sub.example.com' ) {
    define( 'DB_NAME', 'sub_db' );
    define( 'WP_CONTENT_DIR', '/com.example/wp-content/sub' );
    define( 'WP_CONTENT_URL', 'http://example.com/wp-content/sub');
}

define( 'WP_PLUGIN_DIR', '/com.example/wp-content/plugins' );
define( 'WP_PLUGIN_URL', 'http://www.example.com/wp-content/plugins');
define( 'WPMU_PLUGIN_DIR', '/com.example/wp-content/mu-plugins' );
define( 'WPMU_PLUGIN_URL', 'http://www.example.com/wp-content/mu-plugins');

Esta pesquisa no WPSE é um bom lugar para começar a investigar o tema.

Outra opção é usar o WordPress Multisite. O princípio é o mesmo, uma instalação, vários sites, mas ao converter um site normal em Multisite, um painel de super-admin aparece e dali é possível criar sub-sites e controlar quais temas e plugins podem usar. Nativamente, só é possível controlar os temas disponíveis para cada site, mas é possível fazer um plugin para deixar plugins exclusivos para alguns dos sub-sites. Nesse exemplo, o filtro importante é all_plugins.
Gerenciar um Multisite tem suas particularidades que adicionam outro nível de dificuldade, nesta wiki de tag tem alguns recursos úteis.

Nas duas opções, a gestão de plugins deve ser feita com muito cuidado, é fácil derrubar vários sites de uma só vez com um erro de ortografia.
Independente da configuração escolhida para instalar vários WPs, os super-gerenciadores que cita o Felipe são bem bons. Na prática, só conheço o InfiniteWP e gosto muito, mas sei que o ManageWP é bem bom.
Comment: ok. vou experimentar o script que me indicam, Jogar um pouco com a API do wordpress, etc. basicamente, se eu modificar o wp-config para aquilo que me indicam o script vai assumir a pasta indicada no caminho, como pasta de contents, themes, etc? no fundo o que pretendo. atenciosamente, com votos de um bom outono.


Como enviar dados do banco de dados para a view usando ajax com codeigniter 3

Question: Olá! Estou com uma dúvida. Estou desenvolvendo um sistema para uma loja de móveis. Quero fazer com que o dono edite os móveis que ele cadastrou no sistema. Consigo recuperar os dados, mas não consigo colocá-los nos campos de uma janela modal

A janela de edição será esta:

Consigo recuperar os dados do banco via ajax e via segmentos do codeigniter. Mas o problema é colocá-los nesses campos.

$("#editarProduto").click(function(){
  var id = $("table#tabelaEstoque tbody .colorir td:first").text();
  if(id) {
   $.ajax({
    url: "HomeSistema/editarProduto/"+ id,
    data: {id:id},
    type: "post",
    dataType: "text",
    beforeSend: function() {
     $(".loadWateEditProduto").show();
    }
   }).done(function(dataProduto){
    window.alert(dataProduto);
    $("#editarProdutoEstoque").show();
    $(".loadWateEditProduto").hide();
   }).fail(function(){
    $("section#erroInternoEstoque").show();
    $(".loadWateEditProduto").hide();
   });
  }
  else
   $("#selectProduto").show();
 });

Código php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class HomeSistema extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper("url");
        $this->load->helper("form");
        $this->load->helper("date");
    }

    public function index()
    {
        if($this->session->has_userdata("nome")) {
            #listar usuários
            $this->load->model("recuperarUsuariosModel");
            $dados['usuarios'] = $this->recuperarUsuariosModel->recuperaUsuarios();

            # lista produtos
            $this->load->model("recuperaProdutosModel");
            $dados['produtos'] = $this->recuperaProdutosModel->recuperaProdutos();

            # listar Clientes
            $this->load->model("recuperaClientesModel");
            $dados['clientes'] = $this->recuperaClientesModel->recuperaClientes();

            $this->load->view("sistema/homeSistema-v",$dados);
        } else {
            redirect("login", "location");
        }
    }

    public function editarProduto() {
        $idProduto = $this->uri->segment(3);
        $this->load->model("RecuperaProdutosModel");
        $produtos['produto'] = $this->RecuperaProdutosModel->recuperaProdutosEdicao($idProduto);
        $this->load->view("sistema/homeSistema-v",$produtos);
    }

Como faço para editar os dados trazidos do banco? já tentei com segmentos e via post.
Comment: Tudo em `modal`? Sério mesmo? Qual é a necessidade disso?
Comment: So pra mim entender correto. Voçe quer saber como colocar os dados recebidos no formulario?
Answer: Primeiro sua lógica esta confusa, vamos por partes:

Crie uma função que retorne um JSON com os dados do produtos, somente os dados.
Utilize a função .on('click') para carregar os valores dentro dos inputs: $('#nomeProduto').val(respostaProduto.nomeProduto);
Após feito isso com todos os dados, você deve captar novamente estes dados assim que o cliente clicar em salvar, deve-se enviar estes dados a uma nova função para realizar o update no banco de dados e retornar a reposta de sucesso ou erro.
Através de Ajax atualizar a tabela dos produtos com os novos valores.

Pronto hehe.
Obs: Eu gosto de usar o $.post(UrlFunção,dados,function(data){'sucesso'},tipodeDado);
Answer: Como eu faria:
no meu botão colocaria o id do produto com o atributo 'data-' dessa forma:
<button id="editarProduto" data-produto-id="<?php echo $produto['id']; ?>">
</button>

No js eu usaria o $.post que é mais simples, assim:
$("#editarProduto").click(function() {

    event.preventDefault();

    var produtoId = $(this).data('produto-id');

    $.post("HomeSistema/editarProduto", {
        produtoId: produtoId
    }, function(retorno) {
        $(".loadWateEditProduto").html(retorno);
        $(".loadWateEditProduto").show();
    });
});

no construtor faria assim:
public function editarProduto()
{
    $post = $this->request->getPost();
    $this->load->model("RecuperaProdutosModel");
    $produtos['produto'] = $this->RecuperaProdutosModel->recuperaProdutosEdicao($post['produtoId']);
    $this->load->view("sistema/editar-produto-modal",$produtos);
}

*você precisaria ter uma view apenas para o modal


Origin of the Backbeat

Question: I've heard a lot on the origin of the backbeat. Some say it came from African voodoo and others say from the Middle East. Where did it actually come from?
Also, people say it was expressly made for moving your hips and dancing? But what about folksy Irish songs? Those definitely make you want to dance.
Comment: Even if the backbeat comes from a motivation for dance, that isn't neccesarily exclusive. There can be more than one type of music that is made the way it's made because of dancing.
Comment: @ToddWilcox indeed, one can argue that all metrical music owes its existence to dance.
Comment: Look at 'Why is the backbeat called the rockbeat?'
Comment: @phoog Agreed, although marches suggest some rhythms might have martial origins.
Answer: I don't remember where I read this, but some scholarly music history article traced the back beat to the early 1920s or so and claimed it originated with the country music (then called "hillbilly" to distinguish it from "race" music) guitar strumming patterns. It does seem to be common in US developed music, jazz, country, rock, etc.
Edit: I found a nice reference: http://tagg.org/xpdfs/TamlynPhD2.pdf
This is the appendix to a thesis (now a book) on the origins of the backbeat. I didn't find the book online.
Another article: http://www.mtosmt.org/issues/mto.14.20.2/mto.14.20.2.biamonte.html
Comment: The first link that you posted (the Tamlyn PhD) is also one that I just came across, except that yours is Part II - Appendices, whereas I found Part I - Chapters (which is the 395 page thesis). Just change the 2 to a 1 in your link, and it should work.
Comment: Thanks. I noticed the backbeat during the early 1950s. Americans would clap hands on the 2 & 4 counts and Europeans would clap on the 1  & 3 counts.  I'd like to find out a bit more about the history. Of course, now people add a backbeat to other patterns.

Origin of the Backbeat


0:0 score in basketball

Question: 0:0 is quite common score in football (soccer), it also happens in other sports. Is it possible in basketball? In other words does it ever happen in official game? If not what was the closest result?
Answer: When we are talking about professional basketball this result isn't realistic.
NBA:
On November 22, 1950, the Fort Wayne Pistons defeated the Minneapolis Lakers 19-18 in the lowest scoring game in NBA history.
This was prior to shot clock being added in 1954/55.
The lowest scoring NBA game since adding the shot-clock was in 1955, when Boston won Milwaukee 62:57 (119 points together).
The lowest score by one team was in 1999 Chicago vs. Miami when Chicago scored only 49 points.

0:0 score in basketball


jQuery selector returns duplicate elements

Question: I'm trying to select with jQuery all the rows from a table except the first one (column titles) and for that I have this selector:
$("#tableID tr:not(:first)")

Having three rows, one for column titles, and two for content, the selector returns 4, but if I do:
$("#tableID tr")

It returns the three rows just fine. Am I missing something in the selector?
I made a screenshot if it helps:

The code that gives me the problem is this (it is stupidly simple, I don't understand why it doesn't work)
    function addTableColumn() {
        var uls = $('#debate ul').length;
        $('#debate tr:first ').append("foo title	");
        $("#debate tr:not(#debate tr:first)").append("

	").hide().fadeIn("slow");
        alert("I'm seeing " + $('#debate tr:not(:first)').length + " rows (without first row), type: " + $('#debate tr:not(:first)')[0] + " but the row count returns (including titles) " + $('#debate tr').length);
        makeSortable();
    }

Answer: If it's a title row, I would recommend changing your markup to something like so:

            Title
            Title

            Content
            Content

            Content
            Content

            Content
            Content

And then, in your CSS/jQuery, only select the
s in
, it's also more semantic this way.
Comment: After separating the titles from the tbody and making the selector $('#tableID tbody tr'), the row count was fine. Thanks, this was driving me crazy!
Answer: I would use
$('#tableID tr:gt(0)')

but what you have should work!
Answer: $("#tableID tr:not(:first)") works just fine .
Comment: How's that different from OP's?
Comment: Well i took time to verifiy that this code works.. and the question was answred in that time. and yes it's the same code :)
Comment: Apparently it doesn't for the OP so please don't post useless answers, instead, use comments.
Comment: this is the second time i get downvotes , and people just say use comments , how can you comment the original post ? And i understand that people must downvote when the reponse is useless , but i don't think that this reponse was useless .. The  OP should have known by this reponse that  he missed soemthing to tell us in the markup..
Comment: i think so too. if the answer is correct, you should not downvote it. i would also think, that the selector is correct, but the page has some markup-issues (like unclosed elements).


round to inferior odd or even integer in C

Question: Working in C language, I would like to round a float number to its inferior odd integer and its inferior even integer.
The speed of the solution is very important (because it is computed 2M*20 times per seconds).
I propose this solution :
x_even = (int)floor(x_f) & ~1;
x_odd  = ((int)ceil(x_f) & ~1) -1;

I presume that the weak point is the floor and ceil operations, but I'm not even sure of that.
Does someone have a comment on this solution ; I'm interested about it's speed of execution, but if you have another solution to share, I'll be very happy to test it :-).
Comment: I actually just read this today. Might be interesting. http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1
Comment: I have a question about your solution. When x_f is 4.0, x_even is 4, however, when x_f is 5.0, x_odd is 3. Is it really what you want?
Comment: So round 1.5 to 1 and 0, respectively? -0.5 to -1 and -2, right?
Comment: I think this would make more sense if it weren't called "rounding".  It's a reasonably well-defined computation (although, what should be done for NaN and values outside the range `INT_MIN` to `INT_MAX`?)
Comment: Is `x_f` actually a value from an array? Are you on an x86 machine with a reasonably modern processor (< 10 year old)? If so, you could process four floats (or two doubles) in one go with SSE instructions, which may help, and you can do the & and -1 operation using SSE too.
Comment: Do you know anything about the value of the number? If it is in [0, 0x1p24], then you can get x_even by setting the rounding mode to downward and using `x_f + 0x1p24f - 0x1p24f`, with certain caveats about how the compiler handles floating point and . However, setting the rounding mode may be a time-consuming operation. If you bound the value, there may be similar "tricks" that take advantage of the natural rounding in floating point.
Comment: http://codereview.stackexchange.com was designed for questions such as this.
Comment: What platform?  Some platforms will have intrinsics that are designed to do this sort of thing fast (ARM).
Comment: @LightnessRacesinOrbit I think that the difference between a codereview question and a question about already working code on StackOverflow is that in a codereview question, the OP does not come with a specific aspect of the working code that s/he want to improve. Jav does (speed), and I like this question being here, for what it's worth.
Comment: @H2CO3: I don't have specification about negative numbers. But you are right, it they had been negative number, your assumption is correct.
Comment: @Alper: It is not exactly what I wanted, indeed :-/ Even if it's working like this for my usage.
Comment: @PascalCuoq: Code review is code review.
Answer: Perhaps the ceil and floor function won't be necessary as transtypage from a double to an int is equivalent to the floor function for positive integer.
Try something like this for POSITIVE INTEGERs :
double k = 68.8 ; // Because we need something to seed with.
int even  = ((int) k & ~1) ; // What you did
int test = ((int) (k+1) & ~1) ; // Little trick
int odd = (test>k) ? odd+1 : odd - 1 ;

I tested it on codepad, and it works well for on http://codepad.org/y3t0KgwW for C++, I think it will in C. If you test this solution, I'd be glad to know how fast it can be...
Notice that :

This is not a good answer as it shadows the existence of negative integers.
The range is limited to integers'.
I swapped odd and even numbers, I corrected it thank's to Chris' comment.
I'm just adding my humble stone :)
Comment: converting from double to int rounds towards 0, while floor rounds towards -infinity, so they're not the same for negative numbers.  Also, you've swapped `odd` and `even` -- your code gives `odd==68` and `even==67`
Comment: Swapping is something I master. This is just because I'm French, and I always forget which one is Pair and which one is Impair. I guess I got it wrong this time. And by the way, this code obviously sink when given a negative integer. Thank you so much for pointing the swapping out.
Answer: You don't explain what you mean by 'inferior', but assuming you mean 'greatest even/odd integer less than the given number', and assuming you have a 2s-complement machine, you want:
x_i = (int)floor(x_f);
x_even = x_i & ~1;
x_odd = x_i - (~x_i & 1);

If you want to avoid the implementation dependency of doing bitwise ops on possibly negative signed numbers, you could instead do it entirely in float:
x_even = 2.0 * floor(x_f * 0.5);
x_odd = x_even + 1.0 > x_f ? x_even - 1.0 : x_even + 1.0;

This also has the advantage of not overflowing for large numbers, though it does give you x_odd == x_even for large numbers (those too big for the floating point representation to represent an odd number).


What is $X^{\omega}$ where $X$ is a set?

Question: I fail to find a duplicate. If it exists, please link me in the comments and I will delete the question.
In my recently bought topology book, they use $X^{\omega}$ where $X$ is a set. However, this is never defined in the book, probably because it is viewed as a prerequisite (that I obviously lack). Can anyone explain what this means? I skimmed the Wikipedia-article on ordinals, without getting any wiser.
Comment: It should be the set of sequences $(x_n)_{n\in\Bbb N}$ of elements of $X$ indexed by the nonnegative integers.
Comment: $\omega$ would be countable infinity, or the set of natural numbers.  In the same way, $X^3=\{(x_1,x_2,x_3),x\in X\}$
Comment: Ok, so, to gain some intuition, $\mathbf{N}^\omega = \{(1),(1,2),(1,2,3),\cdots\}$ Given Olivier's definition, I get a feeling that this is not quite right.
Comment: In this context, a finite sequence is not a sequence "indexed by the nonnegative integers".
Answer: If $X$ and $A$ are sets then $X^A$ denotes the set of all functions $A\rightarrow X$. Here $A=\omega=\{0,1,2,\dots\}$.
Answer: Think of $ω$ as the natural numbers (one uses $ω$ when talking about the natural numbers as an ordinal number).
Say $X$ is a set.
Then $X^ω$ is defined as the set of all functions from $ω$ to $X$:
$$X^ω:=\{f:ω\rightarrow X\}$$
Each function $f\in X^ω$ (or lets use $x$ instead of $f$ - so) $x\in X^ω$ is determined by its image in $X$ - so:
$$X^ω=\{(x(0),x(1),..)|x\in X^ω\}$$
This is the same as thinking of $X^ω$ as the set of infinite sequences of elements of $X$:
$$X^ω=\{(x_0,x_1,..)|x_i\in X,\space i=0,1,..\}$$
Answer: In theoretical computer science, $X^\omega$ usually denotes the set of infinite words on the alphabet $X$.
Comment: For clarity: this definition is indeed equivalent to the definition in @YonedaLemma's answer, as an infinite word can be expressed as a function from the natural numbers to $X$.


moving D8 from one sub-folder to another

Question: If you move your Drupal 8 website from one sub-folder (example.com/oldsite) of your domain to another sub-folder (example.com/newsite), you will find that internal links to pages and references to images are not updated. Instead, these links and references will point to your old domain name. How to fix this issue?

For example, this is one of the pages after the move the site from one subfolder to another. If I click on any of this links it's taking me back to the old website.
Thanks
Comment: This just seems like content to me - you'd have to update all that content yourself or you could script it if you know how to code.
Comment: Hi, @Kevin you think this module could help in this case? https://www.drupal.org/project/pathologic
Answer: I had to update the content links manually. I learned that for to create any link for the internal content i need to use relative links instead of an absolute link.
Thank You
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/103804)
Comment: @Adrien I have followed what Kevin suggested in the above comment. I updated all links manually.


When a notification email should be sent?

Question: I have a number of action a user can preform in a social network website, like adding friends following people and such.
Now these actions are done by Ajax, and the user could easily undo them(when say following someone, the follow link is turned into unfollow and clicking it again -of course- results in unfollowing the user, and it -the link- turning back into follow).
When these actions occur, the user (being followed) is notified by via email. and the code that sends the email is run in the same ajax call.
That results in two problems, one is that the email is sent even if the user decides to unfollow the other person at once. And two, multiple emails are sent if the user hits the follow/unfollow link multiple times.
I thought of using a session variable to store users'actions and then at "some point" check on that variable and preform accordingly. My struggle is in finding that "some point", thought of when the user logs out, but I can't guarantee that the user will actually log out.
any suggestions?
Comment: This isn't really a programming problem, it's a more general site design question.
Comment: I have struggled in finding a place for my question, and couldn't find  better one>
Comment: As commented, this is actually off-topic, but i recommend just setting a timestamp and sending a mail using a cron job some time later. Anyway, I wouldn't flood my users with email, it makes them grumpy.
Answer: The easiest way I can see to do this is:
Push notifications in a DB table. Also, for users, have last activity column. Check often for any rows in notifications that occured before <code>(user.last_activity + TIME_CONSTANT)</code>, pop them from the table, group them, and send off to users.
"often" can be a cron task, or even each request (since the query would be quite simple and quick).
Comment: Since there is no hope for getting another answer I'll accept your answer :D, some rules in this site are just plain stupid!


Location for Network Location Server

Question: I am working on setting up Direct Access, and a network location server is required. Is there a best practice on where to install it?
The requirement are that it only be accessible from the intranet. So I'm thinking on the ADFS server since it has IIS, another option is the AD controller.
Answer: I would put it on your ADFS box.  Typically you don't want anything running on your DCs other than the AD DS stuff.  Whenever you can separate roles however that is a good practice, just not always realistic.
Comment: thats was I was thinking, just wanted to double check.

Location for Network Location Server


Uninitialised constant issue in custom Rails namespace

Question: I have a Rails project and wanted to create some custom queries objects to be used by my application.
The class files are in /app/queries/tasks, an example of them looks like:
module Queries
  module Tasks
    class TaskQuery
      #some code
    end
  end
end

I have added the /app/queries path to the autoload constant, and verified it with rails r 'puts ActiveSupport::Dependencies.autoload_paths' and I can see that all the directories in /app/queries is included, including /app/queries/tasks.
However, when I try to consume the object like this (from the Rails console or from the controller):
Queries::Tasks::TaskQuery.new()

I get:
Traceback (most recent call last):
        1: from (irb):1
NameError (uninitialized constant Queries)

Any idea why this is happening?
Comment: My version is Rails 5.1
Answer: Your actual code would work if the queries folder contains a queries folder, which contains a tasks folder, which contains the task_query file:
queries
└── queries
    └── tasks
        └── task_query.rb

If the queries folder is in the autoload_paths, then isn't necessary you wrap Tasks within a Queries module, since Queries is the folder that's going to hold it. Use just Tasks:
module Tasks
  class TaskQuery
    ...
  end
end

Comment: If so, then you can just use a folder structure like in the answer. It's going to be redundant for the queries case, but no for other app file types.
Comment: I really do need it in a Queries namespace (there are other task namespaces and tasks in the project).  Any suggestions?


How to subscribe to all question activities

Question: Really newbie question. Is there a simple way to get notifications inside  my inbox about all new comments, and answers for a question?
Is the favorite star the answer for me?
Comment: Ugh, can't imagine favoriting everything. Does http://meta.magento.stackexchange.com/questions/61/rss-feed-for-magento-stackexchange?rq=1 help?
Answer: You can get an RSS feed for any given question by clicking on the "question feed" link at the bottom right of the question page.
Or, if you're into manipulating URLs by hand: for the question
http://magento.stackexchange.com/questions/1234/title-of-example-question
the feed URL is
http://magento.stackexchange.com/feeds/question/1234
There are a couple of other hacky workarounds and incomplete solutions, but this is the best solution we offer that works for any given question.
Comment: I've accepted the answer, as haven't found any better alternative.


Pesquisar valores digitados em um input

Question: Estou tendo problemas para pesquisar pelo conteúdo digitado em um input e não sei o que está errado, este é o código:

let g1=document.querySelector("#g")
let p1=document.querySelector("#p")
let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
let regex = new RegExp('g1');
let newArr = [];
// mesma coisa que for (let i = 0; i < arr.length; i++)
for (let i in arr) {
  // Verifica se o item da array bate com a regex.
  if (arr[i].match(regex)) {
    // Se bater com a regex vai colocar no final da nova array;
    newArr.push(arr[i]);

  }
}
console.log('newArr: ', newArr);
for (let i in newArr) {
p1.innerText += newArr[i] + '   ';
}
<input id="g" type="text">
<button type="submit">pesquisar</button>

Answer: Ao fazer RegExp('g1'), você está criando um regex que busca pelo exato texto "g1", e não pelo valor do que foi digitado no input id="g".
Outro detalhe é que você só deve executar a busca depois que o botão for clicado. Da forma que você fez, o código executa logo que a página é carregada, e depois não executa mais.
Então uma forma de fazer é:

let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
// só executar a busca quando o botão for clicado
document.querySelector('#pesquisar').addEventListener('click', function() {
  let busca = document.querySelector("#g").value; // pegar o valor do input
  let regex = new RegExp(busca); // usar o valor do input na regex
  let newArr = [];
  for (let texto of arr) {
    if (texto.match(regex)) {
      newArr.push(texto);
    }
  }
  console.log('newArr: ', newArr);
  document.querySelector("#p").innerText = newArr.join(' ');
});
<input id="g" type="text">
<button id="pesquisar" type="submit">pesquisar</button>

Repare que usei join para juntar os resultados em uma única string, em vez do for. A diferença é que se você fizer uma busca que encontra algo, o valor do div é atualizado, mas se a busca seguinte não encontrar nada, o conteúdo do div não é apagado (pois ele não entrará no for). Já usando join, se o array for vazio, é retornada uma string vazia e o conteúdo é "apagado" caso nenhum resultado seja encontrado.

Outra forma de fazer a busca é usar filter em vez do for, que já retorna um array com os elementos que satisfazem a condição (ou um array vazio, se nenhum for encontrado):
let newArr = arr.filter(texto => texto.match(regex));

Um detalhe é que se forem digitados caracteres que possuem significado especial em regex (como o ., parênteses, colchetes, etc), isso pode resultar em uma expressão inválida e dará erro ao construir a RegExp. Neste caso, você deve usar alguma função de escape para colocar \ antes desses caracteres (aqui tem algumas alternativas).
Outro ponto de atenção é que criar uma regex com uma string que o usuário digitou requer alguns cuidados  (leia aqui para mais detalhes).

Vale lembrar também que se você só está buscando pelos elementos que possuem o trecho digitado, nem precisa de regex. Basta usar includes, que verifica se uma string é substring de outra:

let arr = ['top', 'topper', 'bot', 'bottom', 'botão', 'test'];
// só executar a busca quando o botão for clicado
document.querySelector('#pesquisar').addEventListener('click', function() {
  let busca = document.querySelector("#g").value; // pegar o valor do input
  let newArr = arr.filter(texto => texto.includes(busca));
  console.log('newArr: ', newArr);
  document.querySelector("#p").innerText = newArr.join(' ');
});
<input id="g" type="text">
<button id="pesquisar" type="submit">pesquisar</button>

Comment: @CmteCardeal
`includes` é pra ver se uma string é substring de outra (case sensitive), seria isso que vc chama de "único"? Pra qualquer coisa mais complicada vc pode usar regex (dependendo do caso, pode ou não ser a melhor opção). Não testei, mas tenho quase certeza que regex é mais lenta em praticamente todos os casos, afinal ela [tem que ser compilada](/a/486263/112052) e tem uma complexidade enorme por baixo dos panos. Mas escolher um ou outro depende do que se quer fazer...
Comment: seria possível pegar os valores dos arrays conseguidos na busca e listá-los em uma outra pagina html que seria aberta apos o evento de click acontecer?
Comment: @YuriCassu Aí já é o caso de [fazer outra pergunta](/questions/ask), detalhando melhor o que vc quer fazer (não esqueça de pesquisar no site antes, pois já devem ter perguntas sobre isso). Fazer outra pergunta é melhor porque vc tem mais espaço para detalhar e colocar o código que já tentou, além de ficar visível na página principal para todos os usuários (aqui nos comentários não tem espaço para explicar tudo e só eu vou ver) :-)
Comment: Eu já estava pensando em fazer uma pergunta, mas acho que você pode me responder por aqui. Existe alguma diferença que se deve levar em consideração ao se usar o `includes` no lugar de regex (ou vice-versa) para o caso de match único? Algo relevante a performance, por exemplo?
Comment: Era esse caso mesmo.  Pelo que falou, provavelmente includes deve ser mais performatico,  mas vou fazer uns benchmark pra confirmar.

Pesquisar valores digitados em um input


How to delete particular content from a file using python

Question: I have the following JSON file which contains some content(1st line and last line) due to which I am unable to load it as a JSON file. I want to edit this file using python so that I only have the content inside {} braces and "source.value(" &  ");" are removed.
source.value(
{Meli:1,jack:3,rustin:4}
);

    with open('check.json', 'rb') as g:
        b=json.load(g)

    Traceback (most recent call last):
      File "<input>", line 2, in <module>
        raise JSONDecodeError("Expecting value", s, err.value) from None
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Comment: `b=json.loads(g.readlines()[1]))`
Answer: I'm not sure how best to generalize for your specific problem since many things could change based on how these files are generated.
First off the json format requires the names to be in double quotes - {"Meli":1,"jack":3,"rustin":4}
Assuming this is fixed, we open the file, read the lines and only use json to read the second line. Remember python indexes from 0.
import json

with open('test.json', 'r') as file:
    lines = file.readlines()
    data = json.loads(lines[1])

Comment: Thanks for the suggestion jake but i want to read the json edit the file and then update in same format like after editing jack value to 5   the file should be updated as below            source.value(
{Meli:1,jack:5,rustin:4}
);


Representation of $\mathfrak{sl}_4\mathbb{C}$: exercise 15.12 in Fulton & Harris

Question: V is standard representation of $\mathfrak{sl}_4\mathbb{C}$ on $\mathbb{C^4}$. $\wedge^2V$ is the irreducible representation $\Gamma_{0,1,0}$.
Exercise is to prove the kernel of $\phi_n$ will be  $\Gamma_{0,n,0}$
\begin{align}
\phi_n: \text{Sym}^n(\wedge^2V) \to \text{Sym}^{n-2}(\wedge^2V)
\end{align}
Actually if we act primitive negative root vectors on the highest weight vector $(e_1\wedge e_2)^n$ to generate the irreducible representation $\Gamma_{0,n,0}$, then we can do similar thing time and time again until we get an irreducible decomposition of $\text{Sym}^n(\wedge^2V)$. The process seems tedious and the multiplicity...
Another question is how the map actually work? I can not give an example which map $\text{Sym}^n(\wedge^2V)$ to $\text{Sym}^{n-2}(\wedge^2V)$.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be closed. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognize and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: For me, the natural way to see this is that there is a natural symmetric bilinear form on $\bigwedge^2 V$:
$$ (v\wedge w, x\wedge y) := v\wedge w\wedge x\wedge y \in \bigwedge\nolimits^4 V \cong \mathbb{C}.$$
Indeed this idea actually identifies $\mathfrak{sl}_4$ with $\mathfrak{so}_6$.
A symmetric bilinear form is an element $ \omega \in\operatorname{Sym}^2(\bigwedge^2 V^*) \cong \operatorname{Sym}^2(\bigwedge^2 V)^*$, so $\operatorname{Sym}^n(\bigwedge^2 V)$ admits a contraction map by this form:
$\phi^n(\alpha_1 \odot \cdots \odot \alpha_n) := \omega \lrcorner (\alpha_1 \odot \cdots \odot \alpha_n) \in \operatorname{Sym}^{n-2}(\bigwedge^2 V)$.
If this is unclear look at how this is done for symmetric powers of the defining representation of $\mathfrak{so}_n$ or alternating powers of the defining representation of $\mathfrak{sp}_{2n}$. I'm sure Fulton and Harris go into detail on this at some point.
Edit: Having had a quick scan through the book the other examples I mentioned are given in Exercises 16.11 and 18.7. If you are not familiar with contraction, they describe it explicitly for the $\mathfrak{sp}_{2n}$ case around Theorem 17.5 and theres a whole section on it in the appendix.


Permissions denied for proftpd virtual users

Question: I installed Proftpd Administrator GUI to make it easier to manage my FTP users. The problem I have is that I have to set the directory permissions to 777 to allow the virtual users saved in the mysql database to edit and save the files. If I change it to 775, the user gets Permission Denied.
This is my proftpd.conf file
Include /etc/proftpd/modules.conf

ServerName                      "ServerName"
ServerType                      standalone
ServerIdent                     on              "Servers identifying string"
DeferWelcome                    on
DefaultServer                   on

DisplayLogin                    .welcome        # Textfile to display on login
DisplayConnect                  .connect        # Textfile to display on connec$
#DisplayFirstChdir               .firstchdir    # Textfile to display on first $

UseReverseDNS                   off
IdentLookups                    off

Port                            21
Umask                           022
MaxInstances                    15
MaxClientsPerHost               3               "Only %m connections per host a$
MaxClients                      10              "Only %m total simultanious log$
MaxHostsPerUser                 1

User                            proftpd
Group                           www-data

ScoreboardFile                  /var/log/scoreboard

# Some logging formats
LogFormat                       default         "%h %l %u %t \"%r\" %s %b"
LogFormat                       auth            "%v [%P] %h %t \"%r\" %s"
LogFormat                       write           "%h %l %u %t \"%r\" %s %b"

# Define log-files to use
TransferLog                     /var/log/proftpd.xferlog
ExtendedLog                     /var/log/proftpd.access_log    WRITE,READ write
ExtendedLog                     /var/log/proftpd.auth_log      AUTH auth
ExtendedLog                     /var/log/proftpd.paranoid_log  ALL default
SQLLogFile                      /var/log/proftpd.mysql

# Set up authentication via SQL
# ===========
AuthOrder                       mod_sql.c
SQLAuthTypes                    Backend
SQLConnectInfo                  proftpd_admin username password
SQLUserInfo                     usertable userid passwd uid gid homedir shell
SQLGroupInfo                    grouptable groupname gid members
SQLUserWhereClause              "disabled=0 and (NOW()<=expiration or expiratio$

# Log the user logging in
SQLLog PASS counter
SQLNamedQuery counter UPDATE "lastlogin=now(), count=count+1 WHERE userid='%u'"$

# logout log
SQLLog EXIT time_logout
SQLNamedQuery time_logout UPDATE "lastlogout=now() WHERE userid='%u'" usertable

# display last login time when PASS command is given
SQLNamedQuery login_time SELECT "lastlogin from usertable where userid='%u'"
SQLShowInfo PASS "230" "Last login was: %{login_time}"

# xfer Log in mysql
SQLLog RETR,STOR transfer1
SQLNamedQuery  transfer1 INSERT "'%u', '%f', '%b', '%h', '%a', '%m', '%T', now($
SQLLOG ERR_RETR,ERR_STOR transfer2
SQLNamedQuery  transfer2 INSERT "'%u', '%f', '%b', '%h', '%a', '%m', '%T', now($

AllowStoreRestart               on
AllowRetrieveRestart            on
RequireValidShell               off
#PathDenyFilter                  "\\.ftp)|\\.ht)[a-z]+$"
DefaultRoot                     ~
DenyFilter                      \*.*/

<Directory /path/to/dir>
        AllowOverwrite          on
        HideNoAccess            off
        <Limit READ>
                AllowAll
        </Limit>

        <Limit WRITE>
                AllowAll
        </Limit>
</Directory>

<Directory /path/to/dir>
        AllowOverwrite          on
        HideNoAccess            on

        <Limit READ>
                AllowAll
        </Limit>

        <Limit STOR MKD>
                AllowAll
        </Limit>
</Directory>

I put the proftpd user that is running proftpd service in www-data (the group that is set to that directory). I changed the virtual users GID to match the www-data GID from the system (which is 33). When I create a new file with a virtual user, that file GID is set to 65533 and permissions with 644. This GID doesn't exist in my systems /etc/group file.
How can I keep the folder and files permissions to 755 and let the user edit and save those files?
Answer: I suspect that mod_sql might be filtering the UID/GID values that you have assigned to your users in your SQL database.  By default, mod_sql (for historical reasons) imposes a minimum value for the numeric IDs; any values below this minimum are mapped to a default value.  See:
http://www.proftpd.org/docs/contrib/mod_sql.html#SQLMinID
and that value of 65533 comes from the defaults, e.g.:
http://www.proftpd.org/docs/contrib/mod_sql.html#SQLDefaultUID
So given this, you might try adding:
SQLMinID 1

to your proftpd.conf.
Comment: Almost 4 years later but still working on proftpd with Debian Stretch. Thanks!


Collecting lists of optionals to a list containing present optionals

Question: I am trying to refactor some code to return a list of optionals instead of an optional.
I have the following list in my class
private final List<Mapper<? extends Message>> mappers;

There is a private method that creates features for these mappers and returns a list of message
private List<Message> mapToFeature() {
        mappers.stream()
                .map(mapper -> mapper.createFeature())
                .collect(Optionals.toList());
}

The Mapper interface looks like this:
public interface Mapper<T extends Message> {
    Optional<T> createFeature();
}

The Optionals.toList() method returns a Collector to filter present optionals into a List.
I want to change the interface (and all the corresponding classes) to return a list of optionals
public interface Mapper<T extends Message> {
    List<Optional<T>> createFeature();
}

I do not have a method in the Optionals util to filter present options from multiple lists. How would I be able to do the same without making any changes to the util class?
Comment: Why do you want to change the interface to something returning `List>`? Why don't you change the interface to something reasonable, like returning just `List`, without empty optionals?
Comment: So let the code which collects these results skip `null` instead of wrapping it.
Comment: I still don't understand. You don't want to make any changes to this util class/package, but I don't know what's included in that from what you've posted in your question. Also, there's two identical `Mapper` interfaces shown above.
Comment: What *util class* are you referring to?
Comment: It's an internal util package
public static  Collector, ImmutableList.Builder, List> toList() {
        return Collector.of(ImmutableList.Builder::new,
                (builder, optional) -> {
                    optional.ifPresent(value -> builder.add(value));
                },
                (left, right) -> {
                    left.addAll(right.build());
                    return left;
                },
                ImmutableList.Builder::build);
    }
Comment: Okay, let's assume we have just one method in this util class, the toList method which I just shared. And I want to refactor the code to look like the the second interface `Mapper`. Sorry, I edited the question to reflect what I want the `Mapper` interface to look like.
Comment: The second interface in the question is identical to the first interface.
Comment: Edited that. Sorry about that.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/209022/discussion-between-tanvi-and-jacob-g).
Comment: @Holger, this list is collecting the result from a number of classes which can be returning nulls.
Answer: Collect a stream of Optionals to a list containing only the present values:
List<Optional<String>> someStrings = ...;

List<String> allPresentStrings = someStrings.stream()
    .flatMap(Optional::stream)
    .collect(Collectors.toList());

Answer: Since unable to understand your issue properly, it would be better if you will post your util class as well mean while see my go for this:
  private List<Message> mapToFeature() {
       return mappers.stream()
                .map(mapper -> mapper.createFeature())
                .flatMap(List::stream)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Optionals.toList());
}

Answer: Stream<Optional<T>> present = listOfOptionals.stream().filter(Optional::isPresent);

Stream<T> asTs = present.map(Optional::get);
// this is safe, because all remaining are present,

//convert Streams to Lists as usual with collect.
List<T> listTs = asTs.collect(Collectors.toList());

Comment: what's a concise way to get the first Optional value, or Optional.empty()
if no value is found?
Comment: filter(Optional::isPresent).first()   You'll have to unwrap the outer optional that first() wraps the result in.
Comment: `You'll have to unwrap ...` - yup, and that's no longer concise...


HSQLDB with Postgresql: type not found or user lacks privilege: BIGSERIAL

Question: I'm building Spring+Hibernate Java Application. I wanted to add some integration tests, done in in-memory database.
So, my normal database is Postgresql, and I populate it using .sql scripts run with flyway plugin. ID fields are set to BIGSERIAL. I wanted to use in-memory database, to resemble my original database, and then try to test some classes with it. I managed to configure preety much everything(I hope so), but when I run the test class itself I get error with CREATE TABLE scripts:
Caused by: org.hsqldb.HsqlException: type not found or user lacks privilege: BIGSERIAL
I found out that I should configure HSQLDB, to enable Postgresql compability.
Use SET DATABASE SQL SYNTAX PGS TRUE or the equivalent URL property sql.syntax_pgs=true to enable the PostgreSQL's non-standard features.
I use persistence.xml to define normal and test persistence unit. This is fragment responsible for defining test persistence unit:
<code><persistence-unit name="testJPA">
        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:butterfly;sql.syntax_pgs=true"/>
            <property name="hibernate.hbm2ddl.auto" value="create"/>
        </properties>
    </persistence-unit>
</code>
Then I use configuration class for tests:
<code>@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"core.utilities"} )
@EnableTransactionManagement
public class TestsInitializer {
    @Bean
    public LocalEntityManagerFactoryBean entityManagerFactory() {
        LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
        factoryBean.setPersistenceUnitName("testJPA");
        return factoryBean;
    }
}
</code>
And in testclass itself:
<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestsInitializer.class }/*, loader = AnnotationConfigContextLoader.class*/)
@Transactional
public class GenreBATest {
    @Autowired
    private GenreBA genreBA;

    @Test
    public void testFindAllAccounts() {
        //whatever
    }

}
</code>
I added the required property at the end of URL, found examples of this exact property across the internet, but it does not resolve my problem.
I'm still getting: Message    : type not found or user lacks privilege: BIGSERIAL
What am I doing wrong?
Answer: Ok, I found out that scripts were run by flyway ignoring all possible syntax commands from persistence.xml. And flyway run with HSQLDB because I used @EnableAutoConfiguration in test configuration class without excludes :) I learned through hard way that Spring Boot already configures Hibernate to create schema based on entities for an in-memory database. So I don't need to use database scripts at all, and they were run by accident.


ErrorCode: 'AuthorizationPermissionMismatch'

Question: I have used service principal in Authentication type while creating Linked services.
but when i try to create a dataset in ADF (i am using adls) i am not able to see my file on container i am getting an error.
ADLS Gen2 failed for forbidden: Storage operation '' on container 'raw-container' get failed with 'Operation returned an invalid status code 'Forbidden''. Possible root causes: (1). It's possible because the service principal or managed identity don't have enough permission to access the data. (2). Please check storage network setting whether public network access is disabled. If disabled, use Managed Virtual Network IR and create Private Endpoint to access. https://docs.microsoft.com/en-us/azure/data-factory/managed-virtual-network-private-endpoint. https://docs.microsoft.com/en-us/azure/data-factory/tutorial-copy-data-portal-private (3). It's possible because some IP address ranges of Azure Data Factory are not allowed by your Azure Storage firewall settings. Azure Data Factory IP ranges please refer https://docs.microsoft.com/en-us/azure/data-factory/azure-integration-runtime-ip-addresses. If you allow trusted Microsoft services to access this storage account option in firewall, you must use https://docs.microsoft.com/en-us/azure/data-factory/connector-azure-blob-storage?tabs=data-factory#managed-identity. For more information on Azure Storage firewalls settings, see https://docs.microsoft.com/en-us/azure/storage/common/storage-network-security?tabs=azure-portal.. Account: 'storage1998acc'. FileSystem: 'raw-container'. ErrorCode: 'AuthorizationPermissionMismatch'. Message: 'This request is not authorized to perform this operation using this permission.'. RequestId: '04dc03d9-a01f-009f-1c85-6c9ead000000'. TimeStamp: 'Tue, 11 Apr 2023 14:52:57 GMT'.. Operation returned an invalid status code 'Forbidden' Activity ID: 500eff90-9056-4084-a7cb-428c38af0523

can you please help me i have checked access on IAM , public network access is also enabled
Comment: can you please share the details on how exactly are you connecting using linked service (share screenshot)?
Answer: I reproduce the same in my environment. I got the same error.

To resolve this issue. You need to enable and allow all networks in the storage account and also grant the Storage blob contributor role to the storage account.
If you already have enough permission still you getting the same error. Try to use a different authentication method. If you are using a service principal to authenticate with your storage account, Try to use a managed identity or Account key or SAS. This will eliminate your issues with the permissions. In my scenario, I am using the Account key as the Authentication type.


Using reactRouter, how send an actual 404 status code on not found pages?

Question: We have a handler for all non-specified routes:
<code><ReactRouter.Route path="*" component={Handle404} />
</code>
But this returns a 200. How can we return a 404 status code?
Comment: Are you using server side rendering?? If yes then [this](https://github.com/ReactTraining/react-router/blob/master/docs/guides/ServerRendering.md) might be helpful.
Answer: We cannot send status code from client-side. For SPAs, when browser requests for page, it just downloads the javascript files and pages are rendered on browser side. Routing is handled purely on client-side. Even when we request server for 404 page, the request to download the page content is successful so it will be status 200 only. Eventhough actual page content is "Page not found".
If you need to send specific case you might want to hadle it at server-side.
However,  you can always create custom pageNotFound page.
Answer: To send a status code of 404 to clients, you need to use a server side language such as node.js with express
React.js on the other hand is a front-end library, it is not a server side language, that's why it cannot do what you asked.


Second order elliptic equation with nonlinearity depending on the gradient

Question: Let us consider the problem
$$-\Delta u =f(x,u,\nabla u)\text{ in }\Omega$$
$$u=0 \text{ on }\partial\Omega,$$
where $\Omega\subset \mathbb{R}^n$ is a smooth and bounded domain. I have seen at many places, where it is written that since the nonlinearity depends on the gradient therefore it is not variational. I understand that it is not variational because we cannot find a functional of which critical points are the solutions of the given problem but I am not able to justify this statement.
Comment: How do you define variational? It is variational in the sense: find $u\in H_0^1(\Omega)$ such that $\int_\Omega \nabla u \cdot \nabla v - f(u,\nabla u)\,\mathrm{d}x = 0$ for all $v \in H_0^1(\Omega)$.
Comment: @grew by saying that problem is variational I mean that there exists a functional J on $H_0^1(\Omega)$ such that critical point of J are the solution to given problem. The fact is that no such functional exists, and I need the proof of this.
Comment: What I can offer is a suggestion how to proof that $v \mapsto \int_\Omega \nabla u \cdot \nabla v - f(u, \nabla u) \, v \, \mathrm{d}x$ is not the derivative of any $J$, under some assumptions on $f$.
Comment: @gerw Thanks.  How to prove that the above map is not the derivative for any J. $f$ can be as regular as we want.
Answer: Here is a suggestion for a proof. Some details are missing, but I am confident that these can be filled.
Let us assume that there is a functional $J : H_0^1(\Omega) \to \mathbb{R}$, such that $J$ is Fréchet-differentiable at $u \in H_0^1(\Omega)$ with
$$J'(u)\,v = \int_\Omega \nabla u \cdot \nabla v - f(u,\nabla u)\,v\,\mathrm{d}x$$
for all $v \in H_0^1(\Omega)$.
If $f$ is regular enough, we might be able to show that $J'$ is also Fréchet-differentiable with
$$J''(u)(v,w) = \int_\Omega \nabla w \cdot \nabla v - \partial_1 f(u,\nabla u) \, v \, w  - \partial_2 f(u,\nabla u) \, v \, \nabla w \, \mathrm{d}x$$
for $v,w \in H_0^1(\Omega)$. Here, $\partial_i f$ is the partial derivative of $f$ w.r.t. argument $i$.
Hence, $J$ is twice Fréchet-differentiable, which implies that the second derivative is symmetric w.r.t. $v$ and $w$. But, in general, the last term might not be symmetric (try integration by parts).


Finding joint sufficient statistics

Question: I'm trying to find two statistics $T_1$, $T_2$ such that $(T_1, T_2)$ is jointly sufficient for $(\lambda, \theta)$ for a random sample $X_1, \dots, X_n$ from a two parameter exponential distribution.
$f(x) = \begin{cases}
\lambda e^{-\lambda (x-\theta)}, & \theta < x < \infty, \\
0, & \text{elsewhere}.
\end{cases}$
Thanks.
Answer: First note that
$$
f(x_1 ,x_2 , \ldots ,x_n |\lambda ,\theta ) = \lambda ^n e^{\lambda \theta n} \exp \bigg( - \lambda \sum\limits_{i = 1 }^n {X_i } \bigg) \prod\limits_{i = 1}^n {{\mathbf 1}(x_i  > \theta )},
$$
where $\mathbf 1$ denotes the indicator function. Then note that
$$
\prod\limits_{i = 1}^n {{\mathbf 1}(x_i  > \theta )} = {\mathbf 1}(\min \lbrace x_1 , \ldots ,x_n \rbrace  > \theta ),
$$
and apply Theorem 2 given here.
Comment: BTW your answer and comments helped me a lot to think about the problem rather than giving the answers straight. Thanks.
Comment: Here we need to factorize $f(x_1 ,x_2 , \ldots ,x_n |\lambda ,\theta ) = u(x_1,x_2,\ldots,x_n) v(r_{1,\ldots,k}(x_1,x_2,\ldots,x_n | \lambda,\theta)$ right ? but I don't see a function $u(x_1,x_2,\ldots,x_n)$. Isn't $\prod\limits_{i = 1}^n {{\mathbf 1}(x_i  > \theta )} = {\mathbf 1}(\min \lbrace x_1 , \ldots ,x_n \rbrace  > \theta )$ dependent on $\theta$ ?
Comment: You can take $u(x_1,\ldots,x_n)=1$ (it is nonnegative and does not depend on the parameters). As for the second question, consider the example given on p. 3 in that link (Uniform population).
Comment: Also, note the last sentence in Theorem 2.
Comment: Further, see the examples in http://en.wikipedia.org/wiki/Sufficient_statistic, in particular the example "Uniform distribution (with two parameters)".
Comment: I kind of see that $T_1 = \sum\limits_{i = 1 }^n {X_i}$ and $T_2 = min\{x_1,\ldots,x_n\}$ are jointly sufficient (please tell me if I'm wrong) but I'm trying to reason it why. I feel like I follow the theorem and exmaples and arrive at the answer. Like always I take the joint pdf and try to separate the function but I don't understand the intuition behind it.
Comment: For the intuition behind this example, see, again, http://math.arizona.edu/~tgk/466/sufficient.pdf (for example).
Answer: by neyman factorization theorem X_bar and X(1) are jointly sufficient stats
Comment: You should include the picture in your post or, better yet, write what it says using MathJax. And please include some words of explanation as well.

Finding joint sufficient statistics


Como redirecionar o usuário (para outra pagina) após sua escolha?

Question: Estou tendo dificuldade de fazer o código abaixo funcionar, preciso que ao ser selecionado uma cidade, este fosse redirecionado para uma determinada página.
Abaixo segue o código que estou tentando usar:
JavaScript:

HTML:

<form id="sistema" name="sistema" method="post" action="">
Estado
    <select id="estado" name="estado"></select>
    Cidade
    <select id="cidade" name="cidade"></select>
</form>

Comment: Alex na minha resposta na outra pergunta não ajudou? Você viu que eu edite ela?
Comment: Tive grande dificuldade. E com este código consegui fácil inserir ou remover as cidades e estados. Não sei onde estou errando.
Comment: Tem dois códigos na resposta é o ultimo, vou postar aqui.
Comment: Com este código aí fiz tudo e deu certinho.. só preciso agora é redirecionar.
Comment: o código lá na resposta faz exatamente isto, rediciona, eu não consigo entender, você não viu a atualização? Tudo bem, segue a resposta com o exemplo de redirecionamento copiado da [outra resposta](http://pt.stackoverflow.com/a/69857/3635). Para testar o código nas respostas clique em **"► Executar trecho de código"**
Answer: Adicione um evento change no seu select da cidade, ai tu consegue saber qual o valor.

<form id="sistema" name="sistema" method="post" action="">
Estado
    <select id="estado" name="estado"></select>
    Cidade
    <select id="cidade" name="cidade"></select>
</form>

Comment: Você realmente está tentando entender o código ou só está copiando e colando?
Comment: Maicon poderia me dar um exemplo com duas cidades abrindo paginas de sites diferentes ?
Comment: @ALEXBROOK Sites diferentes como? Se for mais especifico posso te fazer o exemplo
Comment: Por exemplo: após selecionar a cidade de Divinópolis abre-se a pagina http://redeglobo.com.br/.  Após selecionar a cidade de Belo Horizonte abre-se a pagina: http://google.com.br
Comment: Existe a possibilidade de ser alterado o jeito que é montado o `select`?
Comment: Posso te enviar o arquivo para que possa analisar ? Mas se acessar este link  http://pastebin.com/raw.php?i=Qi2BcFsP   consegue ver como esta estrutura do arquivo.
Comment: @ALEXBROOK Da uma olhada aqui nesse exemplo que eu fiz: http://jsfiddle.net/h890j0r9/1/
Comment: Basicamente eu adiciono a url no `value` do option e depois só redireciono
Comment: coloquei no script e não deu certo ? poderia inserir no script.
Comment: como você colocou?
Comment: Pra entender tu tem que começar pelo "começo" e não pelas soluções prontas
Comment: Vejo que sua dificuldade é na linguagem, não adianta eu te falar como fazer
Comment: https://www.youtube.com/watch?v=t4Y7jd4h-T8
Answer: Como eu postei na outra resposta o exemplo de redirecionamento e expliquei:
Use o evento change, como no exemplo o começo do código deve ficar assim:

window.onload = function() {
    var estados = document.getElementById('estado');
    var cidades = document.getElementById('cidade');

    cidades.onchange = function()
    {
        if (cidades.value !== "") {
            //Basta modificar está linha conforme a necessidade
            window.location = "pagina.asp?estado=" + estados.value + "&cidade=" + cidades.value
        }
    };

    new dgCidadesEstados({
        estado: estados,
        cidade: cidades,
        estadoVal: '<%=Request("estado") %>',
        cidadeVal: '<%=Request("cidade") %>'
    });

    var opts = estados.getElementsByTagName("option");
    var i = 0, j = opts.length, e, remove = [];

    for (; i < j; i++) {
        e = opts[i];
        if (e.value !== "" && e.value !== "MG" && e.value !== "SP") {
            //Pega o elemento que será removido e adiciona ao vetor/array
            remove.push(e);
        }
    }

    i = 0;
    j = remove.length;

    for (; i < j; i++) {
        //Remove todos que são diferentes de Minas Gerais, São Paulo e vazio (este ultimo equivale ao "Selecione um estado")
        estados.removeChild(remove[i]);
    }
};

<form id="sistema" name="sistema" method="post" action="">
Estado
<select id="estado" name="estado"></select>

Cidade
<select id="cidade" name="cidade"></select>
</form>

Para mudar o endereço de destino basta alterar a linha aonde se encontra window.location =