How do I pitch shift a song so that sounds in tune with instruments tuned to 440 Hz?

Question: I have an MP3 file of a specific song where the instruments are not tuned to 440 Hz. When you play along to this song with a 440-Hz-tuned instrument your playing will sound out of tune.
There is a way to get the tuning of the song using the program Sonic Visualizer (Analysis -> Tuning). For my song I got 448 Hz for example.
Now I want to pitch shift this song so that it sounds in tune. I know that for example Audacity should be capable of this, but which function do I have to use with which values, knowing only the two tunings?
Comment: Are you content with slowing the resulting recording down in the process, or must the result be in the same tempo as the original?
Comment: I can't speak to the method for pitch-shifting in Audacity, but I will say I'd rely on something other than software to determine the recorded pitch. 448 Hz certainly isn't impossible, but I'm skeptical. What is the piece in question, and the recording? When a recording uses a pitch other than 440, it's usually to replicate historical conventions, and 90% of the time this means a lower pitch rather than a higher (there are a few exceptions especially in some very diligent recordings of some German sacred music),... ->
Comment: -> ... and 90% of the "low-pitch" recordings use 415 Hz rather than any hyper-historical choice. If you're dealing with a very old recording, it's also possible that the pitch is higher than what intended due to problems with recording or playback. I'd recommend simply looking at the score to see the intended pitches, and then adjusting by ear (either using trial and error with the pitch correction until you "hit" 440, or using a tuner or synthesizer that can be calibrated to try to adjust a generated tone until it seems to match.
Comment: @AndyBonner Recordings are often speeded up or down during mastering, they even used to do this in the days of analog recording.
Comment: @PiedPiper True, maybe I shouldn't say "problems" with recording, though some might certainly argue that a rogue performer, conductor, or producer altering the pitch and tempo merely because it "felt slow" is a problem, especially in the kind of chip-on-the-shoulder world that is proud of either their modern 441 or their 438 that they based on the latest measurements of the Nuremberg organ, combined with historical weather forecasts to best extrapolate the sounding pitch. ;)
Comment: @AndyBonner I was referring to 'pop' recordings rather that 'classical' recordings, there's probably less re-speeding done on 'serious' music.
Answer: Select the bits of your track you're interested in (e.g. with Ctrl+A for the entire track) and apply Effects-> Change Pitch. Just enter the two frequencies under 'Frequency', and it calculates the correct percentages. 'Change Pitch' will preserve the original tempo, as opposed to 'Change Speed'.


Why would someone plot variance normalized by the mean?

Question: I'm reading a scientific paper where they plot the variance of particle intensity normalized by the mean of particle intensity.  I'm a bit confused and don't have an intuition for how this should be helping me.  I'm used to seeing standard deviation and variance, both of which reflect dispersion.
What does plot of variance normalized by the mean give me that plot of variance does not?
Here is an example of the graph I am talking about.  The x-axis represents the length of an RNA molecule resulting in a distribution of particle sizes.  You can just take it as a categorical variable.

edit:
This relation is apparently called the "index of dispersion".
Here they may be looking for "overdispersion" indicate an unexpectedly large grouping or clustering of these particles (which actually what they see under the microscope).
I'm still trying to wrap my head around the intuition though.  I know that for a Poisson distribution the mean = variance (dispersion factor = 1), but that's just me knowing facts, and I don't want to go off thinking of this relation as measuring "how Poissonian" a distribution is.
Comment: this is a statistical forum .. you have to provide the chemistry knowledge (why should the mean and variance of particle intensity be related) or go to another forum
Comment: @seanv507 I don't think the OP is asking for an interpretation of the example plot specifically, but is asking for plots of variance over mean more generally.
Answer: Variance over mean is known as the Index of dispersion.
This can be useful when comparing two random variables with different means, in order to account for larger variance for larges means.
Example: suppose two fields have some sheep, and I hire 2 "counters" to count the sheep in each field. The counters count the sheep 10 times for their field and report the number of sheep counted. If the first counter gets a field with 50 sheep, then for that counter the variability across their counts will be naturally low. On the other hand, for the second counter if their field has 1000 sheep, then the variability of their counting will most definitely be higher than the first counter.
So in this case, we can't just study the variance for the two counters and declare the first counter to be better since he/she had a lower variance. We have to account for the number of sheep in their respective fields. This can be done by weighting the variance by the mean, i.e., index of dispersion.
Comment: Any idea why var/mean and not stddev/mean?
Comment: @Anony-Mousse [Here](https://stats.stackexchange.com/questions/203766/use-cases-for-coefficient-of-variation-vs-index-of-dispersion) is a good discussion between the two.


How do I prove this these inequalities, preferably without calculus?

Question: I'm trying to solve an inequality which stems from this problem:
If x, y, z are positive real numbers and $x^5+y^5+z^5=3$, prove $\frac{x^8}{y^3}+\frac{y^8}{z^3}+\frac{z^8}{x^3} \ge 3$
I thought that solving this directly would require an inequality I'm not familiar with, so I decided to set $y=ax$ and $z=bx$ (note $a>0$, $b>0$), reducing the inequality to be proven to:
$\frac{1}{a^3}+\frac{a^8}{b^3}+b^8≥1+a^5+b^5$ for all $a, b > 0$.
I tried proving it by proving the function $f$ with $f(a)=\frac{1}{a^3}+\frac{a^8}{b^3}+b^8≥1+a^5+b^5$ is always positive for $a>0$ and all $b>0$. I graphed it out, and noticed it only attained a value of zero when $a=1$ and $b=1$ (for values of b between 0 and 10). Afterwards, it seemed to only increase. However, the 11th degree polynomials are simply too much for me to handle.
So, my questions would be:
How do I prove the original inequality?
And how do I prove the inequality I have 'reduced' the original one to?
An answer without calculus and without advanced inequality identities would be preferred, but I would prefer an answer with them than no answer at all.
Comment: I'd recommend using Titu's lemma (a special case of the Cauchy-Schwartz inequality).
Answer: Note that by the rearrangement inequality for triples $(x^3,y^3,z^3)$ and $(x^2,y^2,z^2)$ we can conclude that $$y^3x^2+z^3y^2+x^3z^2 \le x^5+y^5+z^5$$
Now by  Cauchy-Schwarz inequality
$$(\frac{x^8}{y^3}+\frac{y^8}{z^3}+\frac{z^8}{x^3})(y^3x^2+z^3y^2+x^3z^2) \ge (x^5+y^5+z^5)^2 \implies$$ $$\frac{x^8}{y^3}+\frac{y^8}{z^3}+\frac{z^8}{x^3} \ge \frac{(x^5+y^5+z^5)^2}{y^3x^2+z^3y^2+x^3z^2} \ge \frac{(x^5+y^5+z^5)^2}{x^5+y^5+z^5} =x^5+y^5+z^5 = 3$$
Comment: It is "Schwarz" and not "Schwartz" – [Karl Hermann Amandus Schwarz](https://en.wikipedia.org/wiki/Hermann_Schwarz)
Comment: If you're using rearrangement, $\sum_{cyc} \frac{x^8}{y^3}\geqslant \sum_{cyc} x^5$ can be obtained directly...
Comment: Note (I had to think on this for a moment) the rearrangement equality conditions are satisfied only because x, y, z > 0. So raising them all to any power preserves their order (whatever that order be). If they were not constrained positive, the square order might differ from the cube order.
Comment: @oly bit careful about the question!!! Or read it once again it. Question asked for positive reals
Comment: Btw!!! This is straight forward solution with LG which is a calculus approch I see now those who Don't know calculus it's hard for them so , The approach posted above is quiet good but I cannot give full point's though!!!


Compute Pearson correlation avoiding zero values

Question: I have a sparse matrix A(m,n), where n are the variables and m the observations. I want to compute the Pearson correlation among all the n variables.
I have some missing observations, e.g. if A(2,3) is not available it means that I don't have such observation, so if, for example, I need to compute the correlation between column 3 and column 4, I must discard row 2, even if A(2,4) is available. This is how Pearson correlation is normally computed.
In MATLAB, instead, the function corrcoef() consider all the values, including the missing ones (which are considered zeros). Is there a simple way to avoid this? A very similar question is available here Pearson Correlation without using zero element in Matlab but a working solution is provided just for the comparison among two vectors and not for a generic matrix A(m,n) where n > 2.
Answer: Jonas's answer on the question you linked works for you as well if you generalise it:
Col1 = 2;
Col2 = 3;
A=magic(3); A(1,1)=0;
gooddata = A(:,Col1)~=0 & A(:,Col2)~=0;
pearson = corr(A(gooddata,Col1),A(gooddata,Col2));

Thus, looped it would be:
for ii = 1:length(A(1,:))
    for jj = ii:length(A(1,:))
       gooddata = A(:,ii)~=0 & A(:,jj)~=0;
       pearson(ii,jj) = corr(A(gooddata,ii),A(gooddata,jj));
    end
end

Comment: @Eugenio your goals should always be to have functional code first, then figure out where optimize. You can't *a priori* assume that a loop solution is slowest.
Comment: "Premature optimization is the root of all evil" -- Donald Knuth
Comment: I am not sure if I got your answer, I don't need that all elements are non zero, I need to keep the rows where both the values, for the two columns I am considering, are not zero.
If I try your code adding just a zero element to a matrix: a=magic(3); a(1,1)=0; then a(~any(a,1)) gives me an empty matrix
Comment: Thanks but It doesn't provide a solution to the problem: in your example when I compute the correlation between col 2 and 3 I need all three rows but the first one has been deleted because of the zero in A(1,1)
Comment: this works for a single correlation computation, I have to compute the correlations for a big matrix having thousands of columns and I am looking for a simple way to do it without loops
Comment: Simple means loops. You can loop over `Col1` and `Col2`. Besides, since the MATLAB engine overhaul loops are not that slow anymore.
Comment: Ok, I accepted the answer because technically is right, but it just adds loops to a previous existing answer, which is something that any matlab user can do.


Ajax error while uploading or removing file through managed file

Question: I am getting following error while using managed file through my custom form.

"An Ajax HTTP request terminated abnormally."

Also, I updated my jquery version to latest using jquery_update module. Still no any benefit.
Any idea on how to solve it?

EDIT:
Code
  $form['path_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
    '#default_value' => $current_image,
    '#upload_location' => 'public://subpage_banner/',
  );

Comment: Post the code for your managed file field please.
Comment: Yes code has been posted.
Comment: Code looks fine.  Are you working on localhost or via a hosting provider?  Is it possible that Fast CGI is being used?  See this article http://montenasoft.com/en/blog/500-internal-server-error-while-uploading-files-bigger-then-100kb-modfcgid-problem
Comment: @littledynamo I am on localhost. Ubuntu Server 11.04
Answer: MaxRequestLen sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.
See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:
<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

Or try switching from FastCGI to mod_php or php-fpm (if you're using FastCGI).
Answer: Anyone having lots of AJAX issues might want to try disabling the jquery_update module. It is because some modules and library scripts work with different versions of jQuery.
Answer: One reason for this error may be permissions. Please check that the upload AJAX menu item has the right access argument $items['file/ajax']['access arguments'] and no module else hooks and changes its default value.
Answer: It's a jquery_update issue. Check with lower version of jquery.


Verifying that Webforms Hooks are firing

Question: I'm new to Drupal but relatively proficient in PHP.  I'm attempting to use the Webform module as a ticketing system.  What I'd like to do is hook into the webform submission insert (hook_webform_submission_insert) and create an object of type 'support_ticket' each time a webform is saved.  For now, I'm just trying to make sure that I'm hooking in properly, and it looks like I'm not.  I'm using the code below in a template.php file of a custom module:
<code>function pvfk_webform_submission_insert($node, $submission){
   drupal_set_message("IN Insert");

   //Declare a new StdObj

   $new_node = new StdObj();
   //Set the type
   $new_node->type='support_ticket';

   //Set the Title
   $new_node->title='NEW TICKET';

   //Set the body
   $new_node->body = 'TICKET BODY';

   //Set other content fields
   // $new_node->field_name[0]['value'];

   //Finally use functions to save, submit, and insert the new_node
   $new_node = node_save($new_node);
   node_submit($new_node);
   content_insert($new_node);
</code>
I've cleared my cache and created new webforms - but neither a new piece of content is created nor do I see the message.  Am I missing something here?
Answer: Hook functions are run only when they are put inside a .module file.
So you should move your function into your pvfk.module file. Then visit your /admin/build/modules list so Drupal will refresh hooks list.
Answer: Moved it to the module as suggested by ermannob.  Still wasn't firing, finally realized the prefix should have been pfvk and not pvfk...lesson learned.


Minimal MIDI digital piano

Question: I'd like to buy my first keyboard instrument. I want a piano touch with 88 keys and MIDI output and otherwise extremely minimal features. I'm hoping this will allow me to experiment with different sounds over the lifetime of the keyboard rather than being locked in with the sounds that are normally built in to a digital piano. By moving the sound production out of the keyboard, I expect it would also be lighter and easier to transport (several smaller components instead of one large keyboard).
Is this a bad idea?
Is MIDI limited in the sound quality it can produce in any way? (I.e. can I produce completely natural sounding music with it?)
Comment: What's your budget?
Comment: Just want to ask suggest that I thought instrument recommendation questions were not permitted on Music SE?
Comment: That's why I didn't ask for a suggestion for a specific instrument. I want to learn about the process whereby I would find such a set of components.
Comment: I'd like to ignore the question of budget until I know what the possibilities are.
Answer: First, you need to understand what "MIDI" is. The Musical Instrument Digital Interface has nothing to do with sound or sound quality. To say that an instrument is a "MIDI" instrument says nothing at all about what it sounds like. MIDI only refers to the method by which you can connect that instrument to other instruments and computers to move data around in a music studio or performing stage situation.
If you want to find a good digital piano, you need to visit a music store with a wide selection, and you need to sit down and play several instruments and listen to them. It would also be a very good idea to take piano lessons and ask your piano teacher to recommend an electronic instrument suitable for you to purchase.
There is no substitute for seeing, playing, and hearing different keyboard instruments in a store. You can do all the research you want online, and ask all the questions you want in forums or sites like this, but you will not really learn anything useful if you do not also spend considerable time physically handling these instruments yourself.
Comment: You are asking a lot of different questions here, @David, but the answer to these is "yes". MIDI can capture how hard you press the key (velocity), how fast you release the key (release velocity), how hard you press down on the key after it is depressed (aftertouch), and there are foot pedals with partial damping -- but only if the particular keyboard or instrument supports these features.
Comment: I know a little about MIDI and how it works, the basics. I'm specifically wondering if using MIDI limits the quality of the music I can produce if all of my music is generated exclusively from a MIDI source. E.g. can MIDI capture how hard I press a key? Can it capture partial undamping with the foot pedal? (Forgive me, my vocabulary here is lacking.) (Do they make foot pedals that do that for digital pianos?)
Comment: Considering you marked my other, significantly different question a duplicate without any explanation, I wonder if your goal is to help enlighten other users or obstruct them? Please take a little more time to consider your actions. If you think that I am mistaken, please give me the benefit of trying to show me why my answer is a duplicate before marking it so.
Comment: For one thing, your other question had virtually the same title. Secondly, it asked substantially the same question. Thirdly, I'm one of the senior members here and I have years of experience with the kinds of questions we answer here and how they work. Fourthly, I took a considerable amount of time to provide you with one good answer, so I am  indeed working to help you, not to obstruct you. Finally, you are completely new here, so you need to observe and learn how things work here rather than being so critical of those who have experience.
Comment: David, on this site we do not usually entertain detailed questions asking for recommendations for purchasing musical instruments. This site, as its title suggests, is for questions about learning to play instruments, not so much about selecting and purchasing them. If you need extensive recommendations for digital musical instruments, computers, and sound reinforcement, you should look to other sites, not this one.
Answer: Following on from Wheat's excellent response, there are lots of considerations - you probably won't need an 88 note, a 76 will be lighter (one thought), and cheaper. Most are midi these days. Do you want a home piano, or one with a stand for stage work? If you haven't played before, you will not be as fussy as maybe you need to be as far as action is concerned -a lot of pianos out there have a quasi piano feel, but they're not that good. You'll pay lots for a realistic action.
Having  several lesson  with  a good  teacher will  definitely  be more  help than reading any answers here! You'll be able to try out a piano or two, and will be surprised at how different each is. I'd advocate deciding on one which will do for now, and buying a pre-owned one. That way, when you realise you need to upgrade (and you will...) you'll not lose too much. Keyboards/pianos are infamous for dropping in value in no time at all.
Comment: Saying that I'm looking for my first keyboard was misleading, sorry. I've played pianos and taken lessons, and my family had an old piano and a couple of cheap keyboards when I was growing up.
Comment: I just realized I'm being really terse. I got here from stackoverflow so I'm in super technical, very specific, get to the point before you finish the first 3 words mode. Sorry. :)
Comment: So the question's a bit of a red ferret, then.
Comment: I think I could have been more clear about my experience with pianos and keyboards in the past, but I still feel like I'm asking some pretty specific questions here.
Answer: MIDI music can be very 'natural' sounding depending very much on the sample library or synth you use to create the sound.  The two basic types of software instruments are software synthesizer and recorded samples of actual instruments.
There are lots of ways to edit MIDI tracks to make them sound more natural that depend on what real instrument you are emulating.  For example, if you are emulating strings you may want to edit notes to make them overlap slightly and/or change the porto time.
One requirement I would definitely add to your choice of MIDI keyboards is 'touch sensitivity.'  Touch sensitivity maps to 'velocity' and is essential for natural sounding music.

Minimal MIDI digital piano


React: loop through array response does not work

Question: I run an axios get request to an Express server to get some dummy data:
  customers = [
    { id: 1, firstName: "John" },
    { id: 2, firstName: "Brad" },
    { id: 3, firstName: "Mary" }
  ];

the data that is returned is determined by a user input: if the user enters "Brad", the result being returned will be { id: 2, firstName: "Brad" }.
For some reason, when I loop through the data returned, nothing works. Looking into the React Chrome Extension, the State returned is as follows:
{
  "firstName": "Brad",
  "id": 0,
  "customers": [],
  "res": []
}

Because I am learning React, I will post the whole component for you to see, perhaps the problem is something I don't see yet as a newbie:
    class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      firstName: "",
      id: 0,
      customers: []
    };

      this.getName = this.getName.bind(this);

  }

     onChange = e => {
      e.preventDefault();
      this.setState({ firstName: e.target.value });
     };

    getName = e => {
     e.preventDefault();
     axios
      .get("/api/customers", {
        params: {
          firstName: this.state.firstName
        }
      })
      .then(res => {
        console.log(res);
        this.setState({ res: this.state.customers });
      });
     };

     componentDidMount() {}

     render() {

     //if (!this.state.customers.length) return "Data not available yet";
      return (

Customers

Search for a customer

Get the Customer's Name Here

            <form onSubmit={this.getName}>

                <input
                  type="text"
                  className="form-control form-control-lg"
                  placeholder="customer name ..."
                  name="firstName"
                  value={this.state.firstName}
                  onChange={this.onChange}
                />

              <button
                className="btn btn-primary btn-lg-block mb-5"
                type="submit"
              >
                Get Customer
              </button>
            </form>

This is where I loop throuhg the data:
        {this.state.customers.map(item => (

{item.firstName}

        ))}

    );
  }
}

And here is the Express route I'm calling:
app.get("/api/customers", (req, res) => {
  let { firstName } = req.query;
  const customers = [
    { id: 1, firstName: "John" },
    { id: 2, firstName: "Brad" },
    { id: 3, firstName: "Mary" }
  ];
  console.log("the customer's name is " + firstName);
  var str = customers.filter(x => x.firstName == firstName);
  res.json(str);

});

So What I want is to display the data in a  element below the input bar.
Answer: Try :
this.setState({ customers : res });

instead of :
this.setState({ res: this.state.customers });

Also, try to use React Hooks in order to refactor your code.
Comment: Thanks for the hint David. Your solution didn't work for me but it pointed me into the right direction. I changed the line into: this.setState({ customers: res.data }); and it works. I am accepting your answer though. For React hooks, I'm not there yet.


$\int \frac{1}{\cos x}dx$ by half angle substitution

Question: $$\int \frac{1}{\cos x}dx$$
By half angle I did:
$t = \tan\frac{x}{2}$
$$\cos x = 1-2\sin^2\frac{x}{2} = 1-2\frac{\sin^2\frac{x}{2}}{\cos^2\frac{x}{2}}\cos^2\frac{x}{2} = 1-2t^2\frac{1}{\sec^2\frac{x}{2}} =1 - \frac{1-2t^2}{t^2+1} = \frac{1-t^2}{t^2+1}$$
$$dt = \frac{1}{2}\sec^2\frac{x}{2}\implies dx = \frac{2}{1+t^2}dt$$
then $$\int\frac{1}{\cos x} = \int\frac{t^2+1}{1-t^2}\frac{2}{1+t^2}dt = \int\frac{2t^2+2}{1-(t^2)^2}dt$$
I know how to separate it in two integrals:
$$\int\frac{2t^2}{1-(t^2)^2}dt + \int \frac{2}{1-(t^2)^2}dt$$
The first one I know how to integrate, but not the last one. Could somebody help me? Also, Am I doing everything alrigt?
os: I know this integral is easier by $u$ substitution...
Comment: Also why not cancel the two copies of $1+t^2$ right after you cnange from integrating $1/\cos x$?
Comment: $\cos x=\frac{1-t^2}{1+t^2}$, not $\frac{1-t}{1+t^2}$.
Comment: I have not checked your work, but have you ever seen the inverse hyperbolic trigonometric identities when it comes to derivatives? Depending upon the limits of integration, the second integral looks a lot like $\tanh^{-1}\left(\theta\right)$ or $\coth^{-1}\left(\theta\right)$ ... http://math.info/Calculus/Derivatives_Hyp_InvHyp/
Comment: @ThomasAndrews sorry, I knew it but typed wrong. Aready corrected.
Comment: @bd1251252 I cannot use anything related to hyperbolic trig functions yet
Comment: Yes, $t^2+1=1+t^2$, because addition is commutative, so you can cancel. :)
Answer: If you cancel correctly, you end up with:
$$\int\frac{2\,dt}{1-t^2}$$
But: $$\frac{2}{1-t^2}=\frac{1}{1-t} + \frac{1}{1+t}$$
Comment: $\frac{1+\tan u}{1-\tan u} =\frac{\cos u + \sin u}{\cos u-\sin u}$. Multipy numerator and denominator by $\cos u+\sin u$ to get $$\frac{\cos^2 u + 2\cos u\sin u + \sin^2 u}{\cos^2 u -\sin^2 u}=\frac{1+\sin(2u)}{\cos(2u)}=\sec(2u)+\tan(2u)$$
Comment: I ended up with $\ln|\frac{1+tan x/2}{1-tan x/2}|$ but the answer should be $\ln|sec x + tan x|$
Comment: It's true, the half-angle approach gives a different-seeming result. Are they actually different? Replace $\sec x +\tan x$ with their half-angle values and compute through to maybe see they are the same (up to a constant.)
Comment: @GuerlandoOCs, is  $\frac{1+\tan x/2}{1 - \tan x/2} = \sec x + \tan x$  not true?
Comment: That is a general problem with using the half-angle formula, you end up with all those half-angles. :) If there is simpler substitution, you often get a very different-looking answer.


exposing multiple databases in django admin

Question: My use case requires me to expose multiple databases in the admin site of my django project. Did that following this link: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface
Here's the code used:
class MultiDBModelAdmin(admin.ModelAdmin):
# A handy constant for the name of the alternate database.
using = 'other'

def save_model(self, request, obj, form, change):
    # Tell Django to save objects to the 'other' database.
    obj.save(using=self.using)

def delete_model(self, request, obj):
    # Tell Django to delete objects from the 'other' database
    obj.delete(using=self.using)

def get_queryset(self, request):
    # Tell Django to look for objects on the 'other' database.
    return super(MultiDBModelAdmin, self).get_queryset(request).using(self.using)

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    # Tell Django to populate ForeignKey widgets using a query
    # on the 'other' database.
    return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)

def formfield_for_manytomany(self, db_field, request, **kwargs):
    # Tell Django to populate ManyToMany widgets using a query
    # on the 'other' database.
    return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs)

And then:
admin.site.register(Author, MultiDBModelAdmin)
admin.site.register(Publisher, PublisherAdmin)

othersite = admin.AdminSite('othersite')
othersite.register(Publisher, MultiDBModelAdmin)

The example's documentation states: This example sets up two admin sites. On the first site, the Author and Publisher objects are exposed; Publisher objects have an tabular inline showing books published by that publisher. The second site exposes just publishers, without the inlines.
What I don't seem to find out anywhere is: how do I access the other 'site'? What URL has to be used to view the tables exposed in the other 'site'? Should be something straightforward, but I cannot seem to find it anywhere.
Answer: You need to add a url pattern for your admin site, similar to how you enable the regular site:
# urls.py
from django.conf.urls import url
from django.contrib import admin
from myapp.admin import othersite

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^otheradmin/', othersite.urls),
]

You then access the other admin at whatever url you used. In this case, /otheradmin/.
This syntax is for Django 1.10+. On earlier versions of Django, you use include(othersite.urls) instead of othersite.urls.


A linear operator $Tx=(x_1,x_1+x_2,x_1+x_3,\dots)$ between $c_0$ and $c$ and its norm

Question:
The operator $T$ is for $x=(x_n)_{n=1}^\infty \in c_0$ given by $$ Tx=(x_1,x_1+x_2,x_1+x_3,\dots).$$
  Show that $T$ is a bounded linear operator between $c_0$ and $c$ and calculate $||T||$.
Is $T$ injective, surjective?

First I would like you to have a look at my answer to the second question.
It is indeed injective as for each two distinct $x$ and $y$ the images are also distinct:
if $x_1 \ne y_1$ (possibly some other coordinates are different too), then $Tx$ surely differs from $Ty$ in the first coordinate and if $x_1=y_1$ and there are differences between the two in some elements $n \ge2$, than $n$th coordinates of $Tx$ and $Ty$ are not equal.
As for surjectivity, I reckon $\lim_{n \rightarrow \infty} (x_1+x_n)=x_1+\lim_{n \rightarrow \infty}x_n=x_1$ and since $x_1$ is an arbitrary number then every number can be obtained as a limit but I feel I'm missing something here.
As far as $||T||$ goes, firstly let's take $ x=(1,1,0,0,0,\dots) \in c_0, ||x||=1$ and the definition $||T||=\sup_{||x||=1}||Tx||$ yields $||T|| \ge 2$. On the other hand, $||Tx||=\sup_{n\ge2}\{|x_1|,|x_1+x_n|\} \le 2\sup_n|x_n|=2||x||$, hence $||T|| \le 2$. All in all, $||T||=2$.
I'd appreciate any remarks on the correctness of my solution.
Comment: @Theta No, it is not surjective. The image contains only sequences with the first element being equal to the limit. For example, $(1,0,0,0,...)$ is not in the form $Tx$ for some $x\in c_0$.
Comment: @TZakrevskiy $c$ are convergent sequences and $c_0$ are sequences convergent to $0$.
Comment: What are $c$ and $c_0$?
Comment: This is correct.
Comment: @Aweygan Do you also think that $T$ is surjective? Does it imply that every sequence convergent to some $x_1$ can be represented as $(x_1,x_1+x_2,x_1+x_3,\dots)$?
Comment: @A.Γ. Oh, you have a point, thank you for the brief explanation.
Answer:
For injectivity: what you did seems correct. Maybe this can be shortened a little bit, using linearity of $T$. Indeed, if $Tx=0$, then $x_1=0$ and for $n\geqslant 2$, $0=x_1+x_n=x_n$ hence $x=0$.
For surjectivity: as pointed out by A.Γ., the range of $T$ is contained in the set of convergent sequences whose limit is equal to the first term, hence it is not the whole $c$. It is sufficient in order to prove that $T$ is not surjective, but finding the range could be also interesting.
What you did for the norm is correct.


Chi-square and normal distribution

Question: Let $S_n^2\sim\mathcal{\chi_n}^2$ and let $\hat\Sigma_n$ be an estimator of $\Sigma\in\mathbb{R^p}$ such that $(n-1)\hat{\Sigma}_n\sim W(\Sigma,n-1)$ (Wishart distribution) for some $n>p $.
a)Show that $\mathcal{L}(\sqrt nlog(\frac{S_n^2}{n}))$ onverges weakly to $\mathcal{N}(0,2)$.
I know that $$S_n^2=X_1^2+...+X_n^2$$ where $X_i\sim \mathcal{N}(0,1)$. After that I don´t what argument apply to proof a).
I don´t know any result to analyze the convergence of $\sqrt{n}log(\frac{S_n}{n})$ Maybe I can use the central limit theorem but I don´t know how to apply in this case.
Comment: The information about $\hat{\Sigma}_n$ and $\Sigma$ seems redundant and disturbing
Answer: If you apply the Central Limit Theorem to
$$S_n^2=X_1^2+...+X_n^2$$
you get that
$$\frac{1}{\sqrt{n}}(X_1^2+...+X_n^2-n)\stackrel{\text{dist}}{\longrightarrow}\mathcal{N}(0,2)$$
since $\mathbb{E}[X_1^4]=2$. Meaning that $S_n^2/n$ is asymptotically $\mathcal{N}(1,2/n)$.
Now if you apply the continuous mapping theorem, $\log\{S_n^2/n\}$ is asymptotically $\log\{\mathcal{N}(1,2/n)\}$, which is equivalent to a $$\mathcal{N}\left(\log\{1\},\left[\frac{d\log(\mu)}{d\mu}\right]_{\mu=1}^2 2/n\right)$$
by a Taylor expansion.

Chi-square and normal distribution


401 Error Document Within Protected Directory

Question: I have an error document (symlink actually) in a protected directory. I want to use my custom error page but the 401 error isn't working due to it being a private directory. How can I solve this?
Here's my .htaccess right now
<code>ErrorDocument 401 /error.php
AuthType Basic
AuthName "restricted"
AuthUserFile /home1/user/public_html/.htpasswd
require valid-user
</code>
Answer: I fixed this by adding this to my .htaccess
SetEnvIf Request_URI "^/error.php$" allow_all
Order allow,deny
Allow from env=allow_all
Satisfy any


Monitor a HTTPS connection with URL class (Java)

Question: I would like to monitor a simple url. But when its a https server I get a handshake exception. Its possible to verify state of a https url the way browser use to connect? (without having a local certificate). I don't know how browsers do to get content from a https url but I would like to make it the same way. Without need to store a specific certificate for each server. The https being monitored should be anyone.
try {
    URL u = new URL(row.getUrl());
    String protocol = u.getProtocol();
    if(protocol.equals("https")) {
        HttpsURLConnection hc = (HttpsURLConnection)u.openConnection();
        System.out.println("Response Code: " + hc.getResponseCode());
        hc.disconnect();
    }
    if(protocol.equals("http")) {
    u.openConnection();
    u.getContent();
    }
    System.out.println("url is up.");
} catch (Exception e) {
    (...)
}

Comment: Is the server's certificate trusted? I.e. signed by a CA and not expired? If not then you may have to do some cajoling to get it to work right. Accepting self-signed certificates may require additional work.
Comment: no, it should be any host you like to test availability.
Answer: If you really don't care about the validity of the server's certificate, then you want to set an SSLContext that has a TrustManager that doesn't check anything. Then you need to use that to set the default SSLSocketFactory into the HttpsURLConnection, so that the trust manager is used when you use the URL. Here's an example:
TrustManager[] trustEverything = new TrustManager[] {
    new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { return null; }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }
    }
};

SSLContext sslctx = SSLContext.getInstance("SSL");
sslctx.init(null, trustEverything, null);

HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());

A full example using this technique can be found here.
As @erickson points out, this means that you can't tell if you're really talking to the server you're concerned about. An even better solution is to update your Trust store to include the self-signed certificate of the server you're talking to, instead of ignoring all checks.
Comment: I came up to some struggling but found this from your sample: http://www.java-samples.com/showtutorial.php?tutorialid=211

Now it working. Thanks.
Comment: Good solution, but just remember: you're only checking that "some" server is up; you've lost server authentication so you don't know for sure whether it's yours or a spoof.
Comment: Thanks @Ruben Trancoso, glad I could point you in the right direction. I'll add that link to my answer.
Comment: Excellent point, @erickson. We're throwing away an important feature of SSL/TLS by doing this... I'll add something to my answer to address that.


Brain teaser: 2 men can catch 2 fish in 2 minutes, at this rate, how many men can catch 500 fish in 500 minutes?

Question: I found this interview question off of Quora. I'm unfamiliar with rate-related questions when there are 3 dimensions (men, fish, time).
My intuition is:

2 men can catch 2 fish in 2 minutes
then if you multiply the time unit by 250, these 2 men can duplicate this behavior 250 times, which means they can catch 500 fish

So is the answer 2 men can catch 500 fish in 500 minutes?
In general, how do does one solve these rate questions when there are 3 dimensions? I know when there are two dimensions (for example, if catching 2 fishing takes 2 minutes, then how long does it take to catch 500 fish) you basically do cross-multiply as we learned in high school. An explanation of how to solve this type of problems (preferably with examples) would be much appreciated
Comment: Just arithmetic, not even probability, so off-topic here.
Answer: Often, you can reduce dimension of the problem.
Here, introduce an unit of man-minute. '2 men can catch 2 fish in 2 minutes' means, that to catch 2 fishes, you have to allocate 4 man-minutes. So rate is 0,5 fish per man-minute.
To catch 500 fishes you have to allocate 1000 man-minutes. That is 2 men fishing for 500 minutes (or eg. 100 men fishing for 10 minutes).


Transferir arquivos por FTP para Hospedagem Java

Question: Se eu contratar um host para hospedar minha aplicação Java posso transferir arquivos por ftp? para que essa minha aplicação realize a leitura desses arquivos?
Tenho uma aplicação desktop que fica no servidor que gera um arquivo .xml a cada 1 hora e tenho uma aplicação web que lê esses arquivos. Porém como normas de segurança da empresa não posso fazer conexão direta entre o sistema web e o servidor, me falaram que uma forma mais segura de realizar esse processo é passar esses arquivos .xml por ftp para que o sistema web possa lê-los. Isto é possível?
Comment: FTP não seria uma boa escolha para questões de segurança, o ideal seria então SFTP ou melhor ainda se for [SCP](http://stackoverflow.com/a/343723/2766598). Também não entendi a aplicação é Desktop porém roda no servidor, como seria?
Answer: Sim, é possível.
Você deve configurar o serviço de ftp em um servidor.
Do lado do seu cliente Desktop você deve fazer upload do arquivo para o servidor ftp utilizando uma das muitas bibliotecas para isso (e.g., FTPClient da biblioteca Apache Commons Net).
Do lado do servidor você pode, entre outras estratégias, ter processos batch schedulados para ler esses arquivos. O Java EE 7 possuí uma API dedicada para processamento batch, temos também o bom e velho Spring Batch.

PS: Normas da companhia são normas da companhia, porém lembre-se que usar FTP não torna a transferência de arquivos automaticamente segura... Um SFTP bem configurado é uma alternativa interessante a um serviço de upload https, mas de uma maneira ou de outra será necessário controlar aspectos como autenticação / autorização / auditoria, etc. Disponibilidade também é um desafio independentemente do protocolo escolhido (veja as 8 falácias da computação distribuída).
De uma maneira ou de outra transferir arquivos de maneira segura, barata e confiável não é fácil... Não é a toa que em pleno século XXI ainda temos VANs e serviços de EDI sendo cobrados por kilobyte.
Comment: Muito obrigado, vou estudar essas bibliotecas e com o tempo ir aprimorando esse sistema


Como acessar uma variável global do application.json em .NET Core c#

Question: Sou novo com programação e estou tendo dificuldade para acessar um Token que está como variável no arquivo application.json. É um aplicativo de console, o objetivo é apenas utilizar o token da variável global e utilizar como usuário para fazer uma autenticação em um método GET de uma API. Não sei que tipos de prints devo por aqui, vou por algumas abaixo:
Application.json
{
  "Config": {
    "Environment": "Development",
    "ApiTokenSecretQA": "meuToken",
    "UrlApi": "https://api.mundipagg.com/core/v1"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

Program.cs
namespace Gateway_Pagamento
{
    class Program
    {
        static void Main(string[] args)
        {
            GetOrder.GetOrderId();

            //CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                });

Metodo Get Order - tentei fazer para acessar a API
public class GetOrder
    {
        [HttpGet]
        public static void GetOrderId()
        {
            Authenticator auth = new Authenticator();
            Authenticator.Authorization();

            try
            {
                var client = new RestClient("https://api.mundipagg.com/core/v1");
                //var request = new RestRequest(("orders/" + orderId), Method.GET, DataFormat.Json);
                var request = new RestRequest(("orders/"), Method.GET, DataFormat.Json);

                client.Authenticator = new HttpBasicAuthenticator(auth.BasicAuthUserName, auth.BasicAuthPassword);
                var response = client.Get(request);
                client.Execute(request);
                Console.WriteLine(response.Content);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

Comment: e onde precisa acessar isso? no Main, no CreateHost ou num outro método qualquer?
Comment: @RicardoPontual , é em um método GET, chamando a API para consultar e autenticar, vou tentar colar ele acima na pergunta.
Answer: Tem várias formas de se fazer isso. No seu exemplo, ainda não criou nem o Host, então precisa fazer isso manualmente, assim:
public static void Main(string[] args)
{
    // Le o appsettings e criar um objeto IConfiguration
    var config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

    // Lê o valor da chave
    var token = config.GetSection("Config:ApiTokenSecretQA").Value;

    // Passa como parâmetro
    GetOrder.GetOrderId(token);
}

Se estivesse fazendo isso depois de criar o Host, poderia fazer na método Startup também
Agora uma forma mais elegante seria criar uma classe com a estrutura do seu config e ler todo o config para um único objeto dessa classe, assim:
public class Configuracao  // se quiser injetar isso, pode adicionar uma interface
{
   public string Environment { get; set; }
   public string ApiTokenSecretQA { get; set; }
   public string UrlApi { get; set; }
}

// No Main
var minhaConfiguracao = config
    .GetSection("Config")
    .Get<Configuracao>();

GetOrder.GetOrderId(minhaConfiguracao);

public static void GetOrderId(Configuracao config)
    {
        Authenticator auth = new Authenticator();
        Authenticator.Authorization();

        try
        {
            var client = new RestClient(config.UrlApi);
            ....

Comment: Funcionou!! E obrigado pela dica, vou tentar implementar aqui!


JPA all referenced relations are retrieved (ManyToMany - ManyToOne - OneToMany)

Question: Working on this 'twitter' application where a user can have posts @OneToMany and can have followers @ManyToMany.
While retrieving a user all it's posts and followers get retrieved as well.
This is all correct but it's also retrieving every 'poster' for each post (which is the user itself) and for each follower, all it's posts and followers.
I can't figure out how to limit this to the user itself.
User
@Entity
@Table(name = "User")
@NamedQueries({
  @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
  @NamedQuery(
    name = "User.auth",
    query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password"
  )
})
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(unique = true, nullable = false)
  private String username;

  @Column(nullable = false)
  private String password;

  @ManyToMany
  @OneToMany(mappedBy = "poster", cascade = CascadeType.ALL)
  private List<Post> posts = new ArrayList<>();

  @JoinTable(name = "Followers",
    joinColumns = {
      @JoinColumn(name = "USER_ID", referencedColumnName = "ID")
    },
    inverseJoinColumns = {
      @JoinColumn(name = "FOLLOWER_ID", referencedColumnName = "ID")
    }
  )
  private List<User> followers = new ArrayList<>();
 .... constructor, getters and setters

Post
@Entity
@Table(name = "Post")
public class Post {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String content;

  @ManyToOne
  private User poster;
  .... constructor, getters and setters

Outcome I get vs what I want
{
    "id": 1,
    "username": "jim",
    "posts": [
        {
            "id": 1,
            "content": "Post 1 by jim",
            "poster": {
            // ^ this is the user itself (I don't need this one)
              "id": 1,
              "username": "jim",
              "posts": [
                // keeps recurse
              ]
            }
        }
    ],
    "followers": [
        {
            "id": 2,
            "username": "follower1",
            "posts": [
                {
                    "id": 4,
                    "content": "Post 2 by follower 1",
                    "poster": {
                      // ^ this is the follower itself (I don't need this one)
                      "id": 2,
                      "username": "follower1",
                      "posts": [
                        // Same issue
                      ]
                    }
                }
            ],
            "followers": [],    // <-- I don't need this one either
        }
    ]
}

Well it's pretty clear that fetching one user fill keeps fetching all it's relations which are recursive.
Is this a designer's fault or can this be ignored/limited?
Note: I am using Gson to serialise objects to JSON format
Update
Tried to use:
@ManyToOne(fetch = FetchType.LAZY)
private User poster;

Which works but still gets the following extra prop in JSONso not sure if this is a neath solution:
"_persistence_poster_vh": {
                "sourceAttributeName": "poster",
                "isInstantiated": false,
                "row": {
                    "Post.ID": 3,
                    "Post.CONTENT": "Post 3 by jim",
                    "Post.DATETIME": "2018-01-22",
                    "Post.POSTER_ID": 1
                },
                "isCoordinatedWithProperty": false
            }

And
  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(
    ...
  )
  private List<User> followers = new ArrayList<>();

Which still returns all followers (which I want!) I just don't want the followers.followers and followers.posts..
Answer: You can specify fetch=FetchType.LAZY in the annotation you don't want to fetch immediately. The downside is, that if you need the data later you have to access it in the scope of the still open session.
Comment: I updated my question. Using fetch=FetchType.LAZY on the Post.poster will do. But using it on User.followers will still return the followers (which I need). I just don't want the User.followers.followers and User.followers.posts.
Answer: Best guess: it's not actually fetching these objects until you try to dereference them.
Be default, JPA will eager fetch @OneToOne and @OneToMany relations, but not @ManyToOne or @ManyToMany. What happens is that when you reference these fields, it will then go and fetch the actual contents of the list.
How can you tell this is happening? Check the list's class using getFollowers().getClass()
What you see won't be a LinkedList or an ArrayList but a class from your JPA provider, probably with "Lazy" somewhere in the name. When you call Size or Get on the list, it will perform the fetch.
You can set OneToOne and OneToMany relations to be lazy as well, and use EntityGraphs to determine what entities you want to eagerly fetch as well. JPA has a number of gotchas like this.
I've seen GSON mentioned, and just a warning: it won't be aware of the lazy loading lists, so you MUST tell It to avoid the properties you don't want it to follow.
Typically with JSON marshaling, you'll want it to ignore the parent object, so in Post, User should be ignored for example. Additionally links to same types should typically be ignored (followers) or else mapped specially, such that it doesn't Marshall the entire object, but only produces an array of usernames. You can tell it to ignore the actual followers field, and have it marshal a getter which returns an array of usernames to implement this.
Comment: See answer on Henry
Comment: You updated your answer. You mention ignoring it in GSON and not so much the fetch itself. Well I was already thinking of this one, but isn't inefficient to fetch all the entities with all it's relations if I don't need them, and then just ignore them with a JSON converter?
Comment: Indeed it is, but in general, JPA only eagerly fetches cardinality 1 relations, not the whole list of every relation, so the overhead is a lot less than you might think. That's also not the root of the question being asked. Basically the problem you're having seems to be a lack of awareness of the lazy load semantics of JPA and how that interacts with things like JSON marshaling rather than a lack of appropriate lazy loading semantics on the entities.
Comment: Regarding the update to include GSON details, that wasn't mentioned in your original question, so I hadn't talked about it originally. When I noticed you were marshaling the entity graph, your problem became very clear.
Comment: So how is it that Ill get every User.followers.followers and User.followers.posts and keeps on being recursive?

I checked it out logging the list className and it's indeed an JPA list type. So the problem is that the converter the followers called which will get fetched on it's turn or?
Comment: GSON is walking your entity graph to generate the JSON, and as it walks the graph, the lazy lists are being loaded from the DB. It's a little counter-intuitive, but the loads happen when GSON goes to access the contents of the fields, not when you first load the entity. That's how lazy loading works.
Comment: Ah so it's a matter of letting GSON ignore those nested fields and they will never get fetched?
Comment: Exactly. The ideal way to handle this is to tell your Marshaller that certain fields should be marshaled in special ways. The followers field marshals not the entire User object, but just a list of usernames. It will fetch the associated users, but not their posts that way. How to do this is specific to your JSON marshaller, and TBH, I usually stick to Jackson. So, read your marshaller's docs on how it converts field values to JSON and use its annotations to marshal the field in the way you want.
Comment: Ah yes thank you so much on finding the cause here with me. Ill check out the docs of Gson but if it's easier Ill just use Jackson!
Comment: I really doubt GSON vs Jackson is really that different. In general, you'll want to tell the marshaller what fields to ignore using some variety of Ignore annotation and you'll supply a type converter instead of having the marshaller walk the object graph picking out properties. This converter will convert a User to a string by taking a user object and returning the username. This converter is then specified in an annotation on the followers field. That's pretty much all there is to it using any modern marshaller.
Answer: There are two ways to handle this -

You can either use @JsonIgnoreProperties(ignoreUnknown=true) anotation on attributes you want to skip while serializing the object.
Or you change your FetchType to FetchType.LAZY so that you can get the required data on need basis while preparing your JSON , rather than getting all records at once.
Comment: See answer on Henry
Comment: @JimVercoelen I can remove the second point point but  first point still suggest another approach to handle the case. so please feel free to edit the answer rather then downvote.


TileWidePeekImageCollection - which image is shown with text

Question: In my Metro app, I have some code that builds up a TileWidePeekImageCollection06 (I assume this question applies to TileWidePeekImageCollection05, too), as shown here.
If I supply 6 images, then the sixth is shown in the "peek" along with the text, if I supply 5 then it looks like the fifth is shown with the text.  However, if I supply less than 5 images, I can't seem to determine which is shown.
What are the rules for this?  I need to know because the text shown in the "peek" with a single image needs to relate specifically to that image.
Answer: The documentation isn't very explicit, but you could find this out pretty easily through experimentation.  Alternatively, you could use the object model that provides friendly names in the NotificationsExtensions helper library in the tiles sample on MSDN (or look directly at the source mapping the friendly names to the identifiers in the helper library source: TileContent.cs).
For the specific template you mentioned, example XML is provided below with details about each image provided in the alt tag.
<code><tile>
  <visual>
    <binding template="TileWidePeekImageCollection06">
      <image id="1" src="image1.png" alt="Main image on top"/>
      <image id="2" src="image2.png" alt="Small image - row 1, column 1"/>
      <image id="3" src="image3.png" alt="Small image - row 1, column 2"/>
      <image id="4" src="image4.png" alt="Small image - row 2, column 1"/>
      <image id="5" src="image5.png" alt="Small image - row 2, column 2"/>
      <image id="6" src="image6.png" alt="Image with text"/>
      <text id="1">Text Header Field 1</text>
    </binding>
  </visual>
</tile>
</code>
Comment: Experimentation was what prompted the question - as I said, if you supply less that 6 images then it's inconsistent which is used.  For example, supplying 5 images uses the 5th, but supplying 4 images uses the 3rd.
Comment: As far as I know, an image id should always correspond to the location in the visual.  Are you seeing something different in your testing?
Comment: Yes - but only for the image with text, and only where fewer than 6 images are supplied.
Comment: From what I was seeing with tile updates before - you need to specify all fields, otherwise you might not see the updated tile at all. If you don't need one of the images - you probable need to provide an empty image instead.
Comment: You don't need to specify all of the fields.  I just confirmed that the following works, and only shows the image with the text:

Text Header Field 1


Sum of unbiased estimators

Question: Let $X$ follow a Poisson $(\lambda)$ distribution, where $\lambda>0 $ is unknown. If $\delta(X)$ is the unbiased estimator of $g(\lambda)=e^{-\lambda}(3\lambda^2 + 2\lambda+ 1)$, then what is the value of $\sum_{k=0}^\infty \delta(k)$ ?
I know that unbiased estimator implies $E(\delta(X))=e^{-\lambda}(3\lambda^2 + 2\lambda + 1)$. But I am not sure how to proceed.
Comment: This isn't about a sum of unbiased estimators, but rather about a sum of values of an unbiased estimator.
Comment: @MichaelHardy rectified
Answer: $\newcommand{\e}{\operatorname{E}}$You have
$$
\e(\delta(X)) = e^{-\lambda}(3\lambda^2 + 2\lambda+ 1) \text{ for ALL positive values of $\lambda.$}
$$
Therefore
\begin{align}
& e^{-\lambda}(3\lambda^2 + 2\lambda+ 1) = \e(\delta(X)) = \sum_{x=0}^\infty \delta(x) \Pr(X=x) \\[10pt]
= {} & \sum_{x=0}^\infty \delta(x) \frac{\lambda^x e^{-\lambda}}{x!} \\[10pt]
= {} & e^{-\lambda} \sum_{x=0}^\infty \delta(x) \frac{\lambda^x}{x!} \text{ This works because $e^{-\lambda}$ does not change as $x$ goes from $0$ to $\infty.$} \\[10pt]
& \text{Therefore } 3\lambda^2 + 2\lambda+1 = \sum_{x=0}^\infty \delta(x) \frac{\lambda^x}{x!} \text{ for ALL positive values of $\lambda$.}
\end{align}
A theorem that is not very hard to prove says that two power series cannot be everywhere equal unless all of their coefficients are equal. Thus we have
$$
1 + 2\lambda + 3\lambda^2 + 0 \lambda^3 + 0 \lambda^4 + 0\lambda^5 + \cdots = \delta(0) + \delta(1) \lambda + \frac{\delta(2)} 2 \lambda^2 + \frac{\delta(3)} 6 \lambda^3 + \frac{\delta(4)}{24} \lambda^4 + \cdots
$$
and so
\begin{align}
1 & = \delta(0) \\[10pt]
2 & = \delta(1) \\[10pt]
3 & = \delta(2)/2 \\[10pt]
0 & = \delta(n) \text{ for all larger values of $n.$}
\end{align}
So
$$
\delta(0) + \delta(1) + \delta(2) + \delta(3) + \cdots = 1 + 2 + 6 + 0 + 0 + 0 + \cdots.
$$
Comment: Thank you very much. This makes so much more sense now.
Comment: @TheDoctor : I'm glad it helped.

Sum of unbiased estimators


Feature Scaling in Regression

Question: I have a dataset in which each sample has only two features. I designed my own gradient descent algorithm, and applied it to my dataset. However, I could not obtain a result. Then, I printed the parameters generated during gradient descent, and I realized that zigzagging happens. In other words, the algorithm cannot converge to optimum point due to the value ranges that my features vary in. My features have very different value ranges.
Then, I performed mean normalization operation for feature scaling to my dataset and trained my data. My gradient descent algorithm worked perfectly well. It converged very quickly. After that, I trained another model by using built-in scikit LinearRegression library to check the success of my gradient descent algorithm. Both models, first of which is trained by my gradient descent and second of which is trained by sklearn.linear_model.LinearRegression, make very close predictions. As a result, my algorithm works properly.
The problematic issue is the values of parameters which are slope m and bias value b in the equation mx +b. Since I performed mean normalization to the features of my data set, feature space is changed. Hence, parameter values that I obtain at the end of my gradient descent and the parameter values that built-in acquire at the end of the training are not same.
Is it possible to track original parameters even if feature scaling is performed ?
I provided equation of mean normalization that I performed below:
$x^{new} = \frac{x - u}{max(x) - min(x)}$
Answer: You just need to always use this scalling for your futures (also form the test set) if you want to run a prediction, the value xnew will always between (0,1) so I should not be a problem for your prediction. But don't normalize your prediction value, this is not needed.

Feature Scaling in Regression


How can I pass proper querystring when Search from Drupal using my custom search box?

Question: I have this search form in my drupal site.
<form id="mysearch" method="get" action="<?php echo $base_url.'/search/node/'; ?>">
   <input type="text" maxlength="150" id="search" name="s" class="input">
   <input type="submit" value="Search" class="button">
</form>

I have problem is that when I am submit the form it will pass the query like that
http://mysite.com/search/node/?s=xyz

Here I would like to change the URL something like this to search in my site.
http://mysite.com/search/node/xyz

Can anyone help me how can i achieve this thing.
I have put this code for URL Change:
$("#adminbarsearch").submit(function(e) {
    $url = $("#adminbarsearch").attr("action") + $( "input:first" ).val();
    e.preventDefault();
    window.location.href = $url;
});

Instead of this Can we change the URL by using the .htaccess
Comment: jQuery code is working fine.
Answer: If you use the default search block for Drupal, it will give you the functionality you need.
EDIT: Go to Structure > Blocks and enable your Search Form Block by adding it to a region.
If you perform a search using your default search block, it will redirect to a path in the format /search/node/QUERY where QUERY is what you are searching for.
By default the search form outputs (for example):

                <form action="/" method="post" id="search-block-form" accept-charset="UTF-8">

Search form

                                Search
                                <input title="Enter the terms you wish to search for." type="text" id="edit-search-block-form--2" name="search_block_form" value="" size="15" maxlength="128" class="form-text">

                                <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

                            <input type="hidden" name="form_build_id" value="form-4gEUIDHcVH7lHHH3JpkfkVs9xBmPhHXdDQAMFMF9dHA">
                            <input type="hidden" name="form_token" value="afNo5gRQlaauXmqeZYDf80o5dEwKlg0VP6U-Ir8-p6k">
                            <input type="hidden" name="form_id" value="search_block_form">

                </form>

Now if I search for "test", it redirects to /search/node/test
Comment: Can you explain more How I can pass param in querystring without "?"
Comment: I've added more info to my answer


Translate non-digital characters to specific digits

Question: Is it possible to convert characters in a string into specific numbers like
a = 1,  // uppercase too
b = 2,
c = 3,
d = 4,
e = 5,  // and so on til letter 'z'

space = 0 // I'm not sure about if space really is equals to 0

Here's how I think it goes.
$string_1 = "abed";   // only string
$string_2 = "abed 5"; // with int

$result_1 = convert_to_int($string_1); // output is 1254
$result_2 = convert_to_int($string_2); // output is 125405

Comment: What about capital letters? Is `A` 1 as well?
Comment: Yes, mybad didn't think of it. I edited it so others will not be confused about the case sensitivity.
Answer: Here is the complete code:
$s = 'abcde';
$p = str_split($s);
foreach($p as $c) {
    echo ord($c) - ord('a') + 1;
}

Comment: does it apply to a-z as well?
Answer: To use the numbers that you have shown a = 1 etc... then just do a case-insensitive replace:
$result = str_ireplace(range('a', 'z'), range(1, 26), $string);

If you want the ASCII value then split to an array, map to the ord value and join:
$result = implode(array_map(function($v) { return ord($v); }, str_split($string)));

Answer: Create an array, and insert a space to the first element. Then use range() to generate an array with a to z. Use strtolower() to force the input to lowercase (as the characters from range() we generate is lowercase too.
Then do a replacement with str_replace(), which accepts arrays as values. The keys is the value that the value will be replaced with.
function convert_to_int($string) {;
    $characters = array_merge([' '], range('a', 'z'));
    return str_replace(array_values($characters), array_keys($characters), $string);
}

Live demo at https://3v4l.org/cHZap
Answer: To perform a string translation, the most appropriate native function is strtr().
If you don't need to translate to double digit numbers, to can pass two correlated strings.
Code: (Demo)
echo strtr('abcde 5', ' abcde', '012345');
// 1234505

If you need to accommodate the full alphabet, then declare an associative array of string keys to numeric values.  The map can be manually written or populated with a variety of native functions.
Code: (Demo)
$map = [];
array_push($map, ' ', ...range("a", "z"));
echo strtr('abcde 5', array_flip($map));
// 1234505

Or as a one-liner:
echo strtr('abcde 5', array_flip(array_merge([' '], range("a", "z"))));

To accommodate uppercase charactets, simply call strtolower() on the input string before translating.
Relevant reading:

Converting large numbers into letters (and back again)
Create unique string from id to build an link shortening system
Answer: Using regex should be like this:
$search  = array('/[A-a]/', '/[B-b]/', '/[C-c]/', '/[D-d]/', '/[" "]/');
$replace = array('1', '2', '3', '4', '5');

$final = preg_replace($search, $replace,"abcd ABCD a55");

echo $final;

Output: 1234512345155


Como Instalar Python3 Idle junto com Python 3.5.2 no Raspbian?

Question: Olá, tudo bem ?
Tenho tentado instalar o Python  3 IDLE com versão Python 3.5.2 no Raspbian, possuo um Raspberry 4b. Acontece que há duas versões que aparece 2.7 e 3.7 do Thorn IDLE. segui os passos das informações da programação abaixo :
sudo apt-get install build-essential libc6-dev
sudo apt-get install libncurses5-dev libncursesw5-dev libreadline6-dev
sudo apt-get install libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev
sudo apt-get install libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev
cd $HOME
wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz
tar -zxvf Python-3.5.2.tgz
cd Python-3.5.2
./configure
make -j4
sudo make install

porém quando instala a idle com esses comandos :
sudo apt update
sudo apt install python3 idle3

não aparece para ser executada. Se instalar primeiro a Idle do Python 3, fica coma versão 3.7. Como faço a IDLE Python 3 funcionar para a versão 3.5.2 neste caso ?
O objetivo final é poder rodar um programa desenvolvido em Python 3.5.2
Answer: Agora você teria 3 versões diferente do python.
Poderia instalar um simulador de ambiente, controlando qual versão ira usar.
Tente usar pacotes .deb
Aqui alguns https://ubuntu.pkgs.org/


Microsoft Visual Studio Installer Projects - how to provide restart prompt to MSI executed with Process.Start(), but without Repair option

Question: The problem is following: I have my custom uninstaller called before MSI uninstall. After shutting down my application properly it calls msiexec to use Windows Installer to uninstall MSI.
It's done by executing something like "msiexec /x{PRODUCT_CODE} /promptrestart".
And here is important thing - if the system is not restarted after uninstallation, and then the user installs the app again, some of its files will be deleted after next restart, so it's not acceptable. The restart is required, however, I need prompt, automatic and unconditional restart is evil and should never ever be used.
So, the invocation above displays STUPID "uninstall / repair" dialog. I do not want it. When I use "msiexec /x{PRODUCT_CODE} /qr /promptrestart" - then it uninstalls nicely, however it refuses propt for restart afterwards.
I have read about setting ARPNOREPAIR property.
But the idiots who gave that answer wouldn't care to say WHERE and HOW that property could be set. Even... Where the property belongs, it's the property of what? MSI file?
Then, maybe is it another way to achieve this, like invoke the prompt for restart from my code, but... how? The uninstaller should remove all my files until that moment. Maybe it's possible to execute a kind of script after the uninstallation process is complete?
(One more problem, the Windows Installer doesn't delete ALL files and directories created by my app. It would be nice if I could execute some code to clean up better.)
UPDATE
I see 2 paths ahead: make a script to be run once the uninstallation ends (like using Registry or Task Scheduler or IDK), use Win32 API to modify MSI file, because AFAIK it's possible to change its properties that way.
Comment: I added some comments in chat a while back.
Comment: I already (kind of) solved the problem of prompt for restart and various cleanup operations made after the installer is done.
Answer: Questions: Some questions first.

Restart Manager: Are you familiar with the Restart Manager feature of MSI? Intended to help shut down and restart
  applications without the need for reboots. I would give it a quick
  skim? I think this is your real solution?

Alternative MSI Tools: There are many tools available for creating MSI setups. This link also contains further links to a summary of the shortcomings of Visual Studio Installer Projects.

Using the free, open-source WiX toolset - for example - you can change MSI dialogs. Github sample. SO question 1. SO question 2. And here is the official WiX toolset site.
Adding my own answer from SO: Changing text color to Wix dialogs (please do skim)
I am not familiar with how to change dialogs in Visual Studio Installer Projects. Commercial products Advanced Installer and Installshield can certainly change dialogs.

Services: What is the nature of the product you are installing? Does it has a lot of services for example? Services can be shut down and restarted via MSI tables if you use a proper tool to build the MSI.
REINSTALLMODE: Do you use a custom REINSTALLMODE for your setup? (some settings can cause more reboot prompts).
Custom Uninstaller: How do you invoke that custom uninstaller of yours? Manually or do you register an uninstall command line with Add / Remove Programs? (this latter approach is not recommended).

ARP Applet vs MSI Dialogs: The ARPNOREPAIR property is set in the MSI itself - in the property table. It affects only what is seen in Windows' Add / Remove Programs applet (ARP = Add / Remove Programs), and not what you see when your MSI is invoked via command line. Then you see the dialogs defined in that MSI itself (which can be changed - not entirely trivial to do).
ARP / Add Remove Programs Applet: A quick review of this applet below:

Hold Windows Key and Tap R. Type: appwiz.cpl and press Enter. This opens the Add /Remove Programs Applet.
Select the different package entries in the list to see different settings for ARPNOREPAIR, ARPNOMODIFY, etc...

If ARPNOREPAIR is set in the MSI's property table then the Repair entry is missing.
If ARPNOMODIFY is set in the MSI's property table then the Change entry is missing.
If ARPNOREMOVE is set in the MSI's property table then the Remove entry is missing.

If the special ARPSYSTEMCOMPONENT property is set, then the MSI will be missing from ARP altogether.

Links:

In-use files not updated by MSI-installer (Visual Studio Installer project)
Comment: Will have a look. Just off the top of my head, did you try: ``msiexec.exe /x {PROD-GUID} /QB+ REBOOTPROMPT=""`` - Basic UI with a modal dialog at the end. Not sure if the REBOOTPROMPT is even needed, will check when I get a chance. Just wanted to post that so you can test yourself if you want. It is so late that I am probably mixing up something.
Comment: I don't like the above at all. For the record. What you need is [**a better MSI tool**](https://stackoverflow.com/a/50229840/129130) I think - and apply proper shutdown of your services via built-in MSI mechanisms and full control over the GUI dialogs. WiX would do, and you can get a head-start by decompiling your existing MSI with the dark.exe WiX tool. It creates WiX markup to compile an MSI from. It needs cleanup. Involved, but not rocket science. Installshield and Advanced Installer would be great too, and much easier to learn.
Comment: The custom uninstaller of mine is a registry hack. It changes original UninstallString, invokes my code (so it can shut down the app properly), then calls original content, msiexec with parameters. Without the hack I had not repair option.
Comment: I depend on MoveFileEx() from kernel32.dll for deleting files in use (after restart). The file I need to remove like this is low-level driver.
Comment: Changing my toolkit to create MSI is not a good option because of my deadlines. It would take a lot of time to learn a new toolkit, then make everything work. Yes, my app use a Windows service (one), kernel-driver and uses a lot of Windows internals voodoo. There is a nice tool (an add on) to autmate making installers, however I haven't expected it would be ridiculously hard to trigger things before and after install / uninstall. Basically I came far with that. The whole installation experience works. Now I only need that prompt for restart.
Comment: I tried `/x{productCode} /qr /promptrestart`, it's reduced UI. It works except of the restart. There is no prompt, however I can use /forcerestart and there is forced restart without prompt. In documentation stands you can't use /promptrestart with /q. Not good.
Comment: I just tried `/QB+ REBOOTPROMPT=""` - no restart prompt either.
Comment: I suppose you could insert a custom action at the end of the installation sequence that does not obey the UI level and show a prompt at the end of the setup notifying the user about the required REBOOT - if one is required. Not at all OK design-wise and application packagers in corporations will hate it since it would lock up a large-scale deployment if they forget to comment that custom action out. Specifically the dialog would likely show in a non-interactive deployment account where there is no user to dismiss the dialog and the whole deployment will fail for all computers requiring reboot.
Comment: Thanks, I'll consider it, the installation process gives me much more hard time than it should. I struggle with running the tray application by installer, because when it's run by SYSTEM I cannot shut it down sending WM_CLOSE from another SYSTEM process. There is a lot of such small issues costing ridiculous amount of time :/
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189546/discussion-between-stein-asmul-and-harry).
Answer: So, there is an "ugly hack" which solves the exact problem:
First - we need an executable, that isn't affected by the installer. This one is easy, we just copy that one installed exe to a TEMP directory and run it from there.
The next step is to that file must wait unit the uninstall phase is done. There are a couple of ways of doing so. You can observe the installer process, you can observe the file system if main program file is deleted. Considering the pace of common installer operations, polling once a second is a good enough option.
The next step is optional - you remove remaining files created by application, empty directories and such.
The next step is reboot itself, MessageBox.Show() from PresentationFramework is fine to ask user, when user answer OK or YES, then reboot itself can be performed in many ways, I use ExitWindowsEx() from user32.dll since it's probably what msiexec calls internally.
Here's example code:
if (MessageBox.Show(RestartPromptMsg, "", MessageBoxButton.OKCancel, MessageBoxImage.Exclamation) == MessageBoxResult.OK) {
    NativeMethods.ExitWindowsEx(
        NativeMethods.Flags.Reboot,
        NativeMethods.Reason.MajorApplication | NativeMethods.Reason.MinorInstallation | NativeMethods.Reason.FlagPlanned
    );
}

Of course some parameters could be passed to our special clean up executable, so it could do some extra things, like skip the restart prompt if it's not really required.
The last step is to delete our executable itself. It's easy, but it's tricky. Again I hope my example code would help:
var cleanUpTempPath = Path.Combine(Path.GetTempPath(), CleanUpExe);
File.Copy(CleanUpPath, cleanUpTempPath, overwrite: true);
Process.Start(new ProcessStartInfo {
    FileName = "cmd",
    Arguments = $"/c (\"{cleanUpTempPath}\" -purge \"{InstallerDir}\") & (del \"{cleanUpTempPath}\")",
    UseShellExecute = false,
    CreateNoWindow = true
});

We use cmd.exe special feature, the power of & and (). Commands separated with & gets executed when previous command exits. So when our clen up exe completes, it's gets deleted by the same cmd instance which called it. Remember to quote all paths, they can contain spaces. Remember to enclose a command with arguments in parentheses, because otherwise the & operator would be seen as a parameter to the previous command, not the cmd.exe.
I tested it in my big production application and it works as charm. The code examples don't work when just pasted, if you're looking for complete code, just google for it, there are plenty of working examples on pinvoke.net and StackOverflow.


Can I build my .net-core application on a linux platform, then deploy to an azure web app

Question: I am building and deploying APIs to azure web apps, and want to setup a build pipeline for continuous delivery. The options for setting this up are very limited if using msbuild is a requirement. A lot of popular solutions are linux only, or docker based.
  Is it possible to use a linux based build system to build an application (web Api), but then deploy it to an azure web app?
Answer: Have you seen Create a web app with App Service on Linux on learn.microsoft.com?
Comment: Thanks, I understand if the target system is linux, then it should work ok. The linux option is in preview, and seems targeted mainly at php and node.js services. My question is, is it possible to deploy to a standard web app? Are the binaries produced by a build on linux the same as a build on windows ?


Best practices for using `peerDependency`and `devDependency`

Question: I am writing a react component library, and dont want to bundle react, so I added the libs to peerDependencies rather than dependencies.
Also, to prevent those stupid warnings about missing peerDependencies, I add the same libs to the devDependencies section.
Thats not DRY, but a fixed warning is more important to me than a DRY package.json.
So the question is: Is there a DRYer method to achieve this, or do I actually follow the May 2020 best practice?
{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}

Answer: For npm >= v7, npm announced to autoinstall peerDependency packages.
So, just remove the deps from devDependencies, if they are already listed in the peerDependencies section like this:
{
    "peerDependencies": {
        "react": "^16.9.0",
        "react-dom": "^16.9.0",
        "tslib": "^1.11.0",
    },
    "devDependencies": {
        "@types/react": "^16.9.0",
        "typescript": "^3.8.0"
    },
    "dependencies": {
        // nothing here
    }
}

For npm < 7, follow @gcastros answer.

See also: on github and on the npm js blog.
Answer: I'm not sure what you're using to create your bundle but if you're using Webpack or Rollup you can define externals not to be included in the bundle.
In your care everything you have in peerDependencies would go into dependencies and in the config for webpack or rollup you'd define the externals as follows:
{
  ...
  externals: ['react', 'react-doe', 'tslib'],
}

Comment: @helt they do care. If it's a peer dependency it's not included in the bundle but as you have in the question you'll also have to include them in the dev dependencies. This opens up the chance for version mismatches as packages get updated in one place but not the other. Using externals is safer.
Comment: Do you mean, transpiling an bundling phases actually do not care if a dependency is peer, dev or normal?
Comment: I see. with externals, I would at least save duplicate version definitions, which is dryer than before :)


Restoring Tensorflow Model but results are incorrect

Question: I am still trying to grasp how to restore a saved tensorflow graph from disk and feed through dictionaries to the model. I have looked at multiple sources but cannot troubleshoot this. The generic MLP code below (first snippet) saves files to disk, however after restoring (second snippet), my accuracy returns a value of None. Any ideas what the reason for this may be?
# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf

# Parameters
learning_rate = 0.001
training_epochs = 15
batch_size = 100
display_step = 1

# Network Parameters
n_hidden_1 = 256 # 1st layer number of features
n_hidden_2 = 256 # 2nd layer number of features
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)

with tf.name_scope('placeholders'):
# tf Graph input
    x = tf.placeholder("float", [None, n_input],name='x')
    y = tf.placeholder("float", [None, n_classes],name='y')

with tf.name_scope('Layer-1'):
    NN_weights_1=tf.Variable(tf.random_normal([n_input, n_hidden_1],seed=1),name='NN_weights_1')
    NN_biases_1=tf.Variable(tf.constant(0.0,shape=[n_hidden_1],name='Const'),name='NN_biases_1')
    func=tf.add(tf.matmul(x, NN_weights_1,name='matmul'), NN_biases_1,name='Addition')
    func_2=tf.nn.relu(func)

with tf.name_scope('Layer-2'):
    NN_weights_2=tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2],seed=2),name='NN_weights_2')
    NN_biases_2=tf.Variable(tf.constant(0.0,shape=[n_hidden_2],name='Const'),name='NN_biases_2')
    func_3=tf.add(tf.matmul(func_2, NN_weights_2,name='matmul'), NN_biases_2,name='Addition')
    func_4=tf.nn.relu(func_3)

with tf.name_scope('Output'):
    NN_weights_3=tf.Variable(tf.random_normal([n_hidden_2, n_classes],seed=3),name='NN_weights_3')
    NN_biases_3=tf.Variable(tf.constant(0.0,shape=[n_classes],name='Const'),name='NN_biases_3')
    func_3=tf.add(tf.matmul(func_4, NN_weights_3,name='matmul'), NN_biases_3,name='Addition')
    func_4=tf.nn.sigmoid(func_3)

    # Define loss and optimizer
with tf.name_scope('Operations_'):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=func_4, labels=y),name='cost')
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
    # Test model
    correct_prediction = tf.equal(tf.argmax(func_4, 1), tf.argmax(y, 1),name='correct_prediction')
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"),name='accuracy')
    # Initializing the variables
    init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    saver = tf.train.Saver()

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print (("Epoch:", '%04d' % (epoch+1), "cost="), \
                "{:.9f}".format(avg_cost))
    print ("Optimization Finished!")
    print ("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
    saver.save(sess, 'my_test_model',global_step=1000)

Restoring Model and passing dictionary for accuracy:
import tensorflow as tf

sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,"my_test_model-1000")
graph = tf.get_default_graph()
accuracy=graph.get_operation_by_name("Operations_/accuracy")
# Access saved Variables directly
print(sess.run('Layer-1/NN_weights_1:0'))
# This will print 2, which is the value of bias that we saved

print ("Accuracy:", sess.run([accuracy],feed_dict={'placeholders/x:0': mnist.test.images, 'placeholders/y:0': mnist.test.labels}))

Answer: Change it to:
accuracy=graph.get_operation_by_name("Operations_/accuracy").outputs[0]

Tensorflow discards the outputs of Operation objects executed by means of Session.run. See here for detailed explanation: TensorFlow: eval restored graph
Comment: Genuinely appreciate your answer, and the reference too!


How can you toughen up your foot for barefoot kicking?

Question: I'm a mom of a 13-year-old boy.
He loves football. (Me, not so much. No dad.) So after football season was over, he and his buddies were at school playing football, and my son was kicking the ball. Then for what ever reason he decided to take his shoe off and kick the ball. His coach saw him and worked with him, and said he was twice as accurate without his shoe and got more height and distance. Coach said he was on the team when school starts back up based on what he had seen. I think they call it American Wedge kicking.
But he needs to toughen up his foot. He practices everyday. How does he toughen his foot up?
Of course we are from Texas, and football rules.
Comment: How does he toughen up his foot
Comment: Is this meant to be an [tag:american-football] question?
Comment: @PhilipKendall Given all of the information, I think it clearly is.
Comment: What is your question?
Comment: Yes that is my question. He needs to toughen his foot up.
Answer: Practice makes perfect. The more he kicks barefoot the tougher his foot will become over time. Look at thai/kick-boxers, they practically toughen up their shins by kicking over and over again. I should warn however, it's likely that his foot will get sore, he might get bruises on his foot if he's practising a lot..
But leaving the question aside, does it really matter for him to train kicking barefoot? I mean, he will most likely not take off his shoes before taking a kick during a game, so why practice something that you will not be able to do, instead of training to shoot better with his shoes?
Comment: No he will be kicking barefoot in the games are state allows it in school
Comment: @luann could you ask the coach this question?  I would also check with your pediatrician to see if there are any safety concerns you should be aware of.
Answer: Continue kicking and it will toughen up.
Have you considered looking into a shoe made for kicking? It may be that the shoe he was kicking with was inferior for kicking. Basketball shoes or any type of high-top would be a bad idea unless it is has a square toe and you're going for a traditional style.
Some have a cover over the laces:  http://wizardkicking.com/kicking-shoes.html


why is the receptive field size not depend on the input image?

Question: Let say if I fixed the filter size as 3x3, then shouldn't an input of 128x128 image has a larger receptive field size than an image of 32x32?
In addition, what would be the affect of stride and padding on the receptive fields?
thank you.
Answer:
"Receptive fields are defined portion of space or spatial construct containing units that provide input to a set of units within a corresponding layer.
The receptive field is defined by the filter size of a layer within a convolution neural network."

https://towardsdatascience.com/understand-local-receptive-fields-in-convolutional-neural-networks-f26d700be16c
In other words, receptive fields are about the area (in pixels) covered by the convolutional filter(s), not the size of the input.
Padding changes the effective input size, so it can't change the receptive field.
Stride changes how much area is covered by the convolution, so it increases receptive field.
Answer: To answer the second part of the question:

In addition, what would be the affect of stride and padding on the receptive fields?

As explained in Nikolas Adaloglou's blog on AI Summer Understanding the receptive field of deep convolutional networks, increasing the stride in a convolutional layer will increase the receptive field in subsequent convolutional layers. Padding doesn't change the receptive field.
For example, consider a network with two $3\times3$ convolutional layers. The first layer has a receptive field (RF) of $3\times3$ irrespective of the stride. The RF of the second layer changes with different strides used in the first layer. If the stride of the first layer is 1, then the RF of the second layer is $5\times5$. If the stride of the first layer is 2, then the RF of the second layer increases to $7\times7$ and if the stride of the first layer is 3, then the RF of the second layer is $9\times9$.


C++ Order of Classes

Question: Sorry if this was asked before, and if it was, just drop a link.
I'm fairly new to C++.
I have a project that requires me to create a Twitter-like program; where each User has their own wall, homepage, friends list, inbox, etc. The problem is is that I have to turn in one .cpp file; I have to put all classes on one file. Now since C++ reads from top to bottom, I'm having an issue with creating/referencing other classes because they haven't been defined yet.
For instance, since User contains an object made from my FriendsList class, I have to put FriendsList first, but then there's an issue where I can't make an array that holds User because User hasn't been defined yet.
Sorry if this is a stupid question.
Edit:
How would I go about forward declaration?
class FriendsList;
class User()
{
    FriendsList* friends;

    //constructor and other stuff
};
class FriendsList()
{
//stuff
};

Would it be like that? Sorry I'm just confused.
Comment: possible duplicate of [What is the purpose of forward declaration?](http://stackoverflow.com/questions/3110096/what-is-the-purpose-of-forward-declaration)
Comment: edited to ask about how I would go about forward declaration.
Comment: Yes, that's how to do forward declarations.
Answer: I think I get what your saying. It's weird that they make you put everything in one file. So what I would do. is the following.
class user{
    string url = "homepage"
    class friendList{
        user currFriend;
        user* nextFriend;
    };
    class wall{
        string status = "empty status";
    };
    class inbox{
        int number_of_messages;
    };
};

I also think this website might help.
http://en.cppreference.com/w/cpp/language/nested_types
Please message or comment if this help or if it didn't
Comment: I was thinking about doing nested classes, but I've read that it's not preferred. I was just wondering if there was something simpler. But that is a valid option!
Answer: Look up 'forward definition'  to solve the problem of two classes depending on each others definition.
But...I don't think that's the solution that really solves your problem.   Consider using std::list<> (or vector<> or array<> or whatever best suits your need) to hold the information you need.    Look up c++ collections, and go from there
class user
{
    std::list<user&> m_Friends;
    std::list<std::string> m_Messages;
    std::list<std::string> m_Wall;
};

Comment: Even if he uses a vector, doesn't he still need a forward declaration? If `User` contains `vector` and `FriendsList` contains `vector`, you still have a circular dependency.
Comment: You don't need the class FriendsList at all.  That's literally what the `list m_Friends` is.
Comment: But maybe he has other methods he wants to define for the `FriendsList` class.
Answer: Forward declaration was the way to go for most of my issues. Thanks for the help and tips about other alternatives!

C++ Order of Classes


Removing username from personal contact form

Question: On the personal contact form, when someone cc themselves, the username of the user they are emailing is exposed. Many users actually type their full name as username, so for them to remain anonymous, I don't want username to be exposed to others.
Answer: You can customize the email with hook_mail_alter(&$message).
Answer: The email that is send in those cases is set by contact_mail(), which is hook_mail() implementation done from the Contact module, and that contains the following code:
  switch ($key) {
    case 'page_mail':
    case 'page_copy':
      $message['subject'] .= t('[!category] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t("!sender-name (!sender-url) sent a message using the contact form at !form-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;

    case 'page_autoreply':
      $message['subject'] .= t('[!category] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = $params['category']['reply'];
      break;

    case 'user_mail':
    case 'user_copy':
      $variables += array(
        '!recipient-name' => format_username($params['recipient']),
        '!recipient-edit-url' => url('user/' . $params['recipient']->uid . '/edit', array('absolute' => TRUE, 'language' => $language)),
      );
      $message['subject'] .= t('[!site-name] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t('Hello !recipient-name,', $variables, array('langcode' => $language->language));
      $message['body'][] = t("!sender-name (!sender-url) has sent you a message via your contact form (!form-url) at !site-name.", $variables, array('langcode' => $language->language));
      $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !recipient-edit-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = t('Message:', array(), array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;
  }

As visible in contact_personal_form_submit(), the message identifier for the email sent when somebody contacts another user is "user_mail."
Implementing hook_mail_alter() using something similar to the following code, you should achieve the task you want.
function mymodule_mail_alter(&$message) {
  switch ($message['key']) {
    case 'user_mail':
    case 'user_copy':
      $language = $message['language'];
      $message['body'] = array();
      $params = $message['params'];
      $variables = array(
        '!site-name' => variable_get('site_name', 'Drupal'),
        '!subject' => $params['subject'],
        '!recipient-name' => format_username($params['recipient']),
        '!recipient-edit-url' => url('user/' . $params['recipient']->uid . '/edit', array('absolute' => TRUE, 'language' => $language)),
        '!form-url' => url($_GET['q'], array('absolute' => TRUE, 'language' => $language)),
        '!sender-name' => format_username($params['sender']),
        '!sender-url' => $params['sender']->uid ? url('user/' . $params['sender']->uid, array('absolute' => TRUE, 'language' => $language)) : $params['sender']->mail,
        '!recipient-name' => format_username($params['recipient']),
      );

      $message['subject'] .= t('[!site-name] !subject', $variables, array('langcode' => $language->language));
      $message['body'][] = t('Hello !recipient-name,', $variables, array('langcode' => $language->language));
      $message['body'][] = t("A user (!sender-url) has sent you a message via your contact form (!form-url) at !site-name.", $variables, array('langcode' => $language->language));
      $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !recipient-edit-url.", $variables, array('langcode' => $language->language));
      $message['body'][] = t('Message:', array(), array('langcode' => $language->language));
      $message['body'][] = $params['message'];
      break;
  }
}

I altered the message with key equal to user_reply, which is the message returned to the user who sends the message. In this way the CC returned to the sender is the same message sent to the recipient.
Comment: as per the comments in https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7.x , the API has apparently changed a bit. `$message['id]` should now be `contact_user_mail` and `contact_user_copy`.


I'm getting this error: "Missing right parenthesis"

Question: CREATE TABLE CUSTOMER
(
    CUSTOMER_NO INT(3) PRIMARY KEY,
    CUSTOMER_NAME VARCHAR2(200),
    CUSTOMER_ADDRESS VARCHAR2(200),
    CUSTOMER_PHONE INT(10),
    GENDER VARCHAR2(10)
);

Error

Missing right parenthesis
Comment: Then you should at least provide the description of what you have tried to resolve the issue and why it didn't help.
Comment: And in most of the programming languages and databases `int` has no size property and either depends on platform or has fixed size of 4 byte. For other sizes there are appropriate `tiny-`, `small-` or `big-` prefixes. What an `int(3)` is expected to be is very confusing.
Answer: In Oracle, the INT type is not parameterizable. INT is an alias for NUMBER(38).
Either remove the parameters (ie INT(3) and INT(10) should be just INT):
CREATE TABLE CUSTOMER (
  CUSTOMER_NO INT PRIMARY KEY,
  CUSTOMER_NAME VARCHAR2(200),
  CUSTOMER_ADDRESS VARCHAR2(200),
  CUSTOMER_PHONE INT,
  GENDER VARCHAR2(10)
);

or, if you want to limit the number of digits, use NUMBER(p):
CREATE TABLE CUSTOMER (
  CUSTOMER_NO NUMBER(3) PRIMARY KEY,
  CUSTOMER_NAME VARCHAR2(200),
  CUSTOMER_ADDRESS VARCHAR2(200),
  CUSTOMER_PHONE NUMBER(10),
  GENDER VARCHAR2(10)
);

Comment: The second sentence is wrong. `INT` is an [ANSI data type that, in Oracle, is an alias](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Data-Types.html#GUID-0BC16006-32F1-42B1-B45E-F27A494963FF) for `NUMBER(38)`.
Comment: @MT0 Thanks. Corrected. (I stumbled onto the wrong doc).


Not sending in Welcome Message in Discord (using discord.py)

Question: I am new to Python as well as StackOver flow. I am coding a Discord Bot for my Guild. I first feature I want to add was sending a Welcome Message in a Specific Channel. I coded it and when running I got no error...but when someone is joining my Server, no message was send by the bot.
Here's my code:
from discord.ext import commands
import discord

bot = commands.Bot(command_prefix='-')
TOKEN = '<Bot Token>'

@bot.event
async def on_ready():
print("Succesfully logged in as {0.user}".format(bot))

@bot.event
async def on_memeber_join(member):
try:
    channel = bot.get_channel(<Channel ID>)
    await channel.message.send(
        'Welcome to PRIME CLUB {0.mention}'.format(member))
except Exception as e:
    print(e)

bot.run(TOKEN)

Please Help me in correcting my Mistakes...
Thanks in adavnce
Answer: For on_member_join to work, you need to enable the Members Intent, both in your code and on your bot's dashboard. Info on how to do that is in the API Docs.
Also, you spelled member wrong ("memeber"). Your indentation looks wrong as well (1 tab when going inside of a function).
# Enable intents
intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix='-', intents=intents)

@bot.event
async def on_ready():
    # Fix indentation
    print(...)

# Spell the name of the event correctly
@bot.event
async def on_member_join(member):
    # Fix indentation
    try:
        channel = ...

Comment: Hmm...Do I have to do anything with the scopes....cause it didn't work....I have used only the Bot scope
Comment: No, you don't have to do anything else. Are you sure you did everything I said? Enabling intents both in code & on your dashboard and changing the function's name?
Answer: Thx @stijndcl for the help....
Currently This script is working well for me..
@bot.event
async def on_member_join(member):
    for channel in member.guild.channels:
        if str(channel.id) == '<CHANNEL ID>':
            await channel.send(f'Welcome!! {member.mention}')