Skill score/Rating systems that take into consideration margin of victory

Question: I am trying to create ratings/skill scores using ranking systems like Elo, TrueSkill, and OpenSkill. All of these systems are similar in that they have a distribution that represents players' skill and that the update after a match is dependent only on the parameters of the distribution.
Are there similar methods that also incorporate some exogenous measure of victory, so that the update is dependent on the distribution parameters of the players, but also margin of victory, aka how much a player won by?
Comment: See also https://stats.stackexchange.com/questions/592572/obtain-ranking-from-pairwise-comparison-with-continuous-outcome  (so far without answer)
Comment: @kjetilbhalvorsen Thanks, I will keep an eye on that too.
Comment: @clp Some things I have been looking at include Microsoft's TrueSkill and OpenSkill. The issue is neither of these take into account how much a player one a match by, simply whether they won or not.
Comment: Sorry, but I meant the scoring system of the games involved. Is it like baseball, soccer, basketball, football? An example of game scores would also help.
Question 592572 has been answered, and could include clues.
Comment: Can you explain what scoring systems you have in mind? A few examples may help.
Answer: Moderated paired comparison might be an option. It's an adaptation of the Bradley–Terry model for a setting with a continuous outcome, based on fitting a penalized likelihood model to the observed margins of victory.


How do I make it so my page view controller isn't endless?

Question: I have a page view controller that allows me to scroll through the various signup pages and enter the necessary information. The problem is it just scrolls in a circle. How do I make it so that the PlayerInfo page is the last page I can scroll to?
lazy var SignupArray : [UIViewController] = {
    return [self.VCInstance(name: "ParkSelect"),
            self.VCInstance(name: "SportSelect"),
            self.VCInstance(name: "PlayerInfo")]
}()

private func VCInstance(name: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.dataSource = self
    self.delegate = self

    if let firstVC = SignupArray.first {
        setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)

    }
}

public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{
    guard let viewControllerIndex = SignupArray.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return SignupArray.last
    }

    guard SignupArray.count > previousIndex else {
        return nil
    }

    return SignupArray[previousIndex]
}

public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
    guard let viewControllerIndex = SignupArray.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard nextIndex < SignupArray.count else {
        return SignupArray.first
    }

    guard SignupArray.count > nextIndex else {
        return nil
    }

    return SignupArray[nextIndex]
}

Answer: public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{
    guard let viewControllerIndex = SignupArray.index(of: viewController) else {
        return nil
    }

    let previousIndex = viewControllerIndex - 1

    guard previousIndex >= 0 else {
        return nil
    }

    return SignupArray[previousIndex]
}

public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
    guard let viewControllerIndex = SignupArray.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1

    guard SignupArray.count > nextIndex else {
        return nil
    }

    return SignupArray[nextIndex]
}

The reason it is endless because
when previousIndex becomes zero you pass the last VC in array
guard previousIndex >= 0 else {
    return SignupArray.last
}

when nextIndex is equal to count of signUp array u pass the first VC in array.
guard nextIndex < SignupArray.count else {
    return SignupArray.first
}

Remove these two code and ur PageViewer will stop
Comment: Mind telling me what you changed or added?
Comment: @Alexander : Was typing explanation posted code first thats all
Comment: Now the pages don't scroll at all.
Comment: removing those two lines of code will still yield the same result of my pages not scrolling.
Comment: @Alexander : Please use the code I have posted one of ur condition in viewControllerBefore was wrong because of which its not scrolling
Comment: @Alexander : Am glad I could be of help :) Happy coding
Answer: Return nil instead of wrapping around. For example:
public func pageViewController(_ pvc: UIPageViewController, viewControllerAfter vc: UIViewController) -> UIViewController?{
    guard
        let i = SignupArray.index(of: vc),
        i < SignupArray.count - 1
    else {
        return nil
    }
    return SignupArray[i + 1]
}

or, even more concisely:
public func pageViewController(_ pvc: UIPageViewController, viewControllerAfter vc: UIViewController) -> UIViewController?{
    let i = 1 + (SignupArray.index(of: vc) ?? SignupArray.count)
    return i < SignupArray.count ? SignupArray[i] : nil
}


Is there a way to turn sharps and flats into natural notes?

Question: I realise this might be kind of a silly question, but I recently got a kalimba and I am trying to turn various piano songs into kalimba songs!
My kalimba is tuned to C major and has 17 keys; no sharps or flats.
But most C major songs I've found have the occasional sharp or flat note in them that I can't seem to play. Is there a way to change them to a different note that would suit? I assume it might be a little difficult, and would probably depend on the song. I've read about transposing but it looks like that's only for the entire key.
I don't know much about music theory honestly, if this is a bad question feel free to just tell me.
Comment: If you don't want to change the structure of the melody, transposing the piece is your best bet IMO, but that depends if the sharp or flat notes are used instead of the natural note, or in addition. For example, if your piece had a B flat, but no natural B, you could treat it as if it were written in F major, and transpose it to C major (replace each F with a C, each G with a D etc.). If your piece has both B flat and B natural, you're out of luck, and must find ways to modify the melody unobtrusively.
Comment: I would love for you to give some examples of melodies which you're unable to play, to try and work out whether your problem is with transposition, chromatic passing notes, or actual chromatic harmony/modulation, because they're progressively more easy to solve (and I may as well use examples that you actually want to play rather than simply coming up with some of my own- less work for me and more relevant to you so everyone wins haha)
Comment: I suspect you've just discovered that there are limitations to just about anything we know how to do. In order to achieve a designated pitch, you'll need to have something capable of producing it.
Answer: While you can change sharps and flats to naturals, this has a nasty tendency to either sound like amateurish mistakes (as hitting an adjacent note is one of the most common types of mistake made at the regular piano) or major/minor mode changes (changing all the C sharps to C naturals in an A major piece, for instance). I don't recommend it in general, and I really don't recommend it if you're publicly performing these pieces.
You may be able to get away with changing sharps/flats to more distant chord tones in the harmony (e.g. change an F sharp in the bass to a D when you're playing a D major chord), but you basically cannot in the melody without people thinking that you're messing up the piece.
As the question asker has already mentioned, transposing the entire piece to C major has the greatest chance of working, but many pieces still end up with black notes no matter what key they are in (such as every piece that uses 3 or more notes that are a semitone apart from each other). For example, you cannot transpose "The Star-Spangled Banner" to any key without requiring a black note, as due to its use of a secondary dominant, even the C major version requires F, F#, and G.
Comment: To be honest with the star spangled banner the most passable solution is probably simply to play an F natural; in this specific case the melodic shape is more important and in this case an F natural still works as a weak ii V I that's not particularly jarring to the ear (you can imagine the melody *having* been written that way just fine, it just wasn't).  If you play e d c E F G I doubt many people (other than musicians) would notice that much to be honest.  Usually just dropping the sharp isn't a good solution of course, but in this case, it's not so bad,
Comment: With a melody like the star spangled banner that's so well known inside and out with people singing it on a regular basis, it's more difficult to get away with, but often you can change the melody slightly to avoid it.  So for "by the dawn's early light" instead of playing  e d c E F# G I'd play e d c E a G or e d c b a G.  Now, if I was playing the star spangled banner in America, I suspect people might notice that melody change and notice it as "wrong", but in other melodies you can often get away with fudging the melody a little to fit in in the diatonic scale.
Comment: @Some_Guy indeed, the earliest versions of the tune didn't have the F#.  The Library of Congress has a version from as late as 1861 without the raised 4th degree on "dawn's early light" at https://blogs.loc.gov/music/2010/03/our-national-anthem/, though it does have a raised 4th degree at "flag still was there" (sic).  The ca. 1790 print of the Anacreontic Song, however, lacks the raised 4th degree in both places: https://www.loc.gov/resource/ihas.100010458.0
Answer: You might be interested in knowing that there are Chromatic Kalimbas available that would make available all the sharps and flats you might need to play the melody lines accurately, and you can also play the songs in any major or minor key. It would just involve learning how to play it and learning some basic theory. That would be the best solution I can think of.
Answer: You may be able to change the tuning of your kalimba. I had a commercially produced kalimba and the tangs were moveable by pushing/pulling them to become shorter/longer over the bridge which changes the tang's tuning. It's tricky to get the tuning right, but it's possible.
About your actual question: dealing with chromatic pitches on a purely diatonic instrument.
Think of this more as a strategy than a proper musical process. Sort of the way a jazz singer "interprets" a melody and changes pitches around. There isn't a "right" way to do it. Keep in mind chromatic tones are often the distinctive features of a melody, so changing those tones may sound like changes to the essence of the melody. Try to listen to substituted pitches with an open mind.
The first practical thing to do is to transpose all melodies you want to play into C major.
Next, the common reasons for chromatic tones are to form temporary leading tones, subdominants, or borrowed harmonies. Usually those temporary tones are relative to one of the diatonic tones. So, in C major...

the temporary leading tones are C#, D#, F#, G# as leading tones those pitches would move up respectively to D, E, G, and A
there is only one temporary subdominant Bb moving down to A (all the other temporary subdominants are diatonic and present no problem of chromaticism)
the borrowed tones would be Eb, Ab, and Bb and they would likely be tones from borrowed chords, respectively the minor i, iv, or subtonic bVII

...that is just a list of the common harmonic origins of those chromatic tones. We want to know what to play as a diatonic alternative.
For the temporary leading tones you can alternatively play the whole step above the target note. Ex. for C# D try E D. The one place this will not work is D# E where the whole step above is another chromatic tone F#. In that case try playing B the dominant of E or just anticipate the E meaning play an E instead of D# before the main E.
For the temporary subdominant Bb try playing G to A, the whole step below the target tone.
All the above assumes the temporary leading tones/subdominant resolve by step to the next tone. If that doesn't happen in the melody, the most likely thing to happen in the melody will be those melody tones move to some other tone of the given chord. Conveniently all the other chord tones of the various chords involved will be diatonic tones. Ex. G# moving up to A, the G# is from the chord E7, the other tones of that chord are E B D, all diatonic in C major. Instead of playing the G#, try any of E B D.
For the borrowed tones try a similar approach of substituting with another tone from the borrowed chord. For example, if there is an Ab it is likely from a borrowed chord like minor iv, try one of the other tones from that chord like F or C. Conveniently, when dealing with borrowed tones Eb, Ab, and Bb and their respective chords i, iv, and bVII all the other chord tones are diatonic to C major.
It is very possible that a chromatic tone will be none of the chord tones above and will simply be a chromatic non-chord tone such as a chromatic passing or neighbor tone. In such a case you have a bit more freedom to choose an alternative. Probably you can try whatever tone is diatonic in the other direction. Ex. for a lower chromatic neighbor, use the upper diatonic neighbor tone.
An example that I think works pretty well...
Red Roses for a Blue Lady

...with the chromatic tones changed according to my suggestions...
Answer: This is a complex topic. While the presence of accidentals can be a problem, it is not necessarily so, since:

Sometimes older scores do not state all real accidentals, but choose to provide some on every occurence instead, so completing the key signature may get rid of all interspersed ones, and simple transposition would work.
In the cases where not, a transposition may exist, where no further accidentals are required.

I would look for scores for other non-chromatic instruments and transpose them to C, if needed. I know by chance, that many old bagpipes have very limited chromatic support, so searching in that repertoire may improve chances. Also more affordable hook-based harps need some time to get to the accidentals, so the beginner pieces, where no chords are used and the used range is limited, may also be appropriate.


Exchange 2013 Banner

Question: We have an exchange 2013 server that is failing a reverse SMTP Banner Check:
220 [Internal IP] ESMTP Smtpd;
I have gone into our exchange receive connector for the internet, "Default frontend servername" and have changed the banner to "220 SMTP OK domain" however running the check or connecting through telnet will only give the original, default banner. I decided to change all of the receive connectors (just in case) but I still only get the default banner. I opened up the protocol smtp receive logs and I see:
date, receive connector, seq ect, 220 SMTP OK domain,
I think I am misunderstanding, but how do I change what is displayed and comply with the reverse banner check?
Answer: It is Receive Connector setting.
You can change banner using powershell, example:
Set-ReceiveConnector -Identity <connector name> -Banner <banner> -ConnectionTimeout <timeout>

To view Receive Connectors list from your frontend server use powershell:
Get-ReceiveConnector -Server <server name>

Answer: Don't change the Receive Connector banner. It has zero effect on your ability to send or receive email from the internet and is just a way to pass a poorly designed test.
Changing the receive connector banners can affect your ability to send email internally though, which includes sending email between servers and within users.
I wrote about these poorly designed tests over six years ago.
http://blog.sembee.co.uk/post/Exchange-2007-and-SMTP-Banner-Tests
The only test that matters is outbound SMTP banner testing, which you have to use another tool. I have written about that here:
http://blog.sembee.co.uk/post/Exchange-200720102013-Outbound-SMTP-Banner-Testing

Exchange 2013 Banner


Tensor characterization

Question: I want to show that $T^{1}_{1}(V)$ is isomorphic to $End(V)$. I know how to produce a linear map from $h:End(V)$ to $T^{1}_{1}(V)$, i.e. send $f \in End(V)$ to $hf(w,v) = w(f(v))$, but how to write down its inverse explicitly since I want to calculate the trace of its inverse?
Answer: The trick here is that this fact holds only for finite-dimensional vector spaces $V$, so, in order to establish it, we are forced to deal with some kind of a "proof of dimensionality", e.g. a basis.
Notice, that elements of $T^1_1(V)$ are finite sums of "simple" tensors, that is, objects of the form $v \otimes \phi$ for some vector $v \in V$ and a "covector" $\phi \colon V \to k$ (a linear map) where $k$ is the base field, e.g. $\mathbb{R}$ or $\mathbb{C}$.
Suppose, that $\{ e_i \}_{i=1,\dots,n}$ is a basis in $V$, where $n = \dim V$.
We have the dual basis $\{ \widehat{e}_j \}$ in $T_1 := V^* := Hom(V,k)$
and the elements in the dual basis are defined on $v = \sum_i v^i e_i$ by $ \widehat{e}_j (v) = v^j$.
Now, any element $t \in T^1_1(V)$ is uniquely represented as
$$
t = \sum_{1 \leq j,k \leq n} a_{jk} e_j \otimes \widehat{e}_k \tag{*}
$$
(Think of a matrix $A =  (a_{ij})$ of the endomorphism that we a looking for!)
It is clear, that for $t$ as in $(*)$ we can assign an endomorphism
$$
v = \sum_{i} v^i e_i \mapsto \sum_{1 \leq j,k \leq n} a_{jk} e_j \otimes \widehat{e}_k (v) = \sum_{1 \leq j,k \leq n} a_{jk} v^k e_j \tag{**}
$$
It remains to check that $(*) \to (**)$ indeed yields the inverse to your mapping.
I leave the verifications and final conclusions up to you. If I have time later, I will try to update this answer, and. in particular, improve the notation.
Answer: For any vector space $X$, write "$X^T$" for its dual.
Then we define $g:T^1_1(V)\to \mathrm{Hom}(V,V^{TT})$ by $((gb)v)w = b(w,v)$.
When $V$ is finite dimensional we have $V^{TT}\cong V$, and then $\mathrm{Hom}(V,V^{TT})\cong\mathrm{End}(V)$ and $g$ gives the inverse to $h$.
Comment: You've identified $(1,1)$-tensors with bilinear forms implicitly, but apart from that you way looks to me very neat and concise. Could you please explain how can you think of $(1,1)$-tensors as of $b(w,v)$, not using the isomorphism we are trying to prove?
Comment: @YuriVyatkin From the look of the question the questioner is *defining* $T^1_1(V)$ to be the set of bilinear maps $V^T\times V\to\mathbf{F}$ (this definition only agrees with the usual one in the finite dimensional case, but some GR and differential geometry textbooks use it to get to tensors quickly). This is how they can define $h$ by "$hf(w,v) = w(f(v))$". With your definition of the tensor product their definition of $h$ doesn't work, and indeed the $\mathrm{End}(V)\to T^1_1(V)$ direction become the difficult direction to do the construction.
Comment: Thanks. You are correct, I am learning the tensor stuff from Lee's riemannian manifolds. He defines the ricci curvature in terms of the trace of curvature endomorphism. I am totally confused, since there are so many notations and identifications involved. It is really hard to compute its component functions.
Comment: How does the expression you give define an endomorphism on $V$?
Comment: @koch It didn't! I had a mistake in my answer, it should make sense now.

Tensor characterization


Why is the Hessian of the log likelihood function in the logit model not negative *semi*definite?

Question: The Hessian of the log likelihood function is
$$\frac{\partial^2 \ln(\beta \mid x)}{\partial \beta \partial \beta'}
= -\sum_{i=1}^n \underbrace{\Lambda(\beta'x_i)}_{\in(0,1)}\underbrace{\left[1-\Lambda(\beta'x_i)\right]}_{\in(0,1)}\underbrace{x_ix_i'}_{\geq 0}$$
where I have marked my understanding of the ranges of the different factors with underbraces. The Hessian would be zero if $x_i=\mathbf{0}$ for all $i$. Thus, I would conclude that the Hessian was negative semi-definite.
Yet in Greene (p. 691-692)---which specify the Hessian just as I do---it says

Note that the Hessian is always negative definite, so the
  log-likelihood is globally concave.

What am I missing here?
Answer: When they say the Hessian is always negative definite, they are assuming that $X$ is a full rank matrix, which is a very typical assumption for regression models.
So it is true that in your example, the Hessian would not be negative definite. However, they assume that you have informative data: you can't expect to estimate the effect of $x$ if you don't observe different levels of $x$.
Comment: I'll also note that statisticians tend to be a little lazier about stating such things than mathematicians!


Cron error message. table or view not found: 1146

Question: In watchdog I am seeing an error when cron is run.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tdtvnksvps.field_deleted_data_38d3088921' doesn't exist: SELECT DISTINCT t.entity_id AS entity_id FROM {field_deleted_data_38d3088921} t WHERE bundle = :db_condition_placeholder_0 LIMIT 50 OFFSET 0; Array ( [:db_condition_placeholder_0] => ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->readFieldItemsToPurge() (line 1686 of /home/300465.cloudwaysapps.com/tdtvnksvps/public_html/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Pretty sure I mistakenly deleted a table from the database a while back and this is the result.
The issue appears to be similar to Error when deleting some node, but I think the advice given to find a record of the deleted field was written for D7.
Is this the same problem and how resolve it for D8?
Answer: I Had this issue sometimes ago, I deleted a field table from DB manually and this error started to showing up, A way to get rid of it is to create a table for a field, so you can use a mysql code like that :
CREATE TABLE `field_deleted_data_38d3088921` (
    `bundle` varchar(128) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'test',
    `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'A boolean indicating whether this data item has been deleted',
    `entity_id` int(10) unsigned NOT NULL COMMENT 'The entity id this data is attached to',
    `revision_id` int(10) unsigned NOT NULL COMMENT 'The entity revision id this data is attached to',
    `langcode` varchar(32) CHARACTER SET ascii NOT NULL DEFAULT '' COMMENT 'The language code for this data item.',
    `delta` int(10) unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields',
    `test` varchar(2048) DEFAULT NULL COMMENT 'test',
    PRIMARY KEY(`entity_id`,`deleted`,`delta`,`langcode`),
    KEY `bundle` (`bundle`),
    KEY `revision_id` (`revision_id`)
)

Comment: Great idea, then you can run cron and when the purge job sees there are no field records present in the empty table it removes the table and the config pointing at the table.
Comment: This worked a treat. Thank you both for the input.
Answer: This issue is the opposite of Can I delete leftover field_deleted_* tables?. In your case you have leftover field and field storage config entities serialized in the database table key_value as state collection in the keys field.field.deleted and field.storage.deleted.
Normally both, the config entities and the deleted tables, are removed in cron runs.
Comment: Thank you for the explanation


UIView in unexpectedly going under the status bar

Question: I'm working on my iPhone application and I have a really weird behavior with the status bar and the window.
In the beginning my view appears to be slightly under the status bar (my view's height is 480) as i want it to.
But after i use the Movie player in another view and i transition the app to the first view its no longer slightly under it goes down 20px and starting when the status bar finishes cause the lower 20px's of my screen to be hidden.
I dont know what causing this behavior and i really wanna control it.
Can some one please advise ?
Thanks in advance.
Answer: well the error is caused due to the fact that the status bar is 20px in height and the height of the iphone screen is 480px. and so if you create an app that has 480px height with the status bar on top of it than this kind of mess is ought to happen. so my advise is that either you make your view 460px height or hide the status bar if 20px are that important to you.
If you want to hide the status bar then in info.plist add another variable called "status bar initially hidden" and click on the check box its at the end of the list.


How to add app's shortcut to the home screen

Question: I know it's not documented and won't work on every device, but I see more and more apps placing their shortcuts on the home screen after they got installed.
Found bunch of code chunks how to do it but for me they don't fit together.
This is what I got for now.

Need a permission in the manifest.
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

Create an Intent of activity that should be called. Ex (from cgeek):
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName("com.example.androidapp", "SampleIntent");
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Create shortcut itself
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Name");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.icon));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
context.sendBroadcast(addIntent);

My questions is:
Where this code should go to make shortcut added after .apk installed? I tried this code in the launcher activity, it creates broken(another story) shortcut every time app starts.
Comment: I also agree as a user, it is really annoying. But...
As a developer, if it is requested and if i explained that it must not be done but still insisting me to do that. Yeah, you can do that after ICS. Permission is necessary, for the rest [check this answer](http://stackoverflow.com/a/18327304/1171484)
Comment: THis answer is not working on kitkat...
Answer: As far as I know, that's an optional feature of the Market app, not of the apps themselves. By design an application does not receive a broadcast about itself being installed. If that codes works, the soonest you can execute it is the first time the user launches the app. That said:
Do. Not. Automatically. Create. App. Shortcuts.
Ever.
Don't usurp the user's UI design.
Comment: Really tired of people thinking they know everything better than others saying "Do not do this, do not do that, this is evil".
Comment: 1 special case in the ocean of apps is not enough to disregard a fairly basic and uncontroversial rule of thumb. If a user doesn't understand how to manage their home screen, it's all the more reason to NOT put something there that they don't know how to remove.
Comment: "Do. Not. Automatically. Create. App. Shortcuts." I disagree. Viber do that and Viber is not so evil like that. This is useful because the target people of Viber do not is nerd or geek. They don't know how to manage the home screen. It's a fact.
Comment: The point is that Android is an OS not only used on smartphones or tablets (there are thousands of devices!). There are other contexts where you develop apps for Android, sometimes not even using the market at all. One can have VERY GOOD reasons to do what you could call evil in a usual case.

And this also applies to the Android dev team: stating that something shall never be done in usual cases is not an excuse to limit the API on that specific point. This just goes against the flexibility we except from a good API & OS.
Comment: IMHO it's convenient to see app's shortcut, which I wanted to install and try to use right away on the screen, than spend couple+ seconds searching for it among all apps. People that can't manage basic things on android usually do not use those devices. No offence, but your arguments are unconvincing.
Comment: I agree completely with Alex's comment...IMHO it is very narrow minded to only think of Android as a phone OS.
Comment: Looks like it's not allowed anymore : "Apps and their ads must not modify or add browser settings or bookmarks, add homescreen shortcuts, or icons on the user's device as a service to third parties or for advertising purposes. " but I am not sure, because of the last sentence. (from the new policy: http://play.google.com/intl/en/about/developer-content-policy.html)
Comment: can be done see this http://stackoverflow.com/questions/16873256/how-to-add-shortcut-to-home-screen-in-android-programatically
Answer: I agree with the currently accepted answer, that you should not do this by receiving a broadcast or at-install time. Don't do anything without user interaction or permission.
However, if you provide a button in your application, you would put this in the buttons OnClick handler. It would then add a shortcut when the user selects the "add shortcut" option.
Answer: This can be possible just add the below code to your main activity in oncreate method
        Intent HomeScreenShortCut= new Intent(getApplicationContext(),
                MainActivity.class);

        HomeScreenShortCut.setAction(Intent.ACTION_MAIN);
        HomeScreenShortCut.putExtra("duplicate", false);
        //shortcutIntent is added with addIntent
        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, HomeScreenShortCut);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "AppName");
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
            Intent.ShortcutIconResource.fromContext(getApplicationContext(),
                        R.drawable.ic_launcher));

        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

        getApplicationContext().sendBroadcast(addIntent);

Add add this permission to your manifest
 <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

Comment: It adds the shortcut, but if you try to open the app using that it sends a toast "App isn't installed". Am I missing something here? Thank you.
Answer: I used this code to create 3 shortcuts on homepage:
Intent HomeScreenShortCut= new Intent(getApplicationContext(),
            MainActivity.class);

HomeScreenShortCut.setAction(Intent.ACTION_MAIN);
HomeScreenShortCut.putExtra("duplicate", false);
//shortcutIntent is added with addIntent
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, HomeScreenShortCut);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "AppName");
addIntent.putExtra(
    Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
    Intent.ShortcutIconResource.fromContext(
        getApplicationContext(),
        R.drawable.ic_launcher
    )
);

addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

getApplicationContext().sendBroadcast(addIntent);

Comment: What's the "duplicate" for?
Comment: @androiddeveloper it is in order to avoid duplicating icons (it doesnt create an icon if it already exists in home screen).
Comment: I didn't know about this. Where did you find about this parameter? Do you know of others?
Comment: say, what's the correct way to put a shortcut with an icon of another app? You can't obviously use ShortcutIconResource...


Permutations of pairs with restrictions

Question: $n$ friends get together and decide to play a game. Thankfully one friend has a deck of $n$ cards, numbered from  $1$ to $n$.
How the Game Works

The group splits into pairs (the game only works when $n$ is even)
Everyone draws a card
In each pair, the person who drew a card with a higher number wins (yay!)
Winners are recorded and who drew which card is recorded
Cards are collected and shuffled
Repeat steps 1-5 for $m$ rounds
Publish the final rankings in order of wins

The Question
My question is about looking at all the possible ways the game could have played out if people would have paired up differently. There are $(n - 1)!!$ possible ways people could have paired up in a given round. Which means that over $m$ rounds, there could have been $(n - 1)!!^m$ ways for the game to have played out
The next time the group plays the game, they decide that everyone has to pair up with each other roughly the same number of times. The maximum and minimum number of times two people can pair up is as follows
$$\text{max} = \left\lceil \frac{m}{n-1} \right\rceil$$
$$\text{min} = \left\lfloor \frac{m}{n-1} \right\rfloor$$
With this new rule, how many possible ways could the game have played out?
Comment: This is the flavor text that I was going to, but didn't add to the question:

One of the people playing the game (let's call him Bob) starts to realize that one of his friends (let's call him Jimmy) is getting really lucky. Even though Jimmy is drawing really low cards, he seems to always be paired up with someone who draws a lower card. So Bob decides he is going to prove that Jimmy got lucky.
Since all of the data from the rounds is recorded, Bob decides to create a simulation to show what the final rankings should have been in all permutations of pairings.
Answer: Let's call this number $P_n$. It is quite obvious, that $P_2 = 1$. Now, suppose $n > 2$. Then we know, that the $n$-th player paired with $m\%(n - 1)$ people $\left\lceil \frac{m}{n-1} \right\rceil$ times and with $n - 1 - (m\%(n - 1))$ people $\left\lfloor \frac{m}{n-1} \right\rfloor$ times (here $\%$ stands for remainder). He can do that in $C_{n-1}^{m \%(n-1)}$ ways. So $P_n = C_{n-1}^{m \%(n-1)}P_{n - 1} = \Pi_{i = 1}^{n - 1} C_{i}^{m \%i}$.That is the answer.
Comment: Awesome! I have taken some university math but I'm not sure what C or the 2 in Roman numerals mean. Could you add an example with numbers substituted in?
Comment: @alexdrieger, $\Pi$ stands for product in the same way, as $\Sigma$ stands for sum. $C_n^k$ stands for binomial coefficients: https://en.wikipedia.org/wiki/Binomial_coefficient

Permutations of pairs with restrictions


Create Flutter Plugin with pod dependencies

Question: I created a flutter plugin with "FacebookShare" dependency.
My pod spec like below,
Pod::Spec.new do |s|
  s.name             = '{plugin name}'
  s.version          = '0.0.2'
  s.summary          = 'A new Flutter plugin for share image and text in social media'
  s.description      = <<-DESC A new Flutter plugin for share image and text in social media
                       DESC
  s.homepage         = 'https://github.com/jayarajm/flutter_share_social_media.git'
  s.license          = { :file => '../LICENSE' }
  s.author           = { '...' => '...' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  s.dependency 'FacebookShare'

  s.ios.deployment_target = '8.0'
  s.static_framework = true
end

In the sample project, the plugin refers to a local path. So I didn't receive any problem to install pod or run the project.
After publish into "https://pub.dartlang.org/".
I try to use from dart packages in my project, I received a problem in installing pod. I attached the error below,
CocoaPods' output:
↳
      Preparing
    Analyzing dependencies
    Inspecting targets to integrate
      Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
    Fetching external sources
    -> Fetching podspec for `Flutter` from `.symlinks/flutter/ios`
    -> Fetching podspec for `flutter_share_social_media` from `.symlinks/plugins/flutter_share_social_media/ios`
    Resolving dependencies of `Podfile`
    Comparing resolved specification to the sandbox manifest
      A Bolts
      A FBSDKCoreKit
      A FBSDKShareKit
      A FacebookCore
      A FacebookShare
      A Flutter
      A flutter_share_social_media
    Downloading dependencies
    -> Installing Bolts (1.9.0)
      > Copying Bolts from `/Users/jayaraj_m/Library/Caches/CocoaPods/Pods/Release/Bolts/1.9.0-ac656` to `Pods/Bolts`
    -> Installing FBSDKCoreKit (4.40.0)
      > Copying FBSDKCoreKit from `/Users/jayaraj_m/Library/Caches/CocoaPods/Pods/Release/FBSDKCoreKit/4.40.0-ae214` to `Pods/FBSDKCoreKit`
    -> Installing FBSDKShareKit (4.40.0)
      > Copying FBSDKShareKit from `/Users/jayaraj_m/Library/Caches/CocoaPods/Pods/Release/FBSDKShareKit/4.40.0-0e459` to `Pods/FBSDKShareKit`
    -> Installing FacebookCore (0.5.0)
      > Copying FacebookCore from `/Users/jayaraj_m/Library/Caches/CocoaPods/Pods/Release/FacebookCore/0.5.0-74288` to `Pods/FacebookCore`
    -> Installing FacebookShare (0.5.0)
      > Copying FacebookShare from `/Users/jayaraj_m/Library/Caches/CocoaPods/Pods/Release/FacebookShare/0.5.0-963b4` to `Pods/FacebookShare`
    -> Installing Flutter (1.0.0)
    -> Installing flutter_share_social_media (0.0.2)
      - Running pre install hooks
    [!] The following Swift pods cannot yet be integrated as static libraries:
    The Swift pod `FacebookCore` depends upon `Bolts` and `FBSDKCoreKit`, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
    The Swift pod `FacebookShare` depends upon `Bolts`, `FBSDKCoreKit`, and `FBSDKShareKit`, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
    The Swift pod `flutter_share_social_media` depends upon `Bolts`, `FBSDKCoreKit`, and `FBSDKShareKit`, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/installer/xcode/target_validator.rb:135:in `verify_swift_pods_have_module_dependencies'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/installer/xcode/target_validator.rb:38:in `validate!'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:415:in `validate_targets'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/installer.rb:118:in `install!'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/command/install.rb:41:in `run'
    /usr/local/lib/ruby/gems/2.5.0/gems/claide-1.0.2/lib/claide/command.rb:334:in `run'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/lib/cocoapods/command.rb:52:in `run'
    /usr/local/lib/ruby/gems/2.5.0/gems/cocoapods-1.5.3/bin/pod:55:in `<top (required)>'
    /usr/local/bin/pod:23:in `load'
    /usr/local/bin/pod:23:in `'
Error output from CocoaPods:
↳
    [!] `<PBXGroup UUID=`97C146E51CF9000F007C117D`>` attempted to initialize an object with an unknown UUID. `CF3B75C9A7D2FA2A4C99F110` for attribute: `children`. This can be the result of a merge and the unknown UUID is being discarded.
    [!] Automatically assigning platform `ios` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

Comment: did you solve this error ?
Answer: I'd a similar problem, with the same output <PBXGroup UUID..., in my case when I ran pod install --verbose I realize that there was an specific error during pod install

undefined method `each_child' for #Dir:0x00007ff10befa7f0 Did you mean? each_slice

Looking for this specific error I found this answer and I realize that I was using ruby 2.5 and one file generated by Flutter for iOS devices was trying to use a method that was introduced on version 2.6.
After follow the steps on that answer I could run my Flutter app on iOS simulator.

The method dir.each_child was introduced in Ruby 2.6, but you are using Ruby 2.3.0.

You should update Ruby to 2.6.0 or later 2.x version.

After Ruby updating you may also need to restart your IDE and re-install cocoapods.


Gradient zero implies lipschitz with arbitrary constant

Question: I can't work out if this is true or not:
Let $f:\mathbb{R}^N\rightarrow \mathbb{R}$ be differentiable at zero with $\nabla f(0)=0$ and $f(0)=0$. Is it true that for any $\delta > 0$, there is a neighbourhood of $0$ over which $f$ is Lipschitz with constant $\delta$? i.e. does this hold:
$$\forall \delta > 0, \exists r > 0 \text{ such that } \forall x, y \in B_r(0), |f(x)-f(y)|<\delta |x-y|$$
where $B_r(0)$ is the $r-$ball around $0$.
I think it is true but I am struggling to prove it. I thought maybe I could use a proof by contradiction by assuming the opposite of the above and finding $x_n,y_n\rightarrow 0$ such that $|f(x_n)-f(y_n)|>\delta|x_n-y_n|$ to then somehow reach that $|\nabla f|>\delta$ but I can't get this to work. If it isn't true, I can't manage to make a counterexample. Note, I do not want to assume differentiability of $f$ for $x\neq 0$.
Answer: A counterexample is
$f(x):=x^{3/2}\sin\frac1x$ if $x\ne0$, $f(0):=0.$
$f'(0)=\lim_{x\to0}\sqrt x\sin\frac1x=0$ but $f'(x)=\frac32\sqrt x\sin\frac1x-\frac1{\sqrt x}\cos\frac1x$ takes arbitrarily large values in any neighborhood of $0$.
Comment: Oh yes! Clearly! I wasn't thinking straight for a moment - thank you
Comment: Ah right, I see - thank you! Just to check - how do you know $f'(0)=0$ in this example?


Is $x^2 \equiv -1 \pmod{365}$ solvable?

Question: I know that a similar question already exists, but I have a different question to ask.
We want to examine if $x^2 \equiv -1 \pmod{365}$ has a solution.
My thought is: $365=5\cdot 73$. So,The congruence $x^2 \equiv -1 \pmod{365}$ has solution, if and only if, the congrueces $x^2 \equiv -1 \pmod 5$ and $x^2 \equiv -1 \pmod{73}$ has solutions. So, if we use Legendre's Symbol we have

$x^2 \equiv -1 \pmod 5$ has solution $\iff (-1/5)=1 $ (and with simple calculations, indeed)
$x^2 \equiv -1 \pmod{71}$ has solution $\iff (-1/73)=1 $

Now, can we conclude that the congruence $x^2 \equiv -1 \pmod{365}$ has solution?
And more general: If we have the congruence $x^2 \equiv a \pmod n$ with $n=p_1^{n_1}\cdots p_k^{n_k},\ \gcd(a,n)=1$, which is equivalent with the system $x^2 \equiv a {\pmod p_1^{n_1}},\ldots,x^2 \equiv a \pmod{p_k^{n_k}}$, can we conclude that the first has solution if and only if each one of  $x^2\equiv a\pmod{p_i^{n_i}},\ \forall i=1,\ldots,k$ has solution?
Thank you.
Comment: Change $71$ to $73$ and it's fine.
Comment: @RobertIsrael Thank you for your comment and your correction.
Comment: Note the use of \pmod rather than \bmod in my edit to the question.
Comment: @RobertIsrael Ok, thank you
Answer: We have $365 = 5 \times 73$.  The congruence becomes $x^2 = -1 \mod 5$  and $x^2 = -1 \mod 73$.
We have if $p = 1 \mod 4 \implies x^2 = -1 \mod p$ has exactly $2$ solutions.
Thus $x^2 = -1 \mod 5$ has solutions $x_0,x_1$ and $x^2 = -1 \mod 73$ has solutions $y_0,y_1$.
The original solutions satisfies either:
$x = x_0 \mod 5, x = y_0 \mod 73$; $x = x_0 \mod 5, x = y_1 \mod 73$; $x = x_1 \mod 5, x = y_0 \mod 73$ ; $x = x_1 \mod 5, x = y_1 \mod 73$.
For each pair of congruence , $x$ is uniquely determined $\mod 365$ by the Chinese remainder theorem.  Hence the original congruence has $4$ solutions.
Answer: If $\,m,n\,$ are coprime then, by CRT, solving an integer coefficient  polynomial $\,f(x)\equiv 0\pmod{\!mn}\,$ is equivalent to solving $\,f(x)\equiv 0\,$ mod $\,m\,$ and mod $\,n.\,$ By CRT, each combination of a root $\,r_i\bmod m\,$ and a root $\,s_j\bmod n\,$ corresponds to a unique root $\,t_{ij}\bmod mn,\,$ i.e.
$$\begin{eqnarray} f(x)\equiv 0\!\!\!\pmod{mn}&\overset{\rm CRT}\iff& \begin{array}{}f(x)\equiv 0\pmod m\\f(x)\equiv 0\pmod n\end{array} \\
&\iff&  \begin{array}{}x\equiv r_1,\ldots,r_k\pmod m\phantom{I^{I^{I^I}}}\\x\equiv s_1,\ldots,s_\ell\pmod n\end{array}\\
&\iff& \left\{ \begin{array}{}x\equiv r_i\pmod m\\x\equiv s_j\pmod n\end{array} \right\}_{\begin{array}{}1\le i\le k\\ 1\le j\le\ell\end{array}}^{\phantom{I^{I^{I^I}}}}\\
&\overset{\rm CRT}\iff& \left\{ x\equiv t_{i j}\!\!\pmod{mn} \right\}_{\begin{array}{}1\le i\le k\\ 1\le j\le\ell\end{array}}\\
\end{eqnarray}\qquad\qquad$$
Answer: Yes. Let a solution to $x^2+1 \equiv 0 \pmod {5}$ be $r_{1}$, and let a solution  to $x^2+1 \equiv 0 \pmod {73}$ be $r_{2}$
Then note that by CRT, we have that there exists such $x$ that $$x \equiv r_{1} \pmod {5}$$ $$x \equiv r_{2} \pmod {73}$$
Exists. Then note that for such $x$, $$x^2+1 \equiv 0 \pmod {5}$$ $$x^2+1 \equiv 0 \pmod {73}$$
Which gives $$x^2+1 \equiv 0 \pmod {365}$$
Comment: Seems alright now.
Answer: We show the following result:

Let $n,m$ be coprime integers. Let $a \in \Bbb Z$. Then $a$ is a square modulo $nm$ iff $a$ is square mod $n$ and $a$ is square mod $m$.

Assume that there are integers $x_i$ such that $x_1^2 \equiv a \pmod m$ and $x_2^2 \equiv a \pmod n$ where $m,n$ are coprime.
We show that $y^2 \equiv a \pmod {nm}$ has a solution (the converse is obvious).
We know that there is an integer $y$ such that  $y \equiv x_1 \pmod m$ and $y \equiv x_2 \pmod n$, by the Chinese remainder theorem.
Then $y^2-a$ is a multiple of $m$ and $n$, so it is a multiple of $nm$ since $(n,m)=1$. Therefore $y^2 \equiv a \pmod {nm}$.

More generally, we have the following theorem (see Ireland Rosen, p. 50)

Let $a,n \in \Bbb N$ be coprime integers. Write $n=2^e p_1^{e_1} \cdots p_k^{e_k}$ as product of distinct prime powers.
  Then $a$ is a square modulo $n$ if and only if

$a$ is a square modulo $p_i$ (for $1 \leq i \leq k$) ; this is equivalent to $a^{\dfrac{p_i-1}{2}} \equiv 1 \pmod{p_i}$
$e>1 \implies a \equiv 1 \pmod{2^{2+r}}$ where $r = 1$ if $e \geq 3$ and $r=0$ if $e=2$.
Comment: It might be worth explicitly mentioning the CRT here where it's used, but this is elsewise a good, clean answer.
Comment: @Chris : you're welcome. It is chapter 5 in Ireland, Rosen.
Comment: @Chris : since $2$ is not a square mod $59$, it is not a square mod $118$, that's correct!
Comment: Thank you , now it's clear.
Comment: Tell me please something else. If we have the congruence $x^2 \equiv 2 \bmod 118$ could we say that $118=2\cdot 59$ so it's in the form of $2p^m$ and $2^{\phi(118)/ \gcd(2,\phi(118))} \equiv -1 \bmod 118$ so there are no solutions (because it is not a quadratic residue mod 118)?
Comment: But, in this case, $\gcd(2,118) \neq 1$. How could we proceed?
Comment: @Chris : I see. That's confusing because $2$ appears as $a$ in $x^2 \equiv a \pmod n$, but also in $n=2^1 \cdot 59^1$. Here $a$ is not a square mod $p=59$, so it is not a square mod $n=2p$. You don't need $(a,n)=1$ for that.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/53192/discussion-between-chris-and-watson).
Answer: It is true because of the Chinese remainder theorem, which asserts the map
\begin{align}
\mathbf Z/n\mathbf Z&\longrightarrow \mathbf Z/p_1^{n_1}\mathbf Z\times\dotsm\times\mathbf Z/p_k^{n_k}\mathbf Z\\
x\bmod n&\longmapsto(x\bmod p_1^{n_1},\dots,x\bmod p_k^{n_k})
\end{align}
is a ring isomorphism.

Is $x^2 \equiv -1 \pmod{365}$ solvable?


Begin transaction está bloqueando todo meu banco de dados

Question: Estou com um problema, tenho um script php que faz leitura de arquivos grandes em XML.
Antes de iniciar a inserção desses dados faço um begin transaction e no fim o commit, porém durante todo o processo que pode levar até 20 minutos meu banco de dados fica inutilizável, tanto pra quem está fazendo a importação (até aqui ok) tanto para outros computadores que não tem nada a ver com a tabela que está sendo populada, vocês podem me dar uma luz?
Comment: Posta o código para a nós darmos uma checada!
Comment: Quando você chama *sqlsrv_begin_transaction* você nao passa nenhum parâmetro? E se pra cada select que voce fizer dentro dessa transação voce fizer dentro de uma nova transação? Já tentou isso?
Comment: Qual banco de dados é? você da algum lock manualmente?
Comment: Estou utilizando o sql server 2008. Não utilizo nenhum lock, todas as configurações estão padrão de instalação no sql server
Comment: Poderia colocar parte do código php e da sql.
Comment: Hm, estou usando a classe Adodb para PHP com o driver mssqlnative. A chamada que ela executa é para a função "sqlsrv_begin_transaction" e depois disso faço os insert normalmente e então o commit. No meio dessa transaction estou executando alguns selects, vocês acham que as tabelas que executo o select dentro da trans estão sendo bloqueadas ?
Answer: Bruno,
Quando abrimos uma transação todas as tabelas envolvidas do seu script ficarão bloqueadas para utilização até que a transação seja concluída. O SQL Server, e outros SGBDs, utilizam esta técnica para evitar que outros leiam um dado fantasma, sujo ou desatualizado que é um dado não confiável.
Encontrei uma explicação mais detalhada sobre este caso Isolation Level . Neste link, você pode encontrar duas soluções para o caso:

Setar o Isolation Level para READ UNCOMMITTED nas queries fora da transação;
Utilizar a opção WITH (NOLOCK);

Segue um exemplo das suas utilizações:
Isolation Level:
<code>    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
    SELECT * FROM tbIsolationLevel
</code>
WITH (NOLOCK):
<code>SELECT * FROM tbIsolationLevel WITH (NOLOCK)
</code>
Lembrando que você terá problemas de leitura de dados não confíaveis nas duas soluções.


Pra que serve .this em java

Question: Ola, entao, estou comecando no java e gostaria de entender melhor o que é .this.
Imagino que tenha algo a ver com a classe atual ou algo do genero. Mas não tenho certeza. Vou postar uma parte do meu codigo que .this esta contido
<code>   class Conta {
   int numero;
   String dono;
   double saldo;
   double limite;
  // Os metodos que ultilizam o .this
   boolean saca(double valor) {
         if (this.saldo < valor) {
           return false;
         }
         else {
           this.saldo = this.saldo - valor;
           return true;
         }
   }
      void deposita(double quantidade) {
         this.saldo += quantidade;
   }
}
</code>
Tem a public class tambem que só está dando valor as variaveis criadas na classe Conta
Answer: Isso é para diferenciar quando o método tem o mesmo nome de parametro que a class, no seu codigo isso não acontece, então não tem necessidade do this, se vc tivesse algum atributo na classe com o nome de valor, ai aquele metodo precisaria de um this.valor, pra dizer que vc quer alterar apenas o atributo daquela instancia e não da classe
Pelo visto ta estudando pelas apostilas da caelum, logo logo vc vai entender bem isso, esse metodos iram crescer bem ainda rsrs
mas ao grosso modo eh isso, se seu metodo passa parametro com o mesmo nome de um atributo da classe, então para se referenciar a aquela instancia do metodo, se usa o this., senão fizer isso, java ira entender que quer alterar o atributo da classe

Pra que serve .this em java


Determine that this multivariable function is differentiable

Question:
$$
f(x,y) = \begin{cases}
0, & x = 0 = y \\
\frac{x^3}{x^2 + y^2}, & \text{otherwise}
\end{cases}
$$

So, I did determine that this function is continuous(correct me if I'm wrong here). But, the issue is that the first order partial derivative with respect to $y$ is not continuous(I found this out by taking the partial derivative away from the origin and then switching to polar coordinates and taking the limit as $r \rightarrow 0$. So, I cannot use the differentiability theorem(existence of continuous first order partial derivatives guarantee differentiability). So, what do I do from here?
Comment: First calculate what the first partials would be at the origin, directly from definition.
Comment: have you tried using the definition of differentiability for functions of several variables? If you can compute the partial derivatives, you already have the gradient.
Answer: My answer shows it is not differentiable at origin. Kindly check whether  I have  done any calculation error.
$${f_x} (0,0)=\mathop {\lim }\limits_{x \to 0} {{f(x,0) - f(0,0)} \over x} = \mathop {\lim }\limits_{x \to 0} {{x-0} \over x} = 1$$
$${f_y} (0,0)=\mathop {\lim }\limits_{y \to 0} {{f(0,y) - f(0,0)} \over y} = \mathop {\lim }\limits_{y \to 0} {{0 - 0} \over y}=0.$$
Therefore
$$I=\lim_{(x,y)\rightarrow (0,0) } {{f(x,y) - f_x(0,0)x-f_y(0,0)y-f(0,0)} \over{\sqrt{x^2+y^2}}} = \lim_{(x,y)\rightarrow (0,0) } {{{x^3/(x^2+y^2)}-x-0-0}\over {\sqrt{x^2+y^2}}}$$
$$=\lim_{(x,y)\rightarrow (0,0) } {-xy^2\over{(x^2+y^2)\sqrt{x^2+y^2}}}. $$ Calculate the limit value of the second using polar co-ordinates, by taking  $x=r\cos\theta$ and $y=r\sin\theta$ and $r\rightarrow 0.$
Then $I=\lim_{r\rightarrow 0}\cos \theta\sin^2\theta =f(\theta).$ Limit value depends on the path. So limit does not exist and the function is not differentiable at the origin.
Answer: $∆f=f(0+h,0+k)-f(0,0)$
$= \frac{h^3}{h^2+k^2}$
And $f_x = 1$, $f_y=0$.
Therefore $df = hf_x+kf_y=h$.
If the function is differentiable then $\lim_{(h,k)\to (0,0)} \frac{∆f-df}{\sqrt{h^2+k^2}}$ must be $0$.
Now, $\frac{∆f-df}{\sqrt{h
^2+k^2}}= -\frac{hk^2}{\sqrt{h^2+k^2}(h^2+k^2)}....(i)$
Putting $h=r cos\theta, k=rsin\theta$  in $...(i)$ we get,
$\frac{∆f-df}{\sqrt{h^2+k^2}}$
$=-cos\theta sin\theta$
Which in general doesn't approach zero as $\sqrt{h^2+k^2}=r \to 0$.
Hence $f(x,y)$ isn't differentiable at $(0,0)$.


The variable animacao of Controles has not been assigned

Question: Estou tentando fazer meu personagem Andar em uma animation e ficar parado na outra.
Em Animator, criei um parâmetro do tipo float andar para fazer o controle de troca entre as animações como mostra a imagem abaixo.

E atribui nas setas as seguintes condições:
*andar > 0.1 vai pra personagem;
  *andar < 0.1 vai pra personagemStop;
Exemplo de uma das setas:

Meu código está desta forma:
#pragma strict

var speed : float;
var personagem : GameObject;
var animacao : Animator;

function Start () {
    speed = 2;
}

function Update () {
    transform.position.x += Input.GetAxis("Horizontal") * speed * Time.deltaTime;

    //O ERRO OCORRE AQUI!!!!!_________________________________________
    animacao.SetFloat("andar",Mathf.Abs(Input.GetAxis("Horizontal")));
    //________________________________________________________________

    if(Input.GetAxis("Horizontal") < 0){
        personagem.gameObject.transform.eulerAngles = Vector2(0,180);
    }
    else if(Input.GetAxis("Horizontal") > 0){
        personagem.gameObject.transform.eulerAngles = Vector2(0,0);
    }
}

Talvez possa ser algo relacionado a versão do Unity mas não sei o que possa ser, estou fazendo este game seguindo este tutorial
https://www.youtube.com/watch?v=PDuqGIB8j7E
Meu Unity é 5.3.1f1 e o do tutorial é 4.3.2f1
No Animator do exemplo, não existe o Entry mostrado na primeira imagem.

UnassignedReferenceException: The variable animacao of Controles has
  not been assigned. You probably need to assign the animacao variable
  of the Controles script in the inspector.
  UnityEngine.Animator.SetFloat (System.String name, Single value)
  Controles.Update () (at Assets/Assets/Scripts/Controles.js:17)
Answer: Achei o problema.
No link do tutorial mencionado na pergunta, em aproximadamente 5:28 do vídeo ocorre um erro, dai vem uma tela preta dizendo que foi resolvido mas não explica exatamente o que aconteceu.
De fato, ele esqueceu de mostrar uma coisa, no objeto quando adicionamos o código javaScript a ele, devemos informar o personagem e a animação como mostra na imagem. Se não fizer isso, ocorre o erro mencionado na pergunta.

Animacao - personagem (Animator) é o Animator da primeira imagem da pergunta.
Personagem - personagem é filho de principal, onde ocorrem as trocas de sprites.


How do I add conditional product options in Magento

Question: If I have a product and would like to offer a subset of products (accessories) based on a yes/no choice by the user, what's the best way to approach it?
In a simple example, a user selects a Phone. If the user then selects YES from a "Show phone accessories" dropdown
I'd them like them to be offered a set of drop downs offering choice of accessories, e.g skins, case etc.. on that page
Can this be implemented using Magento functionality?  Or must I use an add-on/extension?
Answer: If your question is can this be done using stock Magento functionality, then the answer is No.
You may be able to do this with somewhat stock functionality just by overriding templates with custom javascript.  I.e the 'accessories' drop down is always displayed, but hidden until the user does something.
Comment: Thank you Jared, I suppose the next question is, what extensions are available that can do this?
Comment: I don't know of any extensions that do this, but it is possible that I don't understand the expected behavior quite right.  You want a drop down on all/some products that once moved to the 'yes' position displays a list of related products/cross-sells (presumably in a modal popup or in the product details box).  Correct?
Comment: correct, here's an example (not a magento site) see what happens when you click the pre-hang option http://www.doors4home.com/p-2204-htc700-1-2.aspx
Comment: Ah ok this is different.  You are basically just selecting attributes, or child products.  I could make some recommendations in that regard but would rather do it in a different venue as to not muddy up SO.
Comment: Um, please advise me, do i need an extension like  BCP? http://www.magentocommerce.com/magento-connect/better-configurable-products.html
Comment: Please contact me through my website.


How to proxy a server based on domain name of request using nginx?

Question: There is a situation where firstly all current requests should work as they currently working for certain domain name. For example www.hello.com
A dynamic dns is going to point to the same static ip of www.hello.com server (somedomain.dnsdynamic.com ---> XXX.XXX.XXX.XXX)
All requests, both GET, POST, etc. to be proxied to another server with hostname finalserver.example.com. (note that this server does not have a static ip, so the hostname must be used)
Proxy should only work when the www.hello.com server gets a request with server name somedomain.dnsdynamic.com
Already tried keeping in mind this answer but failed, either getting 502 bad gateway or 404 page not found
Answer: If i understand you correctly, you could try defining two Virtual Hosts :

one for www.hello.com that serves the local web server content
another for somedomain.dnsdynamic.com that proxies to
finalserver.example.com

Something like this :
    server {
      listen       80;
      server_name  www.hello.com;
      root /var/www;
      index   index.html;
    }

    server {
      listen       80;
      server_name  somedomain.dnsdynamic.com;

      location / {
        proxy_pass  http://finalserver.example.com;
      }
    }

Comment: Thanks! seems to work so far. Need to test more thorougly though. One thing that we had to change in order to make it work was to comment out this line `proxy_set_header Host $host;`. This was causing the 404 page not found error because backend server just happened to be configured to not accept any other host name! Lucky guess :)
Comment: @George Pligor Ok, let me know about your tests. Cheers
Comment: @George So what about your tests ? if this actually solved your problem thanks in advance to mark it as "answered"
Comment: You left the site?.. well the issue has been put on hold because of other more critical issue, but rest assured that I will come back at this answer. have a good one
Comment: @George Pligor What you mean ? i'm still here man :)
Comment: Ok sure, you just have no username so I could not reply to you. Ok your solution worked awesomely thank you. I will include as a note that `root /var/www;` and `index index.html` are actually redundant for those who are not using php
Comment: Hi! could you expand your answer to both nginx and Apache ? and I can expand the question for consistency. Thank you
Comment: @George Pligor This is not the way this site works. You asked for nginx and you got an answer. Now, if you want the same for Apache, you have to post a new question. Cheers
Comment: ok got it, no problem
Comment: Can a set up like this reduce load on server? I am getting 502 bad gateway on our servers on increased load. Both our domains are pointing to same uwsgi_server . Will this help in resolving the issue ?


Multithreading: Switching context

Question: I have written a small sample code:
public class Button2 implements Runnable{
    JButton jButton = new JButton();
    static boolean changeContext = false;
    public Button2(){
        jButton.setText("ButtonTWO");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeContext = true;
                ((JButton)e.getSource()).setEnabled(false);
            }
        });
    }
    @Override
    public void run() {
        System.out.println("ButtonTWO run...");
        jButton.setEnabled(true);
        while(true){
            if(changeContext)
                break;
        }
        changeContext = false;
    }
}

When I run it like:
Button2 threadTWO = new Button2();
Thread thread2;
            try{
                thread2 = new Thread(threadTWO);
            thread2.start();
            thread2.join();
            }catch(Exception ex){
                System.out.println("Ëxception caught");
            }

It never comes out, even after clicking button.
If I add a sysout or Thread.sleep(1) after while(true) in run method, it comes out of while loop. What can be the possible reason?
Answer: I assume you're running the bottom portion on the EDT. Thus you're creating the button (and hopefully add it to your ui somehow) then start the thread and make the EDT wait for the thread to die (thread2.join()), hence the EDT can't process the events and changeContext = true is never called.
That adding something makes the loop end probably is due to missing braces:
This only ends the loop if changeContext is true:
if(changeContext)
   break;

I assume you did this:
if(changeContext)
   Thread.sleep(1);
   break;

The above calls sleep if changeContext is true and then immediately ends the loop (the break is not inside the if-block anymore. So if you want consistent behavior write it like this:
if(changeContext) {
   Thread.sleep(1);
   break;
}

Btw, Apple had a security issue last year which basically had a similar source (a double break and no braces).

Multithreading: Switching context


no-indexing a views page

Question: Im using D7 and views 3 and I cant seem to find a solid answer on how to do this or if its possible but I created a page in views and I wanted to no-index the page, I dont see any options in views to do it so im wondering if this is possible and if so how can I go about doing this.
Any help is appreciated it.
EDIT**
Here is a function I managed to come up with however it something is making it not work. Does anyone have any suggestions?
function noindex_taxonomy(&$head_elements) {
  if (arg(0) == 'taxonomy' && arg(2) == 104 || arg(0) == 'taxonomy' && arg(2) == 103 || arg(0) == 'taxonomy' && arg(2) == 108) {
    $head_elements['noindex'] = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
  }
}

Answer: There is not any option in views module to add metatags. but you can add metatags to any url of your site by other drupal metatag modules.
See How to define Meta tags on Views?.
Comment: Yeah I tried using that but its throwing off errors on my site.
Answer: I was able to achiveve this by putting my function into my template.tpl.php file
function loans_html_head_alter(&$head_elements) {

/*Url inside the view*/ $siteurls = drupal_get_path_alias();

if (arg(0)== 'taxonomy' && $siteurls == 'taxonomy/term/104/latest') {
    $head_elements['noindex'] = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
  }
}

no-indexing a views page


Inferring number of solutions for a linear system of three variables from just two equations

Question: Consider the equations:
$ x+2y + 2z =1$
and, $ 2x+4y+4z=9$
According to my book, we can infer there are zero solutions from looking at both equations. However, this doesn't make sense to me as, I was taught that we find out about number of solution using the determinant of the coefficients of three equations for a linear system of three variables.
Basically my question is, given two equation of three variables, can we infer about the number of solutions without having a third?
Comment: $(x,y,z)=(1,0,0)$ is a solution over the field $\Bbb F_7$.
Comment: what is a field
Comment: For example, $\Bbb Q$, or $\Bbb R$, or $\Bbb C$, or $\Bbb F_p$. See [wikipedia](https://en.wikipedia.org/wiki/Field_(mathematics)). Where did you want to have the solutions? In the integers?
Comment: Yes, you can use the determinant of the coefficient matrix when you have enough equations, but that's not applicable here since there are fewer equations than unknowns.  The determinant by itself doesn't really tell you enough even when there are. If it vanishes, then you need to examine other things to determine whether there are zero or an infinite number of solutions to the system.
Answer: You may simply observe that once multiplied by 2 the first equation becomes $2x+4y+4z=2$. However since $2\neq 9$ we may note that for all values these two equations are inconsistent and so there are no solutions.
Comment: By that with functions I meant in general just consider the coefficients. Essentially the planes are the same if you can reduce the coefficients down to the simplest possible form and if they are the same consider the constant term. Generally if the coefficients are different then the equations are different. You just have to be careful in the case say :$x+y+z=1$ and $-x-y-z=-1$ since if you multiply the second plane by -1 you have the same equation and thus same plane.
Comment: I meant to say don't we need 4 equations to determine consistency
Comment: No. And btw: the question whether that makes sense to you won't make much sense to the universe.
Comment: In general for $n$ distinct equations in $n$ variables you can determine the a solution through the method you stated above. However in general given two equations you cannot say for certain without observing properties of the functions. For example in the case you gave you can observe the two planes run parallel and so there are no solutions. Further they could be the same equation and so you can have infinitely many solutions in that case also, provided by the plane. Finally they could intersect in a line so you obtain infinitely many solutions again there. In general no.
Comment: I meant '3' equations sorry
Comment: So, what exactly is the algorithim for determining if there is solutions or not?
Comment: @DDD4C4U I assumed that so answered with considering the case of two planes (e.g. two equations given in 3 variables) and considered the possibilities in how they can interact. The number of solutions will vary by the consideration of another plane. If the three planes are distinct they will intersect at one point (can you see why?) and otherwise if you have two planes we are in the case above. Does this clarify your issue? If not can you try to be more specific and I'll see if I can explain it further.
Comment: the thing which threw me off in the first comment is the stuff about functions. Other than that I think I get it now, how do u check if two planes are distinct or not?
Comment: I didn't get a notification of this yesterday but I understood now :)


Without using L'Hospital's rule, what is $\lim\limits_{x \to 0}\dfrac{\tan{x}-\sin{x}}{x^3}$?

Question: I have to find the following limit without using L'Hôpital's rule:
$$\lim\limits_{x \to 0}\dfrac{\tan{x}-\sin{x}}{x^3}$$
I first converted $\tan{x}$ to $\frac{\sin{x}}{\cos{x}}$, and factored like this:
$$\dfrac{\dfrac{\sin{x}}{\cos{x}}-\sin{x}}{x^3}$$
$$\Rightarrow \dfrac{1}{x}\dfrac{\sin{x}}{x}\dfrac{1}{\cos{x}}\left(\dfrac{1-\cos{x}}{x}\right)$$
I can find the limit of each fraction except the first which is $\frac{1}{x}$.
How can I solve this without using L'Hospital's rule?
Comment: Hint. $\frac{\sin{x}}{x}\frac{1}{\cos{x}}\frac{1-\cos^2(x)}{x^2}\frac{1}{1+\cos(x)}=\left(\frac{\sin{x}}{x}\right)^3\frac{1}{\cos{x}}\frac{1}{1+\cos(x)}$
Answer: I would do it this way:
$$\frac{\tan{x}-\sin{x}}{x^3}=\dfrac{\sin x(1-\cos x)}{x^3\cos x}=\dfrac{\sin x(1-\cos^2x)}{x^3\cos x(1+\cos x)}=\frac{\sin^3x}{x^3}\,\frac 1{\cos x(1+\cos x)}.$$
Added: it may be shortened, using the result of this standard high-school exercise:
$$\lim_{x\to 0}\frac{1-\cos x}{x^2}=\frac12.$$
Answer: $1-\cos x=2\sin^{2}(x/2)$, so you need $x^{2}$ in the denominator to have the pairing.
Answer: $$\lim_{x\to0}\frac{\tan x-\sin x}{x^3}=\lim_{x\to0}\frac{\tan x}x\lim_{x\to0}\frac{1-\cos x}{x^2}=\frac12\lim_{x\to0}\frac{\sin^2\frac x2}{\left(\frac x2\right)^2}.$$
Answer: An asymptotic approach
We note that as $x \to 0$
$$\frac{\tan x -\sin x}{x^3}=\frac{\tan x(1-\cos x)}{x^3} \sim \frac{\tan x \,(\frac{x^2}{2})}{x^3} \sim \frac{1}{2}$$


absolute beginner to integration, need to study integration for highschool level competition exam

Question: I'm in high school and lazed around during 1months class of integration, mainly because my teachers were only focused on getting students to memorize types and solve questions based on them. I can memorize types but really dislike memorizing stuff. I'm really good at differentiation(for my course level). Differentiation follows rule and such and hence it is easy to get creative with it and solve even more complex question.
I want to know if there are stead fast rules to solving integration or atleast some vital points to note while solving one. I dont mind memorizing formulae and type but it becomes tedious when there is a different type for each question you get.
Is integration really only about memorizing stuff, or is there pattern recognition and rules at play?
Comment: Didn't you have to memorize the rules for differentiation? Computing the anti-derivative is simply finding the inverse: what function would I take the derivative of to get "this". Yes, that can be difficult to do and for some things there is no way to solve algebraically.
Comment: My tried and true method of learning math is to attack many math exercises.
Comment: so is memorizing types the only way of solving questions?
Comment: In addition to treating integration as anti-differentiation as a form of pattern recognition, it is worth being able to handle partial fractions, integration by parts, and substitution, and to know how to deal with $\int \frac1x\, dx$.
Comment: @user2661923 is there any source you'd recommend to do questions from?
Comment: That is a question for your math teachers.
Answer: For those of you who are more experienced users, I'm sorry, I just don't have enough reputation to comment. Anyways it's more pattern-y than memorization. Patterns like substitution, integration by parts, and partial fractions are going to be a lot more helpful than memorizing an integral table. I would highly recommend checking out blackpenredpen's many videos on integration and practicing on the examples he provides.


proving a transpose times its original equals to $I_n$?

Question: Let $P = [p_{ij}] \in \mathsf{M}_n (\{0,1\})$ (i.e., $p_{ij} = 0$ or $p_{ij} = 1)$ and suppose that
$$ \sum_{i=1}^n p_{ij} = 1,~i=1,\dots,n $$
and
$$ \sum_{j=1}^n p_{ij} = 1,~j=1,\dots,n. $$
Prove that $ P^\top P = I_n $.
I have no idea how to prove this. I always just considered  that $ P^\top P = I_n $ was true so I am coming up with no idea on how do do this.
so my question how do I prove this question?
I don't know if the title is accurate, but it you have a better one feel free to change it.
Answer: The product $PP^T$ has it's $(i,j)$th entry as $\sum_{k=1}^n P_{ik}P^T_{kj} = \sum_{k=1}^n P_{ik}P_{jk}$.
Now, note that there is precisely one $k_i$ for which $P_{ik_i} \neq 0$. If $j \neq i$, then naturally the product will be zero, since $k_i \neq k_j$, otherwise the vector containing $(i,j)$ and $(i,k)$ would have sum greater than $1$.
If $i = j$, then the above sum is clearly $1$, since the sum is just $\sum_{k=1}^n P_{ik}^2 = 1$.
Hence, the entries are $1$ if $i=j$, and $0$ otherwise. This is clearly a description of the identity matrix.
Answer: $$ \sum_{i=1}^n p_{ij} = 1,~i=1,\dots,n $$
means each column sums to $1$, since $P$ is a binary matrix, there is exactly one $1$ in each column.
and
$$ \sum_{j=1}^n p_{ij} = 1,~j=1,\dots,n. $$
means each row sum to $1$, similarly, there is exactly one $1$ in each row.
Hence $P$ is a permutation matrix.
Hence $P^T=P^{-1}$.
Comment: then would i have to prove that $P^{-1}P = I_{n}$ or can i say that that is just a fact
Comment: Isn't $P^{-1}$ defined to be the matrix that satisfy $P^{-1}P=PP^{-1}=I$?
Comment: yes it is. i was just wondering it i need to prove it , but apparently i can get by by just saying $PP^{−1}=I$, so thanks
Comment: I added a link to my post for readers who might not be familiar with permutation matrix.
Comment: how did you know that $P$ was a binary matrix, was it the $ P=[p_{ij}]∈M_n({0,1})$?
Comment: $P = [p_{ij}] \in \mathsf{M}_n (\{0,1\})$, yes, elements of $P$ take only value of $0$ and $1$.


CSSFriendly issue just after publishing to web server

Question: I created a website and used css friendly adapters for Menu, TreeView and GridView, all was correct, but after publishing it to my great web server, the menus and treeviews didn't load and there is just some bullets!
Here is my work: http://jds.cot.ir (dead link)
Left side I have a menu which did not load.
Comment: For anyone still following this, there is a compile issue with App_Browsers and the .Net 3.5 or prior runtimes and VS2010. It will compile all other elements to the prior runtime but App_Browser.dll to 4.0 ... delete /bin/App_browsers.dll and it should be fine. This may not be the explicit cause you have, but it might just help.
Comment: I viewed the html source, all are correct, and classes are visible and the style.css has been loaded, I don't know why it does not work.
Comment: what are the datasources for your controls? Are they binding to a database? If so, have you copied across your database etc?
Answer: Did you copy over the App_Browsers folder? I'd check you copied all files over and, if you can, restart the application pool (touching web.config should achieve this).
Comment: this folder exists, whould I restart the application pool? if yes, how? Do you mean via web.config, I can restart application pool?
Comment: I restarted the application by copying app_offilne.htm and requesting the url and renaming the file and again requesting the web site, but it is not correct yet.
Answer: I found the problem and the solution, I have an error loading one css file:
<link href="/WebResource.axd?d=FmPs0x8PbK0cHdhnI4N-J7cB33HdEr5UOoA_QzdIwqZdeINM8Kod5dxru5SzZMkL0&t=633820044382031250" type="text/css" rel="stylesheet" />

and the content of this css was an error titled:
Specified argument was out of the range of valid values. Parameter name: utcDate

I changed my pc date to one month ago and rebuilt my solution, and upload it again.
And every thing is correct. ;)
Comment: I just had this happen this evening while devloping, apparently due to the time change!!!
Answer: Try deleting precompiled.config from the root of the web app on the server.  That did it for me.  Haven't really looked into what the pros and cons are.  Looks like the publisher's precompilation doesn't take into account the control adapters for some reason.  I just ran into this in VS2010 beta 2.


Is the set $I$ in the axiom of infinity often interpreted to be an actual infinite set?

Question: After some discussion on philosophy stackexchange I wanted to know what some set theorists consider the infinite set that the axiom of infinity posits to exists.
Question
Do most, or you if you're a set theorist reading this question, set theorists believe that the infinite set $I$ in the axiom of infinity believe that $I$ is a completed infinite set or just a potentially infinite set?
This question is important to me, because I've been wondering how most mathematicians can believe that the set $\mathbb{N}$ is a completed infinite set without the presupposition that actual infinite sets exist. Then I began reflecting on the axiom of infinity, which would provide the mathematician a starting point to begin working on deductions concerning actual infinite sets if this axiom concerns actual infinite sets.
Another reason I'm asking is because I know that if a mathematician is a constructivist or intuitionist, then the axiom of infinity is used as an axiom in their set theory, and I believe this is possible if they interpret that $I$ is a potentially infinite set.
Lastly, and I don't know if it's possible to answer this question, but when Zermelo first proposed the axiom of infinity, did he have in mind that $I$ is an actual infinite set or did he withhold any claims as to whether or not it was an actual or potential infinity?
I'm sorry in advance if this question is not suitable for this stackexchange, but my prior discussion on philosophy stackexchange has led me to confusion as to whether or not $I$ can be interpreted as an actual or potential infinite set, so I was curious to know what some or most mathematicians, especially ones who have no problem with actual infinite sets, consider $I$ to be with respect to the infinite.
So what is $I$ to you?
Comment: I'm not a set theorist. But generally speaking mathematicians view $\mathbb{N}$ as the smallest infinite set. That is every infinite set has a subset for which a bijection with the natural numbers exists. Mathematicians consider this set to be infinite, that is every finite subset is proper. Whether or not such sets correspond to reality is another matter altogether. This is a logical construction that allows us to do our work.
Comment: in case it's helpful, mathematicians also categorize cardinality of sets as countable and uncountable. There is a finer breakdown in the uncountable category as well. The set of real numbers is an uncountable set, and is constructed by looking at infinite sequences of rational numbers and placing them into equivalence classes we ultimately call real numbers. This all relies on thinking of infinite sets as actually infinite.
Comment: The axiom of infinity is an axiom of set theory for all mathematicians, not only constructivists and intuitionists.
Comment: [Axiom of infinity](https://plato.stanford.edu/entries/set-theory/ZF.html): "$∃x[ \emptyset \in x ∧ ∀y(y∈x → \bigcup \{ y, \{ y \} \} \in x)]$". Thus, if we call it $I$ it is clear that **all** the sets "generated" by the axiom are elements of $I$, i.e. they belongs to $I$.
Comment: [Zermelo (1908)](https://books.google.it/books?id=v4tBTBlU05sC&pg=PA204): "There exists in the domain at least one set $Z$ that contains the null set as an element and is so constituted that to each of its elements $a$ there corresponds a further element of the form $\{ a \}$ ... $Z_0$ is the *common component of all possible sets constituted like* $Z$. The set $Z_0$ contains the elements $\emptyset, \{ \emptyset \}, \{ \{ \emptyset \} \}$, and so fort, and it may be called the *number sequence*..."
Comment: @Max I don't think I restricted the axiom to any proper subset of mathematicians, but I mentioned the constructivists and intuitionists as examples of mathematicians who *use* the axiom of infinity, but they do not believe in actual infinite sets as true or meaningful sets.
Comment: @MauroALLEGRANZA I definitely agree that all sets generated by the axiom are in the set. They are in the set due to the logical skeleton of the set, as you provided. Mozibur Ulluh on philosophy stackexchange then said $I$ is a potentially infinite set. However, I think there is a consensus on this site and PSE that there is an interpretation on what the infinite set means in the axiom. One can view it as an iterative process never terminating or a completed entity, it seems. It's because of this interpretative characteristic that it hasn't been cast into serious doubt or rejection as AC.
Comment: @BenedictVoltaire : in maths (as far as I know) there are no processes, and if things are, they have always been and will always be, whatever that means. You could argue that one can view $\Bbb{N}$ as an unending process, but I hardly see how you could do so for uncountable sets such as $P(\Bbb{N})$ or $\aleph_{\omega_1}$. Just enumerating the elements of those sets would get you nowhere
Comment: @BenedictVoltaire : in maths (as far as I know) there are no processes, and if things are, they have always been and will always be, whatever that means. You could argue that one can view $\Bbb{N}$ as an unending process, but I hardly see how you could do so for uncountable sets such as $P(\Bbb{N})$ or $\aleph_{\omega_1}$. Just enumerating the elements of those sets would get you nowhere
Comment: @Max I agree! I was just trying to understand the perspective of of finitists and constructivists. They deny $\pi$ for example as a completed infinity, that is, they don't view it as a real constant. They do believe it has an infinite decimal expansion that can continue iteratively forever, but it doesn't exist as a constant. Same goes for $\sqrt{2}$.
Answer: I, personally, don't even believe that "potential" is a meaningful adjective to attach to "infinity".
Or, more accurately, that the term is a misnomer — when used, what people seem to have in mind is a class of finite things, and there is no upper bound on the sizes of the members of the class.
For example, if someone disbelieved in the infinite divisibility of a Euclidean line and spoke of its point-set as merely being "potentially infinite" set, they aren't talking about its point-set at all — instead, what they are talking about is all of the different you can mark finitely many points on the line.
With the misleading term "potential infinity" discarded, and replaced with the more precisely defined notion of an "unbounded family" of things, the answer to your query is now obvious: the axiom of infinity specifies the existence of one set with a particular property, not a whole family of sets with fragments of that property.
Comment: That's a very good emendation on what people usually mean when they say a potentially infinite set, and I accept that precise definition. But I want to make sure I understand your post correctly, so would you mind elaborating on what you mean by "not a whole family of sets with fragments of that property"?
Answer: Looking in Gregory H. Moore's book "Zermelo's Axiom of Choice", one can find a brief history of the axiom of infinity (pp. 154--155).
Its roots lie with Bolzano, who argued the existence of an infinite set (via a somewhat-diagonal argument, like the Euclidean proof of the infinitude of primes); Dedekind later reformulated this into what we know now as "Dedekind-infiniteness"; and several others have formulated this in one way or another. However, the foundations of mathematics were still shaping, and a lot of this won't pass the test of modern rigor. Zermelo, however, was different, and postulated the axiom by formalizing exactly what it means for a set of "repeated singletons" to exist.
It seems probable that Zermelo had the natural numbers in mind, since at this point Peano's postulates already existed, and so modeling the natural numbers as $0=\varnothing$ and $n+1=\{n\}$ seemed like a natural thing to do. And Zermelo's axiom of infinity essentially postulated the existence of the natural numbers as a set using this modeling.
The modern formulation of Infinity, however, comes in later, when we think about ordinals, and $\omega$ or $V_\omega$ in the von Neumann hierarchy. To a set theorist, "the infinite set" is by all means $\omega$, which is also the natural numbers for all useful purposes in the context of set theory.
As far as the terms "potential" and "completed" or "actual", I think that you're mixing several philosophical approaches here. In the context of real analysis, sets are not of interest, and only real numbers and functions (or sequences) are of interest. Those are, naively, given by various constructions, and you can ask whether or not something is unbounded. In other words, does a function attain arbitrarily high values? If so, it can be seen as potentially infinite. However every valid input has to return a real number, so it cannot be infinite. Therefore "potential infinity" works just fine.
In set theory, however, we take a fixed universe, and argue over it (using what basic assumptions we made on this universe, e.g. a model of $\sf ZF$ or $V=L$ or whatever). So when we look at an infinite set whose existence is guaranteed by the axiom of infinity, we do not look at it as something "to be constructed in parts", but rather something which already exists. We assumed the axiom, and derived (using existential instantiation) the existence of said set. We can prove that this set is also infinite in any "reasonable" definition of infinite, as far as the universe we work inside cares to admit. Which is why we all have the tacit agreement "yes, this set is infinite".
Comment: I am not entirely sure about the timeline there when it comes to the axiom of infinity and the construction of the natural numbers as sets. And I have to go in a bit, so I don't have the time to get into this very deeply right now...


Can we use keyword arguments and curry until all arguments are received?

Question: Can we use keyword arguments and curry a function until all arguments are received in any order?
For example I have this code:
def create_folder_transformer(folder):
    return lambda predicate: lambda file_transformer: map(file_transformer,
        filter(predicate,
            os.listdir(folder)))

I can create a folder_transformer with a specific folder and then mention the`predicate etc. But it has a specific order. However, I don't think it need to be tied to that order.
I would like to achieve something like this instead:

If I pass predicate, I get a partial function that takes folder
and file_transformer as arguments. Now if I supply folder, I get a partial function that takes file_transformer.
If I pass file_transformer, I get a partial function that takes predicate and folder as arguments. Now if I supply predicate, I get a partial function that takes folder.

In short, is there an inbuilt partial creator that recursively keeps on generating partial functions until all inputs are obtained; if inputs are satisfied just execute the code. I believe it is called currying in Haskell and it is how functions perform by default.
Use cases where I think it might help:

When I am transforming a specific folder with n operations,
creating a partial with folder will be better.
When I am having a specific predicate like - filter out mp4 files across many folders - a partial with a predicate like string.endswith(".mp4") will be better.

I read the partial docs but these partials don't return partials if I haven't filled in some args. But since I have declared it as None, I can't expect it either. Ideally, I would like my function itself to behave like that without even worrying about using an additional function like partial i.e it should be baked into my function.
def folder_transformer(folder=None, predicate=None, transformer=None):
    return map(transformer, filter(predicate, os.listdir(folder)))

file_transformer = partial(folder_transformer, predicate=os.path.isfile)

# This gives me a "map" object, but I want another partial takes "transformer".
current_transformer = file_transformer(folder=folder)
# This works, but my question is can I make my function do this automatically.
current_transformer = partial(file_transformer,folder=folder)

Comment: Yes, please read the docs: https://docs.python.org/3.7/library/functools.html#functools.partial
Comment: Any good reason you are reinventing the wheel and not using `functools.partial`?
Comment: @DeepSpace, Can I use keyword arguments like the way I described above?
Answer: I came with a small script for my personal use.
PS: If anyone knows a library that can do something similar, please let me know.
import inspect

def curry(function):
    original_func = function
    original_args = inspect.signature(function).parameters

    def wrapper(**kwargs):
        call = True
        current_args = {}
        for each in original_args:
            if kwargs.get(each):
                current_args[each] = kwargs.get(each)
            else:
                call = False
        if call:
            original_func(**current_args)
        else:
            def partial(**nargs):
                current_args.update(nargs)
                return wrapper(**current_args)
            return partial

    return wrapper

@curry
def foo(a=None, b=None, c=None):
    print(a, b, c)

# first partial
bar_with_a = bar(a=1)
# next partial
bar_with_a_and_b = bar_with_a(b=1)
# next partial
bar_with_a_and_b = bar_with_a_and_b(b=2)
# next partial
bar_with_a_and_b = bar_with_a_and_b(a=2)
# call
bar_with_a_and_b(c=2)


Remote Desktop Connetion Software Detection

Question: I´m using windows server 2012. And I have hyper V with x machines. That people connect to work.
 I have software in that machine, is possible for that software to know if that is a remote connection , is possible for them to query info , and find out about it? Or that the machine I´m using is a virtual machine?
I´m askying this because I don´t want the software company to know that it is being used in remote connection and in a virtual machine. Do I explain myself.
If they can query for that info. What can I do to prevent that?
Any info that anyone can provide me . I will be thankfull.
Comment: So, you want to violate the terms of your licensing agreement? I am sorry, but SF is the **absolutely wrong place** to ask this kind of questions. Please read our [FAQ]. And hire a good lawyer in case you get caught.
Answer: If you're trying to skirt licensing restrictions or supported configuration concerns I suggest you abandon the idea. It is fairly trivial for application software to "detect" it is being executed in a VM and/or over Remote Desktop.
Preventing either would be difficult w/o modifying the application's code. Obscuring the hypervisor's virtual hardware might get you something, but then you're probably talking about modifying the hypervisor (likely in violation of license terms).


Calling function if ajax request is finished

Question: I have a button and 2 links, which makes an ajax request. If a request called by button is finished, I want to show alert. But I don't want to show the alert if I click on some link. This is my code:
HTML:
<button id="ajax">Ajax</button>
link 1
link 2

JS:
$('#ajax').click(function() {
    $("div").load("/echo/js/?js=button");

    $( document ).ajaxStop(function() {
        alert('alert')
    });
})

$('a').click(function() {
    $("div").load("/echo/js/?js=link");
})

http://jsfiddle.net/rgyxzwj6/
Why if I click on the button and then I click some link, it shows the alert? And after first click on the button it shows alert only once. But if I click on the button second time, it shows alert two times. How can I fix that?
Answer: 1. Perform your alert
You should use the callback function of jquery load to perform your alert:
$('#ajax').click(function() {
    $("div").load("/echo/js/?js=button", function() {
        alert('alert');
    });
});

$('a').click(function() {
    $("div").load("/echo/js/?js=link");
});

Callback Function
If a "complete" callback is provided, it is executed after
  post-processing and HTML insertion has been performed. The callback is
  fired once for each element in the jQuery collection, and this is set
  to each DOM element in turn.

from the jquery API and for more information about load(): http://api.jquery.com/load/
Here is the updated fiddle for your case: http://jsfiddle.net/55rpfe0w/
2. the ajaxStop handler
Your code...
$( document ).ajaxStop(function() {
    alert('alert')
});

...the event handler is also called when you do your ajax request with the links.

Whenever an Ajax request completes, jQuery checks whether there are
  any other outstanding Ajax requests. If none remain, jQuery triggers
  the ajaxStop event.

from jquery API: https://api.jquery.com/ajaxStop/
3.the multiple time alert

And after first click on the button it shows alert only once. But if I
  click on the button second time, it shows alert two times. How can I
  fix that?

The reason is, that you set the handler for the event ajaxStop in your click function and every click you do on your button you set another event handler and so:

Any and all handlers that have been registered with the .ajaxStop() method are executed at this time.

from jquery API: https://api.jquery.com/ajaxStop/
Answer: You can pass a function as the second parameter to the load function, this passed function will get called when the load function completes.
If you don't want any function to run, you don't have to pass it anything, just like you're doing in the $('a').click function.
http://jsfiddle.net/rgyxzwj6/1/
$('#ajax').click(function() {
    $("div").load("/echo/js/?js=button", function() {
      alert('alert');
    });
})

$('a').click(function() {
    $("div").load("/echo/js/?js=link");
})


How to migrate a PUT endpoint to a command based app (event sourcing)

Question: I'm almost done with implementing event sourcing using CQRS module of NestJS, but now there is something I don't know how to handle.
Currently, I have cron jobs that send transactions hourly to a my PUT /transactions endpoint. The payload is like this:
{
    "status": "pending",
    "amount": 10000,
    "uid": "test123",
    "transaction_id": "test-transaction1234",
}

When the transaction is sent to the endpoint, I don't know which fields have changed yet.
I have four posible commands: CreateTransactionCommand, UpdateAmountCommand, ApproveTransactionCommand, DeclineTransactionCommand. Two commands could occur at 'the same time', for example and UpdateAdmount and then an ApproveTransaction. The first one should aways occur at first.
How should I handle that? I was thinking about something like this, is it a good solution?
  @Put()
  async createOrUpdate(@Body() dto: Transaction) {
    try {
      await this.transactionsService.createTransaction(dto);
    } catch (e) {
      if (typeof e == ExistingTransactionError) console.error(e);
      else throw e;
    }
    try {
      await this.transactionsService.updateTransactionAmount(dto);
    } catch (e) {}
    if (dto.status === 'approved')
      await this.transactionsService.approveTransaction(dto);
    if (dto.status === 'declined')
      await this.transactionsService.declineTransaction(dto);
  }

Comment: A community like the ddd-cqrs-es discord (https://discord.gg/sEZGSHNNbH) would probably be a better place to ask this question - there isn't going to be an "authoritative" answer, just lots of different trade offs to consider.
Comment: That said, I don't think you are going to enjoy the future maintenance of this kind of solution - control flow via exceptions has a bad reputation, and I think your PUT handler is the wrong place for the logic you show here.
Answer: Okay, I simply did a PUT endpoint, and thanks to the power of the aggregate root, it's pretty easy to know which command I can do.
  @Put()
  async createOrUpdate(@Body() dto: TransactionEventDto) {
    try {
      return await this.transactionsService.createTransaction({
        ...dto.payload,
        status: 'pending',
      });
    } catch (e) {
      if (!(e instanceof TransactionAlreadyCreatedError))
        throw new HttpException(e.message, HttpStatus.BAD_REQUEST, e);
    }
    try {
      const { transaction_id, amount, status } = dto.payload;
      await this.transactionsService.updateTransactionAmount(
        transaction_id,
        amount,
      );
      if (status === 'approved') {
        return await this.transactionsService.approveTransaction(
          transaction_id,
        );
      }
      if (status === 'declined') {
        return await this.transactionsService.declineTransaction(
          transaction_id,
        );
      }
      return;
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST, e);
    }
  }

If the order matter, just use the 'sequential way' of promise (i.e await in chain)