Primes in ring theory

Question: I have this definition of primes in my lecture notes and I don't understand it i was wondering whether someone could explain it to me
$p$ is prime if and only if for all $a$, $b$ that are elements of $R$, we have $p \mid ab$ implies $p \mid a$ or $p \mid b$.
See I am rather lost by this definition.
Comment: $ab$ aren't digits, it's a product of $a$ and $b$.
Comment: Have you tried with the usual prime numbers to see if they fulfill that definition?
Comment: I have tried, but I'm attempting wrong, say I take 3 as a prime number 3|27 is true but, but 3 does not divide 2 or 7? am i missing something here?
Comment: The defining property of primes that you're used to from elementary school (the only divisors are itself and $1$) is in ring theory (with a suitable generalisation) called "irreducible" instead. For nice enough rings (like the integers) the concepts of prime and irreducible coincide. However, in general they are two different concepts.
Comment: @TrevorGunn Thank you that makes so much sense:)
Comment: I thought you might got confused about prime with irreducible. https://en.wikipedia.org/wiki/Irreducible_element You could write down the definition of irreducible and primes and compare them. Their exact meaning based on the ring(ID etc.) they were the same in UFD.
Answer: Have you tried seeing why composite numbers don't fit that definition?
For example, take $p = 14$, $a = 2$, $b = 49$. Then $ab = 98$ is divisible by $p$. However, $2$ is clearly not divisible by $14$, nor is $49$ divisible by $14$ either. No surprise, given that $14$ is composite, not prime.
Now consider $p = -7$, $a = 2$, $b = 49$. Then $ab = 98$ is divisible by $p$, just like before. Although $2$ is not divisible by $-7$, $49$ is. We can choose other $a$ and $b$ such that $ab = 98$, but it is guaranteed that in each case we will find that $-7$ is a divisor of either $a$ or $b$, if not both. Indeed $-7$ is a prime number.
Working in $\mathbb{Z}$ this might not seem like such a big deal. Look at almost any other number ring and this becomes a very important distinction.
Answer: When $R$ is a UFD (unique factorization domain, e.g. $R = \mathbf Z$) then the following two concepts are equivalent for an element $p \in R$ and $p$ is not zero and $p$ is not a unit:

$p$ is irreducible, meaning whenever $p$ is written as a product of two other elements of $R$, i.e. $p = ab$, then either $p \mid a$ or $p \mid b$. Necessarily, if $p$ divides $a$ or $b$ the other has to be a unit in $R$. For example, if $p \mid a$ and we write $a = pc$ for some $c \in R$ then $p = ab = pcb$ so $1 = cb$ and hence $b$ has an inverse, namely $c$.
$p$ is prime, meaning whenever $p$ divides a product of two other elements, i.e. $p \mid ab$, then $p \mid a$ or $p \mid b$.

The classical definition of a prime number is an irreducible element of $\mathbf Z$ and prime numbers are indeed prime elements as defined above.
Historically, when attempting to prove Fermat's Last Theorem ($x^n + y^n = z^n$ has no solutions for $n \ge 3$ except when one of $x, y$ or $z$ is zero) mathematicians (such as Dedekind and Kummer) noticed that when $p$ is prime, we can factor $x^p + y^p$ as
$$ (x + y)(x + \zeta y)\cdots(x + \zeta^{p-1} y) \tag{1}$$
where $\zeta$ is a principal $p$-th root of unity. (It was already known that if Fermat's Last Theorem could be proved for prime exponents, it holds for all exponents.)
What was noticed is that if $x^p + y^p = z^p$ then $(1)$ and $z^p$ are two different factorizations of $z^p$. The issue is, $\mathbf Z[\zeta]$ isn't always a UFD.
This prompted a more serious look at rings which aren't UFDs but still come from adjoining roots of polynomials, such as $\zeta$ to the integers.
For example, in $\mathbf Z[\sqrt{-5}]$ we have non-unique factorization:
$$ 21 = 3 \cdot 7 = (1 + 2\sqrt{-5}) \cdot (1 - 2\sqrt{-5}).$$
The idea to solve this is that somehow there were a larger class of "ideal numbers" in which we get a unique factorization. That is, there would be "ideal primes" $\mathfrak{p}_1, \mathfrak{p}_2, \mathfrak{p}_3, \mathfrak{p}_4$ such that
$$ 3 = \mathfrak{p}_1\mathfrak{p}_2, 7 = \mathfrak{p}_3\mathfrak{p}_4 $$
and
$$ (1 + 2\sqrt{-5}) = \mathfrak{p}_1\mathfrak{p}_3, (1 - 2\sqrt{-5}) = \mathfrak{p}_2\mathfrak{p}_4 $$
these "ideal primes" give us a unique factorization of $21$ into "ideal numbers".
Well, when you look at what properties you want of an "ideal number" you find that they should basically be defined in terms of divisibility. Here, $\mathfrak{p_1}$ and $\mathfrak{p_2}$ "divide" $3$.
Carrying on with this idea, you realize that an "ideal element" $\mathfrak{a}$ isn't anything more than the set of things it divides:
$$ \mathfrak{a} ``=" \{a \in R : \mathfrak a \mid a\}. $$
This is where the definition of an ideal inside a ring came from.
Of course, in a ring that isn't a $UFD$, talking about "factoring numbers" isn't well-defined. So what mathematicians did is move away from the notion of irreducible elements to the notion of prime elements which can be phrased naturally in terms of ideals. Specifically, an ideal $\mathfrak{p}$ is prime if whenever $ab \in \mathfrak p$ (in terms of "ideal primes" this says that $\mathfrak p \mid ab$) then either $a \in \mathfrak p$ or $b \in \mathfrak p$.
In a UFD, all these notions are the same:
$p$ is irreducible if and only if $p$ is prime if and only if the ideal $(p)$ is a prime ideal.

This explanation of "ideal elements" is based off of Chapter 1.3 in Neukirch's Algebraic Number Theory.

Primes in ring theory


I need to count the number of cells that say something from another workbook

Question: I'm creating a spreadsheet on google sheets and need to count how many cells contain certain information on another workbook, any ideas on what formula I should use? I've tried combining countif and importrange but can't seem to get it to work.
It would also be really useful if I could get the formula to match the date at the top of the column that I'm referencing to the date of the column on the spreadsheet I'm creating
This is the last formula I tried:
=Countif(importrange(link,"Resource Planner 2021!HL:HL"),"<>Day Off")
Comment: If you run just IMPORTRANGE() alone, does it pull in the correct dataset?
Comment: Not as yet but I've just found out the document I'm referencing is an excel import
Answer: You could use QUERY and feed it the IMPORTRANGE as data. Then use something like <code>=QUERY(IMPORTRANGE(link;"Resource Planner 2021!HL:HL");"select Sum(ColX) where ColX = "Day Off"";1)</code>
In case you could provide a example or copy of the sheet in question I could try to make a more specific sugestion.


Satisfying Three Dimensional Coordinate Systems

Question: In Multivariable Calculus, what is the best way of finding what points P(x,y,z) satisfy for example:
$$x^2 +y^2 = 4,$$ and $$z=3 $$
I've been told graphing the two equations and finding an intersection does it but is there a simpler way, algebraically maybe?
Comment: The "simplest" way is to realize that $x^2 + y^2 = 2^2$ is the equation (in 2D) of a circle of radius $2$ (_not_ disc!).  Since $z$ isn't mentioned, the "height" (if you take $z$ to be "height") can be anything thus you repeat this circle for every $z$ value, which makes a "tube"--the lateral surface of a cylinder of radius $2$ perpendicular to the $xy$-plane and centered about the $z$-axis.  Now that $z$ _is_ specified, it's the circle of radius $2$, parallel to the $xy$-plane at "height" $z = 3$.
Comment: And, fyi, this is already stated in the "algebraic" way.  If I give you a random point, you can plug in and tell me whether or not that point satisfies these two equations.
Comment: @Jared Mmmm I see, that makes a lot of sense, I was just having trouble visualizing it. Would you want to write that as an answer so I can upvote it? And thanks a bunch!
Answer: Because these two equations do not share variables, you shouldn't need to solve it. The solution set is just $z=3$ and any values of $x$ and $y$ that satisfy $x^2+y^2=4$. It's like asking someone to solve the equations $x=1$ and $y=2$. Generally speaking though, finding algebraic solutions is often hard unless you have a system of linear equations. You could use a Root-Finding Algorithm like Newton's Method in general to get a numerical solution.


What is the formal definition of an "atomless" distribution?

Question: The use of atomless (continuous) distributions is ubiquitous in applied works. While the general idea is somewhat clear to me, I was looking for a formal definition or some useful references on the matter. Any help would be greatly appreciated.
Comment: There are many equivalent definitions. The name may come from the fact that the continuous distributions are precisely those with everywhere continuous distribution functions. Any book on probability and statistics (except for those introductions that avoid as much math as possible) will discuss this: pick your favorite.
Answer: Given a measure $\mu$ and measurable sets $\mathcal{M} \subseteq \mathcal{P}(X)$, a set $A \in \mathcal{M}$ is said to be an atom in the measureable space $(X,\mathcal{M},\mu)$ if
$\mu(A) > 0$ and $\mu(B) \in \{0,\mu(A)\}$ for all $B \subset A, B \in \mathcal{M}.$ The measurable space is atomless, if there is no such $A \in \mathcal{M}$. That is, an atom is a set of positive measure which contains no nontrivial smaller measurable sets. See https://en.wikipedia.org/wiki/Atom_(measure_theory) .
An atomless distribution, I guess, is one which generates an atomless measure on the underlying probability space.A google search on the terms "measure theory" and "atom" yields a couple of other useful references.
Comment: @mrb Why not? I assume you meant $\mu(0)$ as shorthand notation for $\mu(\{0\})$. Let $A=\{0\}$ and $B\subset A$. Then, either $B=A$ or $B=\emptyset$. In the first case $\mu(B)=\mu(A)$ and in the second case $\mu(B)=0$. Thus for any $B \subset A$ we have $\mu(B) \in \{0,\mu(A)\}$ and thus $A$ is an atom per the definition given in this answer.
Comment: So, if for instance, the probability space is defined on the interval $[0,1]$ and the probability measure on the lower bound of the interval is $\mu(0)>0$. Then, it is not an atom according to your definition, isn't it?


How to properly code UNICODE FONT ICONS so they render on all browsers

Question: I want to add Unicode icons to a website, and only unicode -No custom font files.
I know I can do something like:
<code>[class^=icon-facebook]:before {
    content: "\00066";
}
[class^=icon-twitter]:before {
    content: "\01F426";
}
[class^=icon-phone]:before {
    content: "\01F4DE";
}
[class^=icon-fax]:before {
    content: "\01F4E0";
}
[class^=icon-email]:before {
    content: "\01F4E7";
}
[class^=icon-link]:before {
    content: "\01F517";
}
[class^=icon-pay]:before {
    content: "\01F4B8";
}
[class^=icon-dollar]:before {
    content: "\01F4B5";
}
[class^=icon-yen]:before {
    content: "\01F4B4";
}
[class^=icon-save]:before {
    content: "\01F4B0";
}
</code>
jsFiddle
However, I am reading that some browsers won't render the "icon" (Unicode character) properly. Sometimes browsers would display an empty square instead of the Unicode character.
How can I code my CSS to prevent that from happening?

No custom fonts
No images
Comment: If you don't want to use a font that supports the character and don't want to use an image of the character, then what you're asking for is not possible.
Comment: Use images instead of unicode characters...?
Comment: What  @一二三 said: you apparently want a browser to display a particular glyph when  there is no copy of that glyph on the local computer and you are not willing to give it one (by image, SVG or embedded font). This is quite obviously impossible.
Comment: Take a look at this question: http://stackoverflow.com/questions/22380974/fallback-for-using-unicode-with-css
Comment: You want to prevent the square from appearing? Even if the browser doesn't support the character you chose?
Comment: @mauricio-moraes Yes
Comment: Either use a font you know that it supports universally the unicode chars, or use images.
Comment: @mauricio-moraes Let's say I want to use `font-family: Arial, Helvetica, Tahoma, Verdana, sans-serif;`  What's the next step? Can you post it as an answer?
Comment: @一二三 I do not want to use a custom font. Common web safe fonts that support UNICODE characters are OK.
Comment: If "no custom fonts" means "no web fonts I serve up with @font-face style rules", you have to check that Arial, Helvetica, Tahoma, and Verdana cover *every* UTF-8 glyph you're using as an icon (you can't count on sans-serif).
Comment: @HonoreDoktorr How can I check if a font covers a desired UTF-8 glyph?
Comment: If you don't mean programmatically, [fileformat](http://www.fileformat.info/info/unicode/char/1f4e0/index.htm) is pretty useful.
Comment: @bobince What I want to accomplish is to know how can I have Unicode characters (AKA icons/glyphs), with local fonts and prevent them from showing the wrong way...I am not sure if it's explained?
Answer: i understand that you dont want to make an "extra" call for a font download or image download. if you insist on keeping it all in the CSS you could try Base64 for example:
<code><style type="text/css">
div.image {
    width:            14px;
    height:           14px;
    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpGMjdBMjVGOTU2NTAxMUUyOUFBN0EzOUYwOEVBMkQ1MCIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpGMjdBMjVGQTU2NTAxMUUyOUFBN0EzOUYwOEVBMkQ1MCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkYyN0EyNUY3NTY1MDExRTI5QUE3QTM5RjA4RUEyRDUwIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkYyN0EyNUY4NTY1MDExRTI5QUE3QTM5RjA4RUEyRDUwIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+AND5IAAAAHBJREFUeNpi/P//P4OJiQkDGmAG4r9AzATl/4Oy/zHgAWfOnIFrOAjE/5HwHyj9F4r/I9G48CEGJBdQA4AMZWCBcuypZSo1XUhbAw8SCHBi8EFkA/9TwXH/kCPFYeRFygEqRMoBmuQURlDhQE0AEGAA1LJE38CAHLYAAAAASUVORK5CYII=');
}
</style>
</code>
This will place the hamburger menu icon.
Here is a working example: Demo
It will surely look exactly the same in all browser because it is an image and not a font.
you can make any png image into this here:
PNG to Base64
Good luck :)
Answer:
However, I am reading that some browsers won't render the "icon"
  (Unicode character) properly. Sometimes browsers would display an
  empty square instead of the Unicode character.
How can I code my CSS to prevent that from happening?

I am not sure if you are meaning that you want to prevent rendering the empty square only or you want the font to be the same for all browser.
If you mean you want the font to be the same for all browser, and don't want to include any font file or image file, all you can do is choose a font that is supported by all browser and test if they are shown correctly.
Here is a tool that you may try for testing your icon on every possible browser:
https://spoon.net/browsers
Or if you just want to know if the character is correctly shown and in case not you want to handle the error by another way, here is a way that you may find useful.
https://stackoverflow.com/a/1912045/1273587
Answer: If a browser supports Unicode at all, it will support all character codes. But not all fonts will have character glyphs for all Unicode characters.
So, to get support for the characters that you want, you would need to use a font (in your case, the web safe ones) that has those characters, in formats used by all different operating systems.
Answer: till today there is no single web-browser is built which will comply all the standards and meet all our technical and design requirements.
Every browser has it's own capabilities and limitations. That's why, we developers try to understand those limitations and come out with alternate solutions so that our applications work as seamlessly and as perfect as possible in all the browsers and in all versions. Writing the cross-browser compatible code is an skill/art.
The day when all browsers gets standardised and follow the same rule, then the life of webdevelopers(specially HTML CSS Developers) will be very easy and may not have much work/challenges too !! ;-)
What you are trying to achieve is very optimistic solution but in reality it is just not possible. It's hard truth but you have to digest it and should focus on other ways as how to achieve your goals with the available alternate solutions (Which you already know)


Highcharts scrollbar not working properly

Question: I have columnrange graph set up which is working perfectly fine. I grab the data required using ajax and recreate the graph everytime on user click event. I am trying to add x-axis scrollbar but it is not workin gporperly. I have to change the js import to highstock. and if I chnage the min value to any number it does not work. The data.cat brings back 32 categories, without the scrolling feature it all looks very squashed.
here is the graph
$('#projects').highcharts({
                                        'chart':{
                                            'type':'columnrange',
                                            /* events: {
                                                 load: function (event) {
                                                     $('#projects').width(800);
                                                     }
                                                }*/
                                        },
                                        'exporting':{
                                            'enabled':true
                                            },

                                        'title':{
                                            text:'Projects in progress, '+data.asaarea
                                            },
                                        xAxis:{
                                            categories:data.cat,
                                            min: 10
                                            },
                                        'yAxis':{
                                            'title':'Date',
                                            'type':'datetime',
                                            'dateTimeLabelFormats':{
                                                'month':'%b %Y'
                                            },
                                            'min':Date.UTC(2010,00,01)
                                        },

                                        'tooltip':{
                                            formatter: function(){
                                                var percentage = '';
                                                if(this.series.name == "Actual"){
                                                    var data = "PROJECT="+this.x + "&StartDATE="+this.point.low;

                                                    var percent = $.ajax({
                                                        url: "index.php?r=ViewWebprojectreport/getPercent",
                                                        type: "GET",
                                                       dataType:"html",
                                                        data: data,
                                                        global: false,
                                                        async:false,
                                                        success:function(data){
                                                            return data;
                                                        }
                                                    }).responseText;

                                                    percentage = percent +'% Complete
';
                                                }
                                                return  percentage + '' +this.series.name + ': '+ Highcharts.dateFormat('%e %b, %Y', this.point.low) + ' - ' +  Highcharts.dateFormat('%e %b, %Y', this.point.high) +'
' ;
                                                  }
                                            },
                                        'legend':{
                                            'enabled':true
                                            },
                                        credits: {
                                            enabled: false
                                        },
                                        scrollbar: {
                                            enabled: true
                                        },
                                        'series':[
                                                    {
                                                    'name':'Forecast',
                                                    'data':data.data,
                                                    'color': 'blue'
                                                    },
                                                    {
                                                    'name':'Actual',
                                                    'data':data.complete,
                                                    'color': 'green'
                                                    }
                                                ]

                                    }); // end of columngraph

on jsfiddle
Comment: But what do you expect? Highcharts doesn't calculate anything to make chart wider just because you enabled scrollbar.. I think you need to set for example `max: categories.length > 5 ? 5 : categories.length` so you will have condition if set max or not (and the same for scrollbar). Where categories is your variable with all categories.
Comment: What doesn't work? For example `min: 25`, see: http://jsfiddle.net/4GYu3/2/ works fine. Regarding scrollbar - you are right, you need to use Highstock.
Comment: why is it `min:25`? what if I dynamically change the number of categories and data in series. with `min:25` it does not display properly?
Comment: Have you checked this answer if it works for you? http://stackoverflow.com/a/11464098
Comment: Agreed with pawel's comment. For enabling scrollbar we need to first add the highstock.js and second thing we need to add (scrollbar:{enabled:true} and add the max and min attribute in xAxis:. It should work.
Answer:

I have included necessary jscripts. To make a dynamic scroll bar i used JQuery to increase div length. Containers of the graph

Adjust size as appropriate
if(data.type == "column"){
        $('#weekly_status_graph_line').hide();
        $('#weekly_status_graph').show();
        columnGraph(data);
    }else if(data.type == "line"){
        $('#weekly_status_graph').hide();
        $("#weekly_status_graph_line").css("width","1830px");
        $("#weekly_status_graph_line").css("margin-left","-0px");
        $('#weekly_status_graph_line').show();
        lineGraph(data);
    }


How to get a lot of if statements more readable in Python

Question: I recently practiced python and I was finding myself get involved with a lot of if statements for a simple rock paper scissors game it looks like this:
and my question is how i get my code more efficient and more friendly to write and read
 while True:

        player_choice = raw_input("\n1-Rock\n2-Paper\n3-Scissors\n{} choose a number:".format(name))
        player_choice = int(player_choice)

        if player_choice == 1:
            player_choice = Choices.rock
        if player_choice == 2:
            player_choice = Choices.paper
        if player_choice == 3:
            player_choice = Choices.scissors

    # Getting the cpu choice.
        cpu_choice = random.randint(1, 3)
        if cpu_choice == 1:
            cpu_choice = Choices.rock
        if cpu_choice == 2:
            cpu_choice = Choices.paper
        if cpu_choice == 3:
            cpu_choice = Choices.scissors

        if player_choice == cpu_choice:
            print"\n Its a Tie!\n!"

        if player_choice == Choices.paper and cpu_choice == Choices.rock:
            print"\n Congratulations!\n{} you won!".format(name)

        if player_choice == Choices.scissors and cpu_choice == Choices.paper:
            print"\n Congratulations!\n{} you won!".format(name)

        if player_choice == Choices.rock and cpu_choice == Choices.scissors:
            print"\n Congratulations!\n{} you won!".format(name)

        if cpu_choice == Choices.scissors and player_choice == Choices.paper:
            print"\n Too bad!\n{} you lost!".format(name)

        if cpu_choice == Choices.paper and player_choice == Choices.rock:
            print"\n Too bad!\n{} you lost!".format(name)

        if cpu_choice == Choices.rock and player_choice == Choices.scissors:
            print"\n Too bad!\n{} you lost!".format(name)*

Comment: I think **_readable_** is really more appropriate the efficient in the context of you question. Because without being readable it is efficient especially if you were using `elif`.
Comment: So what's `Choices`, is it a `Enum` subclass?
Answer: Your if statements can be replaced by dictionaries. For example, mapping an integer to a specific Choices attribute can be done with a dictionary like this:
choices = {1: Choices.rock, 2: Choices.paper, 3: Choices.scissors}

Now you can use
player_choice = choices[player_choice]

and
cpu_choice = random.choice(choices.values())

From an encapsulation point of view, it should really be the responsibility of the Choices object to handle this mapping. If you were to use an actual enum.Enum object (requires Python 3 or the installation of the enum34 backport package) then you could just use:
player_choice = Choices(player_choice)

but depending on how you defined Choices, you could give it a __call__ method that basically uses the above mapping to give you the same result.
Next, you could use a dictionary to determine winners:
# if a player picks the key, and the opponent has picked the value,
# then the player wins.
wins_against = {
    Choices.rock: Choices.scissors,
    Choices.paper: Choices.rock,
    Choices.scissors: Choices.paper,
}

then determine the winner:
if player_choice == cpu_choice:
    print"\n Its a Tie!\n!"
elif wins_against[player_choice] == cpu_choice:
    print"\n Congratulations!\n{} you won!".format(name)
else:  # not the same, and not a win, so the player lost
    print"\n Too bad!\n{} you lost!".format(name)

That mapping could also be part of your Choices enumeration objects however; give those a wins_against attribute:
if player_choice == cpu_choice:
    print"\n Its a Tie!\n!"
elif player_choice.wins_against == cpu_choice:
    print"\n Congratulations!\n{} you won!".format(name)
else:
    print"\n Too bad!\n{} you lost!".format(name)

If you were to use the enum library, the code could become:
from enum import Enum

class Choices(Enum):
    rock = 1, 'scissors'
    paper = 2, 'rock'
    scissors = 3, 'paper'

    def __new__(cls, value, win_against):
        instance = object.__new__(cls)
        instance._value_ = value
        instance._win_against = win_against
        return instance

    @property
    def win_against(self):
        return type(self)[self._win_against]

 while True:
    options = '\n'.join(['{}-{}'.format(c.value, c.name) for c in choices])
    player_choice = raw_input("\n\n{} choose a number:".format(
        options, name))
    try:
        player_choice = int(player_choice)
        player_choice = Choices(player_choice)
    except ValueError:
        print "Not a valid option, try again"
        continue

    cpu_choice = random.choice(list(Choices))

    if player_choice is cpu_choice:
        print"\n Its a Tie!\n!"
    elif player_choice.wins_against is cpu_choice:
        print"\n Congratulations!\n{} you won!".format(name)
    else:  # not the same, and not a win, so the player lost
        print"\n Too bad!\n{} you lost!".format(name)

Answer: You should use if/elif/else statements - it will only compare the conditionals until a true value occurs.
And you may want to put an error message if the user inputs some other value
    if player_choice == 1:
        player_choice = Choices.rock
    elif player_choice == 2:
        player_choice = Choices.paper
    elif player_choice == 3:
        player_choice = Choices.scissors
    else:
        print "Invalid choice"

Comment: Better than the code from the question, but far from perfect.


ActionLink does not create the right link

Question: This is super straight forward, but somehow it is not working.  Can you please take a look?
on my page I have:
<%= Html.ActionLink("My Recipes", "Index", "Recipes")%>

and i have the following controller:
namespace MyWebSite.Controllers
{
    public class RecipesController : Controller
    {
        //
        // GET: /Recipes/

        public ActionResult Index()
        {
            return View();
        }

the html that is generated is:
My Recipes

while I expect it to be:
My Recipes

My controller is named: RecipesController.cs and is in the Controllers folder with all my other controllers?
Whats wrong?
Many thanks!
Comment: You have messed up with your routes, haven't you? Show them please so that this could be confirmed.
Comment: yup. thanks . will fix you answered it!
Comment: posted my comment as answer so that you can accept it and close this question.
Comment: @Darin, write your comment as an answer and I will mark it as such
Comment: posted as answer, feel free to accept once the timeout expires.
Answer: You seem to have messed up with your routes.


exposed sort not defaulting to "any"

Question: I have an exposed sort on my view by "has taxonomy term with depth".  I want it to default to "Any " but it keeps on defaulting to one of the choices.  Is there a way to make it default to Any? I dont see the option for the default choice.
thanks.
Answer:
Did You checked if the exposed sort is not "required"? (there should be a checkbox that it's not mandatory field)
Did you checked if the "remember last chosen option" is unchecked?

Did You highlighted any possible option in configuration of this sorting?

EDIT:

I'm talking about this options list in 3. It should not be highlighted to default to ANY
EDIT 2
Comment: Ok, first of all i guess you mean exposed filter - not exposed sorting - correct me please if i'm not right.
Second: i have just checked and in this filter configuration You have the list of terms. Leave blank (not highlighted) for all. Otherwise, the first selected term will be the default instead of "Any".
Comment: yes to number 1 and 2 I dont know what you mean by number 3
Comment: I added a picture, the option that says "Add select all/none links" is disabled , wont let me check it
Comment: Oh no - i'm talking about this certaing filter field (first column in Views below FILTER CRITERIA label).  :)
Comment: Hi I dont know what yo mean by that first column in views before the filter criteria label.  there is no column before that
Comment: I added a picture of how i set up the choices .. I dont see any way to make it defautl to "any"
Comment: "Below" -> i added an image for You :)
Comment: ok, great - not You have to deselect all options in "Select terms from vocabulary Event Type"
Comment: BTW. You can deselect options by clicking them while holding CTRL
Comment: If I deselect all of the options I can no longer see the query string that says ?tid=   and I need that .

exposed sort not defaulting to "any"


glue job times out when calling aws boto3 client api

Question: I am using glue console not dev endpoint. The glue job is able to access glue catalogue and table using below code
datasource0 = glueContext.create_dynamic_frame.from_catalog(database =
"glue-db", table_name = "countries")
print "Table Schema:", datasource0.schema()
print "datasource0", datasource0.show()

Now I want to get the metadata for all tables from the glue data base glue-db.
I could not find a function in awsglue.context api, therefore i am using boto3.
client = boto3.client('glue', 'eu-central-1')
responseGetDatabases = client.get_databases()
databaseList = responseGetDatabases['DatabaseList']
for databaseDict in databaseList:
    databaseName = databaseDict['Name']
    print ("databaseName:{}".format(databaseName))
    responseGetTables = client.get_tables( DatabaseName = databaseName,
    MaxResults=123)
    print("responseGetDatabases{}".format(responseGetTables))
    tableList = responseGetTables['TableList']
    print("response Object{0}".format(responseGetTables))
    for tableDict in tableList:
        tableName = tableDict['Name']
        print("-- tableName:{}".format(tableName))

the code runs in lambda function, but fails within glue etl job with following error
botocore.vendored.requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='glue.eu-central-1.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to glue.eu-central-1.amazonaws.com timed out. (connect timeout=60)'))
The problem seems to be in environment configuration. Glue VPC has two subnets
private subnet:  with s3 endpoint for glue, allows inbound traffic from the RDS security group. It has
public subnet: in glue vpc with nat gateway. Private subnet is reachable through gate nat Gateway. I am not sure what i am missing here.
Comment: Can you verify if 443 port is open to internet as it requires other services for it to work and also check try passing the region along with client = boto3.client('glue')
Comment: yes the port 443 is open and i have added the region, still times out after 15 minutes and the job fails.  the security group of the glue vpc looks like this. i have allowed almost all traffic for testing purpose but still cannot connect glue using boto3
All TCP TCP 0 - 65535 0.0.0.0/0
All TCP TCP 0 - 65535 self reference
PostgreSQL TCP 5432 Sg of the peered VPC
All traffic All All Self referencing group
All traffic All All Sg of the peered VPC
Comment: Hi @Uraish did you find a solution for this? I'm facing the same problem and would very much appreciate some help. Thanks.
Comment: Same issue here, @Uraish if you found a solution, please update. Thanks!
Answer: Try using a proxy while creating the boto3 client:
from pyhocon import ConfigFactory
service_name = 'glue'

default = ConfigFactory.parse_file('glue-default.conf')
override = ConfigFactory.parse_file('glue-override.conf')

host = override.get('proxy.host', default.get('proxy.host'))
port = override.get('proxy.port', default.get('proxy.port'))

config = Config()

if host and port:
    config.proxies = {'https': '{}:{}'.format(host, port)}

client = boto3.Session(region_name=region).client(service_name=service_name, config=config)

glue-default.conf and glue-override.conf are deployed to the cluster by glue while spark submit into the /tmp directory.
I had a similar issue and I did the same by using the public library from glue:
s3://aws-glue-assets-eu-central-1/scripts/lib/utils.py
Comment: I have not found doc about that. Where are those docs documented.
Answer: can you please try the boto client creation as below by specifying the region explicitly?
client = boto3.client('glue',region_name='eu-central-1')

Comment: I have explicitly specified region, you can also see it in the error log.                                         botocore.vendored.requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='glue.eu-central-1.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to glue.eu-central-1.amazonaws.com timed out. (connect timeout=60)'))
Answer: I had a similar problem when I was running this command from Glue Python Shell.
So I created endpoint (VPC->Endpoints) for Glue service (service name: "com.amazonaws.eu-west-1.glue"), this one was assigned to the same Subnet and Security Group as the Glue Connection which was used in the Glue Python Shell Job.


Implement Strategy Pattern in C++ without Pointers

Question: My goal is to have a C++ Implementation of the Strategy Pattern without manual memory allocation. I do not feel like it ought to be necessary in the example that I give, conceptually speaking. Also, manual memory management is prone to errors. Keep in mind that my example is just an MWE, in reality all objects are more complicated and manual memory management often introduces bugs.

In the below example, the class Base needs to be given a Strategy to be constructed, which it will use to produce the output in its method getStrategyDecision(). Of course, it can not be given a Strategy because that class is abstract, so this argument has to be a reference. For my above reasons, it is not a pointer.
The following code does compile, but only because const has been added in several places.
class Strategy {
public:
    virtual int decision() const = 0;
};

class AlwaysZero : public Strategy {
public:
    int decision() const { return 0; }
};

class Base {
private:
    Strategy const &strategy;
public:
    Base(Strategy const &s) : strategy(s) {}

    int getStrategyDecision() {
        return strategy.decision();
    }
};

class Main : public Base {
public:
    Main() : Base(AlwaysZero()) {}
};

int main ()
{
    Main invoker;
    return invoker.getStrategyDecision();
}

If you remove the const qualifiers, it fails because in the constructor of Main, passing the temporary object AlwaysZero() to the reference argument of the constructor of Base is illegal.
I could understand that error, but

Why does it work when everything is const? This seems to suggest it should work without const equally well and I am just missing something.
I do not even want a "temporary" object, the only reason I have to do this is because I cannot pass a Strategy itself, because the class is abstract.

Again, I know I could solve this by making the variable strategy a pointer to a Strategy and passing a new AlwaysZero() to the Base constructor. This is what I do not want, as explained above.

My question is twofold. First, I want to know why my example compiles, when it does not without const. I want to understand what is going on here.
Secondly, I would like to know if this example can be modified so that strategy is no longer const (and it works), but without using any kind of pointer. Only if the answer to this second question is "no", I will start looking for clever ways to avoid the problem (such as smart pointers, as suggested in the comments).
PS: I use g++ as a compiler. It might or might not matter.
Comment: A const reference prolongs the life of a temporary. See http://stackoverflow.com/q/2784262/3422652 and https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/. The same is not true of a non-const reference.
Comment: Why not use smart pointers such as unique_ptr? More or less everything you are worried about regarding "Manual memory management" will go away but you will keep pointer semantics and behaviours.
Comment: @const_ref: That is a very reasonable suggestion, thanks. However, I would only use it if the answer to the question is *"no"*, i.e. it is strictly impossible to do this without pointers. I am also quite curious as to why this example works with `const` and not without it, i.e. I really want to understand what is going on here.
Comment: Fair enough, might want to update your question to say so. Smart Pointers arent what I would class as manual memory management :)
Comment: @const_ref: Good point, done.
Comment: Just to be clear, you can use pointers without memory management.
Comment: @ChrisDrew: Okay, but why? I read through both the answer and the linked article, they simply restate what I already observed. **Why** can't C++ prolong the lifetime for non-`const` references, or rather, why was it decided in the standard that it does not? Also, if you have a good suggestion on how to do this with pointers but without calling `new`, by all means, please post it.
Answer: The reason your code compiles is that a const reference prolongs the life of a temporary but a non-const reference does not. See https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ for a detailed explanation.
As for why the C++ standard says a non-const reference doesn't prolong the life of a temporary. As explained here, non-const references can't be bound to temporaries in the first place. See here for a simple example of why.
So, your technique should work fine. But if you want some other options...
Strategy Template
template<typename T>
class Base {
private:
    T strategy;
public:
    Base(const T& s) : strategy(s) {}

    int getStrategyDecision() {
        return strategy.decision();
    }
};

class Main : public Base<AlwaysZero> {
public:
    Main() : Base(AlwaysZero()) {}
};

Non-owning Pointer
You can use pointers without manual memory management. As long as they are non-owning pointers.
class Base {
private:
    Strategy *strategy;
protected:
    void setStrategy(Strategy& s) { strategy = &s; }
public:
    int getStrategyDecision() {
        return strategy->decision();
    }
};

class Main : public Base {
    AlwaysZero my_strategy;
public:
    Main()  { setStrategy(my_strategy); }
};

Comment: The template version is a reasonable workaround, but I still do not understand why `const` references can prolong the lifetime of an object but others cannot. I simply do not understand the deeper reason for this. For your second suggestion, the problem for me here is that the code no longer guarantees that `Base` always has a functional strategy attached to it. The pointer could be `NULL`, in your particular version any child of `Base` might simply decide to not call `setStrategy` at all.
Comment: For strategies that does not hold its state it might be simpler to just call static: T::decision()
Comment: @Maciej Sure, there are number simplifications that could be made in this case but as OP said their real situation is much more complicated I avoided making them.
Comment: @JeskoHüttenhain I've added some links that try to explain *why* const references can't prolong the lifetime of a temporary object.
Comment: Alright! I think I got it now. I can't say I am happy with it, but I understand much better now. Thanks for your patience! +1 and Accept.


Is alpha cumulated in ordinal regression?

Question: My outcome is an ordinal variable having 4 levels. I did an ordinal regression and get one universal beta-coefficient describing each level change.
If I do 3 logistic regressions on each level change, I would have an alpha-error of 3 * 5% (multiple testing)
My question: Is there such a cumulation of alpha error in ordinal regression models (proportional odds or continuation ratio), too?
Answer: If you are using the ordinary parallel forms of proportion odds or CR models, the restrictions imposed on those models (equal slopes assumptions) concentrates the effects into a single parameter if the predictor is linear.  There is no extra type I error.  This is a form of borrowing information across $Y$ levels.
Comment: No, then all bets are off.  It is best for those models to do joint (composite; chunk) tests grouping all the parameters that go with each predictor.  The degrees of freedom in such tests is equal to the number of unconstrained slopes, which gives a perfect multiplicity adjustment.  And if you estimate cutoff-specific effects of variables or make graphical judgments doing same, you'll need to estimate the effective degrees of freedom to do the multiplicity adjustment.
Comment: thx for your answer. is this still true in "partial proportional models", where the equal slopes assumption does not hold for one predictor, and where the model gives for that predictor a coefficient for each level change (while giving universal coefficients for any other predictor)?


Checking if column value == TRUE in php and mysql

Question: I'm trying to create a menu that will only populate links based on what the user has subscribed to. Basically I will be using php to check the user against a table that will contain his/her email + registered courses in a boolean format ie:
email          | course 1 | course 2 | course 3|
email@example.com   TRUE       FALSE       TRUE

I want to create an if statement that if course 1 = true WHERE email = firstname.lastname@example.com then echo some html
else check for course 2, etc.
What I'm having trouble with is how would i structure my if statement? Would I use
$sql="Select * FROM courses WHERE user = $user and course1 = TRUE"
$result = mysql_query($sql) or mysql_die($sql)
if($result)
{

echo html

}

or is there another way to do this? Is there a way I can write an if statement to check multiple values for example if($_SESSION['auth_id'] == 1) and if (course1 == TRUE) (i know that the last if statement isnt correct but I'd like to combine the two if possible). Would I need to write it as an if statement within an if statement:
if ($something)
{
   if ($somethingelse)
    {
       do work
     }
}

or an elseif:
if ($something)
{
   elseif ($somethingelse)
    {
       do work
     }
}

Comment: Really... you want to see the html as well or just the relevant part that isn't working. If you want more information be like everyone else and ask for it.. dont be condescending. Instead of recommending Codes-R-Us to others, you should take some courses on people skills.
Comment: You don't have any plan nor is this your code, right? Can you explain where $_SESSION['auth_id'] comes from? Also your database structure is not normalized ...
Comment: Don't use the deprecated mysql* functions and don't build queries by concatenation.
Comment: @ Fred -ii- i didn't know I was being graded on semicolons. I just put it together really quickly to make a point. If you want to help - be constructive not annoying
Comment: @Fahad Ten you should have put up actual code and not just "You (as in me/us) Fill in the Blanks) and take care of the rest. You ought to know better.
Comment: @djot auth_id is from after the user logs in. They're basically divided in to certain groups or categories. So the page will be checking initially to make sure user is logged in, but there will be multiple pages that will have to check the user category and if they can access specific courses.
Comment: @Fred-ii- I'm asking how to structure an if statement, not for you to write everything for me. It's a simple question. If you don't know the answer, don't take up comment space with silliness
Comment: @Fahad *"I'm trying to create a menu"* - You shown us no actual code that you're having difficulty with. So IMO, your question didn't show any effort to resolve/build what you need to achieve. Just a lot of `IFs` and `do work`.
Comment: @Fahad I doubt very much that I was "condescending" as you call it. Re-read my comments. If you can't take creative criticism, then you're in the wrong business. [Here](http://php.net/manual/en/control-structures.if.php) and [here](http://php.net/manual/en/control-structures.elseif.php) are where you'll find most of your answers on how to construct `if/else`. Plus Google isn't broken nor offline.
Answer: Get the row with the desired ID with all three courses. Then use PHP to check each of the course values and output the desired HTML accordingly.
To combine if statements, do this (you were close):
if (condition1 AND condition2)...
elseif (condition3)...

Or use && instead of AND, they'll work the same in your case, but they are not the same because of precedence. I'm writing you pseudo language that's a bit easier to read.
You can have as many conditions as you want:
if ( ((c1 OR c2) AND (!c3 AND c4) AND !(c5 AND c6)) OR c7 )...

And don't forget to stop using the mysql_* functions as they are deprecated. Switch to mysqli or PDO instead.
Answer: You're asking how to do multiple conditions in an if in PHP, I see.
The boolean operators && (AND) and || (OR) will be your friends here.
if($cow=='brown'){
    if($cat=='white'){
        doStuff();
        }
    }

is the same as
if($cow=='brown' && $cat=='white'){
    doStuff();
    }

The && in the middle means the condition is only true overall if both parts are true.
see Logical Operators
The second one, with elseif, would be a use for ||. The wexample you gave would not work (it would never reach the elseif if the first one were not true...) but these two are equivalent:
 if($something){
    doStuff();
    }
 elseif($somethingElse){
    doStuff();
    }

and
 if($something || $somethingElse){
    doStuff();
    }

it will doStuff() if either one is true.
Comment: $cow='brown' is not same as $cow=='brown'
Answer: About logical operators:
Example  ----- Name---Result
$a and $b---And-----TRUE if both $a and $b are TRUE.
$a or $b  ----Or-------TRUE if either $a or $b is TRUE.
$a xor $b--   Xor------TRUE if either $a or $b is TRUE, but not both.
! $a-----------Not------TRUE  if $a is not TRUE.
$a && $b----And------TRUE if both $a and $b are TRUE.
$a || $b----Or--------TRUE if either $a or $b is TRUE.

The returned $result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data
Something like this:
while ($row = mysql_fetch_assoc($result)) {
  $userid=$row["userid"];
  $course1 =$row["course1"];
  if($userid==1 && course1){
    //do something
  }
}

Get result
As side note: mysql_* functions are deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_assoc()
PDOStatement::fetch(PDO::FETCH_ASSOC)
Comment: yes add an elseif($course1) after `if statement`...`if` isn't a function
Comment: Thanks, makes sense. If I wanted to continue it on after course1, I would just add an elseif after the if function correct?
Answer: This is NOT intended as an answer, it's just that it's too big for a comment.
It looks like you are pretty new to all of this. We all were, once, so I wish you luck. Stick with it and it will become clear and easier (and you will build up a good collection of code snippets).
Read a few books. That really got me up to speed with PHP and MySql.
And be sure that you know when to use MySql and when to use Sqlite. I mention this because, although PHP has some slight preference for MySQl, it also happilly supports Sqlite. And, if you think you might ever develop for Android or Ios then it might be better to become an Sqlite guru as both of them support Sqlite, but neither support MySql.
Get a good IDE. I personally love Netbeans. It's coding & debug facilities are excellent. For development on your own PC you need an Apache server and MySql; I don't think you can beat Xampp if you are using Windows (it's even easier with Linux).
But, I digress, I only started this to mention that you might want to consider your database design. It works fine so long as you are 100% certain that you will never have more than 3 courses.
Even then, it is not third normal form.
I would probably start with something like this. You can add more columns as needed and I will leave it to you to sort out the Primary and Foreign Keys.
mysql> show tables;
+------------------------+
| Tables_in_menu_example |
+------------------------+
| course_subscription    |
| courses_description    |
| students               |
+------------------------+
3 rows in set (0.00 sec)

mysql> describe students;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| student_id | int(11) | NO   | PRI | NULL    | auto_increment |
| email      | text    | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> describe courses_description;
+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| course_id   | int(11) | NO   | PRI | NULL    | auto_increment |
| course_name | text    | NO   |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> describe course_subscription;
+------------+---------+------+-----+---------+-------+
| Field      | Type    | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| student_id | int(11) | NO   |     | NULL    |       |
| course_id  | int(11) | NO   |     | NULL    |       |
+------------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

I do realize that this hasn't answered your question at all (sorry), but I hope that it will help some. Good luck!!
Comment: Actually this was a big help, as I have come to a point with the DB where I'm not 100% certain of the structure anymore and it's looking messy - currently my plan was that I would have 2 main tables and then a separate table per course category. The 2 main tables are users which would store user info, and then 2nd would be courses (all the courses that are offered, along with one column for email/username to show which user has subscribed to which course). Then there would be a third (or many more) table that would have all the chapters in a course along with their descriptions, urls, etc.
Comment: I would basically use the php from the question above to push out the chapters based on the following sequence of authentication: user-->course subscription ---> Course Chapters, and those chapters would basically populate in a list for users to click on and view. The problem is, I have A LOT of courses for subscription, and it'll grow in the future. This is meant to stream tutorial videos on things like math, chem, bio, etc. So I'm not entirely sure where to take the database structure. At this point im doing some research on it
Answer: try to use *mysql_num_rows.*
example:
    $syntax = mysql_num_rows(//your query syntax);
if($syntax >0 )
{
  // do return
}
else
{
  // refresh
}


Manipulacao de arquivo txt no JAVA

Question: Ola ,sou iniciante no java e preciso criar um programa que crie um arquivo txt com um conteudo pre definido , leia ele e divida o conteudo desse arquivo em dois arquivos txt diferentes , sendo o conteudo passado pro primeiro arquivo todas as linhas que comecem com // (comentarios do java) e passe o restante (sera um codigo de java) para o segundo arquivo e por fim compile esse codigo.
A maior parte do programa eu consigo fazer, mas a minha duvida esta na parte em que eu preciso passar o conteudo para um arquivo diferente.
public static void main(String[] args) throws IOException {
    //conteudo
    String conteudo = "arquivo inicial\nlinha2"; //conteudo inicial
    String conteudo1 = null; //o que vai ser separado para o arquivo1(comentarios)
    String conteudo2 = null; //o que vai ser separado para o arquivo2(codigo a ser compilado)

    //cria os 3 arquivos (inicial , txt dos comentarios e txt do codigo
    File arquivo = new File("arquivo.txt");
    File arquivo1 = new File ("arquivo1.txt");
    File arquivo2 = new File("arquivo2.txt");

    //prepara pra escrever no arquivo inicial
    FileWriter fw = new FileWriter(arquivo.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    //escreve e fecha o arquivo
    bw.write(conteudo);
    bw.close();

    //le o arquivo linha por linha
    FileReader ler = new FileReader("arquivo.txt");
    BufferedReader reader = new BufferedReader(ler);
    String linha;
    while( (linha = reader.readLine()) != null) {
        System.out.println(linha);  //printa linha por linha do arquivo inicial
        if (linha.contains("//")) {    //se o arquivo conter // , ele separa para outro arquivo
            }
        else {

        }
    }

    }

Minhas duvidas sao: o if que vera se a linha contem duas barras(no caso o comentario em java) devera ficar dentro ou fora do while que le o arquivo ate nao existir mais nada para ler , e qual comando eu posso usar dentro do if que seja capaz de separar apenas as linhas com comentarios e crie uma nova string com ela?
Muito obrigado a todos
Answer: Completei seu código com uma implementação bem simples.
Recomendo utilizar as novas APIs(Classes) de Arquivos do Java 7 para manipulação de arquivos, já que elas possuem alguns métodos que abstraem a escrita e leitura de arquivos de seu código.
Implementação:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        //Conteudo inicial.
        String conteudo = "Linha Codigo\n//Comentario"; //conteudo inicial

        //Obtem um path para cada um dos 3 arquivos (inicial ,comentarios e txt do codigo
        Path arquivoInicial = Paths.get("arquivoInicial.txt");
        Path arquivoComentarios = Paths.get("arquivoComentarios.txt");
        Path arquivoCodigo = Paths.get("arquivoCodigo.txt");

        //Escreve o conteudo inicial
        Files.write(arquivoInicial, conteudo.getBytes());

        //Chama a funcao de fitro, pasando o arquivo Origem e os arquivos de destino.
        filtrarComentarios(arquivoInicial, arquivoComentarios, arquivoCodigo);
    }

    /**
     * Filtra o codigo de um arquivo, separando em código e comentarios.
     */
    public static void filtrarComentarios(Path arquivoInicial, Path arquivoComentarios, Path arquivoCodigo) throws IOException {
        //Cria duas listas para armazenar o codigo e comentarios.
        List<String> comentarios = new ArrayList<>();
        List<String> codigo = new ArrayList<>();

        //Itera todas as linhas do arquivoInicial, o método readAllLines de Files retorna uma Lista
        //de String que denota as linhas do arquivo.
        for (String linha : Files.readAllLines(arquivoInicial, StandardCharsets.UTF_8)) {
            //Utiliza o método trim() para que qualquer comentario seja detectado, o método trim() remove todo whitespace(espaco, tabs) do inicio e fim da String.
            if (linha.trim().startsWith("//")) {
                comentarios.add(linha);
            } else {
                codigo.add(linha);
            }
        }

        //Escreve o resultado em cada arquivo.
        Files.write(arquivoComentarios, comentarios);
        Files.write(arquivoCodigo, codigo);
    }
}

A ideia do código é iterar sobre todas as linhas do arquivos e filtrar as linhas cujo caracteres inicias sejam //, após iteração o resultado é escrito nos dois arquivos.
É importante notar que os métodos utilizados da classe Files lançam a exceção IOException caso ocorra um erro durante a escrita/leitura de um arquivo, assim interrompendo a execução, é recomendado que este erro seja tratado com um bloco try/catch porém não foi feito para simplificar a implementação.
Comment: Entendi perfeitamente, e eu já estava pensando em colocar em um bloco try/catch para tratar as excecoes , mas por se tratar de uma dúvida pessoal preferi deixar assim para economizar tempo, mas muito obrigado pela ajuda.

Manipulacao de arquivo txt no JAVA


How to call function by user input in python?

Question: I am working on a mechanical button presser with a motor. I have written some code. I have some tasks given to press the button in different intervals (ex long press, short press, 3 sec press, etc)
from time import sleep
import RPi.GPIO as GPIO

DIR = 26   # Direction GPIO Pin
STEP = 19  # Step GPIO Pin
CW = 1     # Clockwise Rotation
CCW = 0    # Counterclockwise Rotation
SPR = 15   # Steps per Revolution (360 / 1.8)

GPIO.setmode(GPIO.BCM)
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(STEP, GPIO.OUT)
GPIO.output(DIR, CW)

MODE = (14, 15, 18)   # Microstep Resolution GPIO Pins
GPIO.setup(MODE, GPIO.OUT)
RESOLUTION = {'Full': (0, 0, 0),
              'Half': (1, 0, 0),
              '1/4': (0, 1, 0),
              '1/8': (1, 1, 0),
              '1/16': (0, 0, 1),
              '1/32': (1, 0, 1)}

GPIO.output(MODE, RESOLUTION['Full'])
step_count = SPR
delay = .0208

for x in range(step_count):
    GPIO.output(DIR, CCW)
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay)

sleep(2)
GPIO.output(DIR, CW)
for x in range(step_count):
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay)

for x in range(step_count):
    GPIO.output(DIR, CCW)
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay)

sleep(8)
GPIO.output(DIR, CW)
for x in range(step_count):
    GPIO.output(STEP, GPIO.HIGH)
    sleep(delay)
    GPIO.output(STEP, GPIO.LOW)
    sleep(delay)
GPIO.cleanup()

In the above code you can see I have two intervals i.e 2 sec press and 8 sec press. So I want something when we run the code it will ask which function you want to use and then after giving input it will call that particular interval and the button will get pressed for that interval. Any help would be highly appreciated.
Answer: I'm not sure I correctly understand the context in which you want to ask for user input (since most RPs are used in environments where you can't easily get a command prompt in the first place).
But assuming that you do have some kind of shell in which you're running this Python script, this is one way:
def short_press():
    ...

def long_press():
    ...

actions = {'short': short_press, 'long': long_press}

command = input('Choose an action: ({})'.format(', '.join(actions.keys())))

if command in actions:
    actions[command]()
else:
    raise ValueError('{} is not a recognized action'.format(command)

Comment: I have tried to put the function in that def thing but it did not work


$f \in C^1[0,\infty)$ such that $\lim_{x \to \infty} \dfrac {xf(x)}{f'(x)}=2$ ; then for $s<2$ ; $\lim_{x \to \infty}x^{-s}f(x)=\infty$?

Question: Let $f \in C^1[0,\infty)$ be such that $\lim_{x \to \infty} \dfrac {xf(x)}{f'(x)}=2$ ; then is it true that for $s<2$ , $x^{-s}f(x) \to \infty$ as $x \to \infty$ ?
Answer: If $\frac{xf}{f'}\to2$, then there is some $M$ where $x>M\implies \frac{xf}{f'}<3$.
Then if $x>M$,
$$\int_M^x\frac{f'(t)}{f(t)}dt>\int_M^x\frac{t}{3}dt\implies  \log\frac{f(x)}{f(M)}>\frac{x^2-M^2}{6}\implies f(x)>f(M)\exp\left(\frac{x^2-M^2}{6}\right)$$
Noting that $\exp\left(\frac{x^2-M^2}{6}\right)$ grows faster than any power of $x$, the result is proved. Note further that we do not need the $s<2$ stipulation for this to hold.
[below - proof based on a misreading of the OP]
If $\frac{xf'}{f}\to2>s$, then there is some $M$ where $x>M\implies \frac{xf'}{f}>\frac{s+2}{2}$.
Then if $x>M$,
$$\int_M^x\frac{f'(t)}{f(t)}dt>\int_M^x\frac{s+2}{2}\frac{1}{t}dt\implies  \log\frac{f(x)}{f(M)}>\frac{s+2}{2}\log \frac{x}{M}$$
Then:
$$x^{-s}f(x)>x^{-s}f(M)\left(\frac{x}{M}\right)^{\frac{s+2}{2}}\propto x^{\frac{2-s}{2}}\to\infty$$
assuming $f(M)>0$. A similar result follows if $f(M)<0$
Comment: @πr8 The question is about $xf/f'$, not $xf'/f$.
Comment: $\exists M >0 $ ... you should assume $M>0$ , otherwise you cannot divide by $x$ and retain inequality ...
Comment: @user228169 $f$ is only defined for $x\ge0$, so I don't think this really gets in the way - $M$ isn't going to be 0, because $0=\frac{xf'}{f}>\frac{s+2}{2}>1$ can't happen. Besides, it's a tail inequality, i.e. if $M$ works, so does any $M'>M$.
Comment: @MarcoCantarini My mistake - have edited to fix. Misread because the $s<2$ condition is only material for the $xf'/f$ case.


How to remove item space between 2 pivot items in Windows Phone 8?

Question: I am using pivot control to display full sizes multiple image on the screen as a flip view. But the problem with pivot is that it is taking empty space between two pivot items. How to eliminate this space?
If any other solution is available to display images as Flip view,please share.
I used FlipView control by Kinnara fork's as a datatemplate of ListBox:
<ListBox Background="AntiqueWhite" x:Name="FlipViewList" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemTemplate="{StaticResource DataTemplate2}"/>

     <DataTemplate x:Key="DataTemplate2">
        <Grid Height="200">
            <toolkit:FlipView x:Name="ImagePivot" Height="200" ItemsSource="{Binding imageCollection}" Tag="{Binding}" IsLocked="False" Grid.ColumnSpan="1" Grid.RowSpan="1">
                <toolkit:FlipView.ItemTemplate>
                    <DataTemplate>
                        <Grid HorizontalAlignment="Left" Height="200" Width="480">
                            <Image Stretch="Fill" Source="{Binding images}" Height="200" Width="480"/>
                        </Grid>
                    </DataTemplate>
                </toolkit:FlipView.ItemTemplate>
            </toolkit:FlipView>
        </Grid>
    </DataTemplate>

Everything works fine but the vertical scrool is not working for listbox. How to resolve this scrool issue?
Answer: The problem here is there's no FlipView provided by msdn for the WP8 platform where as it's been added to the 8.1 version:
How to add a flip view
There are two options or even could be more, but i'm mentioning here two of them:
1) You could try out the Telerik SlideView control:
WinRT FlipView like control in WP8
Sample has been given here.
2) Or else you could go for the FlipView provided by Kinnara's fork.
Comment: I had tried FlipView by kinnara's fork. I used this as a child in Listbox so the problem is, this flipview is stopping the vertical scroll for listbox
Comment: What about the other one?
Comment: It seems to be Telerik SlideView control is paid one
Comment: You could go for the trial one still! http://www.telerik.com/products/windows-phone/download.aspx
Comment: thanks for ur reply but i dont want to go for paid controls. Can you tell me that either we can remove the space which is shown in between 2 pivot items or can we give full width image as a panaroma item
Comment: You can give the width as `auto` and see, but it changes according to the resolution of the image.
Answer: I had a similar problem, so I decided to use my own custom XAML control. Basically, you can have a StackPanel that holds the images, and house that StackPanel within a Horizontally Scrolling ScrollViewer, and can modify the scrolling so that it scrolls 1 item at a time. the Images can be given a margin before adding them to the StackPanel, and that's how you can achieve the spacing between them. Check this out for instructions and a sample - https://quirkd.wordpress.com/2015/01/18/make-your-own-swipe-carousel-control/
Comment: I go through the link which has mentioned by you. But the issue is that, if i disable the horizontal scrolling in xaml then i am unable to set horizontal offset for a scrollviewer programatically as its horizontal scrolling is already disabled in xaml.


How to fetch the row and column number of error

Question: How to fetch the row and column number of error (i.e which part of string does not follow the grammar rules)?
I am using yacc parser to check the grammar.
Thank you.
Answer: you'd better read the dragon book and the aho book that explain and show example of how to write a lex/yacc based compiler.
In order to get line/column of the error, you shall make your lexer preserve the column and line. So in your lexer, you have to declare two globals, SourceLine and SourceCol (of course you can use better non-camel cased names).
In each token production, you have to calculate the column of the produced token, for that purpose I use a macro as follows:
#define Return(a, b, c)    \
{\
    SourceCol = (SourceCol + yyleng) * c; \
    DPRINT ("## Source line: %d, returned token: "a".\n", SourceLine); \
    return b; \
}

and the token production, with that macro, is:
"for" { Return("FOR", FOR, 1);

then to keep lines, for each token that makes a new line, I'm using:
{NEWLINES}     {
    BEGIN(INITIAL);
    SourceLine += yyleng;
    Return("LINE", LINE, 0);
}

Then in your parser, you can get SourceCol and SourceLine if you declare those as extern globals:
extern unsigned int SourceCol;
extern unsigned int SourceLine;

and now in your parse_error grammar production, you can do:
parse_error : LEXERROR
{
    printf("OMG! Your code sucks at line %u and col %u!", SourceLine, SourceCol);
}

of course you may want to add yytext, handle a more verbose error message etc.. But all that's up to you!


How to show votes in view results by node id?

Question: I installed the modules "rate (voting widget)" and "voting api". These modules work very well.
I use views to get a list of nodes, and I added the voting results. Now I get a row for each vote, not for each node...
Views rows:
Node 1  --  angry: 1  happy: 1
Node 1  --  angry: 1  happy: 1

Node 2  --  angry: 1  happy: 0

Node 3  --  angry: 0  happy: 1

I want to group the results by node id, but this doesn't seem to work. what would be the easiest solution for this problem?
Answer: You can use hook_query_alter() in your custom module. Your code should look like this:
function MODULENAME_query_alter(&$query) {
  if(!empty($query->alterMetaData['view']->name) && $query->alterMetaData['view']->name == 'VIEWNAME'){
    $query->groupBy("node.nid");
  }
}

Comment: Hmm, this sounds like a very good idea, thanks in advance!
Answer: Easiest way is to use the built in aggregation functions in views / voting api. Select 'Relationships' under the 'Advanced' tab and add a relationship based on vote results:
Content: Vote results
Aggregate results of votes cast on Node.

The settings page lets you select whether you are aggregating for total votes, total score or even looking for an average.
Comment: But I want to show ALL results (emotions in my case). So I want to show: "node Angry:1 - Happy:1", but because of the two votes I get 2 results in views. I don't want the total of all votes...
Comment: ok - maybe all you need is to add a distinct setting to your view to get views to clear up the confusion. Try this under 'Advanced: Query Options' and check the 'distinct' checkbox. If that doesn't work, you might want to try posting your view because there's something in the view configuration that is causing it to repeat these.


Must solution of the differential equation $\frac{dy}{dx}=f(x,y)$ and $ y(x_0)=y_0$ be unique?

Question: Must solution of the differential equation $\displaystyle\frac{dy}{dx}=f(x,y)$ and $\displaystyle y(x_0)=y_0$ be unique?
Example: I found that (i) $y=x,x\neq0$, (ii) $y=|x|$ and (iii)  $f(x)= \begin {cases} x&\text{if }x >0\\
-Ax\ &\text{if }x<0 \end {cases}$ for any $A\neq 0$ all satistify the differential equation $\displaystyle\frac{dy}{dx}=\frac{y}{x}$ and $\displaystyle y(1)=1$. Can we accept them as answer?
On the other hand, if we start from $\displaystyle\frac{dy}{dx}=\frac{y}{x}$, it leads to $\displaystyle\int_1^{y}\frac{dy}{y}=\int_1^{x}\frac{dx}{x}$. To apply the First Fundamental theorem of calculus, $x,y>0$ so that $\frac{1}{x}$ and $\frac{1}{y}$ are continuous at $[1,x]$ and $[1,y]$ respectively. Solve it and we get $y=x,x>0$.
Any comment or answer?
Answer: No the solution is not unique in general, if the right hand side is local lipschitz the solution will be unique with picard lindelöf, if the right hand side is continuous a solution exists (but not necessary a unique one).
Without thinking a lot
$$\left\{
\begin{array}{l}
y'=y^{\frac{1}{3}}\\
y(0)=0\\
\end{array}
\right.$$
has at least 2 different solutions, something like
$$y(t)=\frac{2}{3} \cdot \sqrt{\frac{2}{3}} t^\frac{3}{2}$$
and the trivial solution $y(t)=0$


How to show in a view the total number of paragraphs for a node?

Question: I have a content type with a field of type paragraphs, with possible unlimited values. I need to show the total number of paragraphs for every node, in a column, in a views (table of fields). It seems to be only possible to render a preview of the paragraph. I tried to use "rewrite result" with "replacement patterns" but the only token available are the following:
<code>{{ field_hours }} == Hours
{{ field_hours__target_id }} == Raw target_id
{{ field_hours__target_revision_id }} == Raw target_revision_id
</code>
How I can proceed?
Answer: I managed to achieve this doing the following:

Create a View to show Content of Type All. Add a page as well if you wish.
Format the style to be a Table.
Go to Advanced and turn on "Use aggregation".
Go to aggregation settings for the field "Content:Title" and set the aggregation type to "Count".
Change the label of this field to something like "Number of paragraphs in the node:".(*optional)
In Fields add field "Content:Title", aggregation type should be Group results together.
Add Filter Criteria "Hours (field_hours:target_id)", aggregation type should be Group results together, and set the operator to "is not empty(NOT NULL)".

This is how the Display settings should look at the end:

And here are the desired results in the preview:

I hope this helps.
Comment: Thanks for your time Emily, this worked well


Como verificar se o arquivo é uma imagem do Input type="file"

Question: Tenho um input type="file" que iria servir para o usuário adicionar uma foto de perfil e gostaria de verificar se o arquivo é uma imagem antes.

Já fiz a verificação via PHP, mas gostaria de fazer via Javascript também.
Answer: Sim, inclusive, você pode adicionar no HTML também caso não saiba:
<input type="file" accept="image/*"/>

Vou te dar a base, depois é só implementar condições:

function validation(){
  var file = document.getElementById("myFile");
  var file = file.files[0];

  document.getElementById("logger").innerHTML = "Nome: " + file.name + "
Type: " + file.type + "
Tamanho: " + file.size;
}
 <input type="file" id="myFile" accept="image/*" onchange="validation()" />

Comment: Valeu cara, não sabia mesmo, valeu.
Answer: Você pode utilizar o atributo type do arquivo, ele vai retornar o tipo no formato image/png, é só verificar se contém o texto image
Ex.:

var file = document.getElementById('file');

function test() {
    if (file.files[0].type.includes('image')) {
        alert('É uma imagem')
    } else {
         alert('Outro tipo de arquivo')
    }
}

document.getElementById('testButton').addEventListener('click', test)
<input type="file" id="file">
<button id="testButton">Testar</button>

Obs.: O tipo é detectado a partir da extensão do arquivo, o que não pode ser muito seguro

Fiz um outro exemplo baseado nessa resposta, é mais complexo, porém mais seguro do que o anterior:

var fileInput = document.getElementById('fileInput')
var fileReader = new FileReader();

fileReader.onloadend = function(e) {
    var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
    var header = "";
    for(var i = 0; i < arr.length; i++) {
       header += arr[i].toString(16);
   }
    var type = ""

    switch (header) {
        case "89504e47":
            type = "image/png";
            break;
        case "47494638":
            type = "image/gif";
            break;
        case "ffd8ffe0":
        case "ffd8ffe1":
        case "ffd8ffe2":
        case "ffd8ffe3":
        case "ffd8ffe8":
            type = "image/jpeg";
            break;
        default:
            type = "unknown"; // Or you can use the blob.type as fallback
            break;
    }

    alert(type)
};

fileInput.addEventListener('change', function () {
    var blob = fileInput.files[0]
    fileReader.readAsArrayBuffer(blob);
})
<input type="file" id="fileInput"/>
Answer: Você pode verificar pela extensão do arquivo usando .match com o regex:
/\.(gif|jpg|jpeg|tiff|png)$/i

Exemplo:

function isImagem(i){

   var img = i.value.split(".");
   var ext = "."+img.pop();

   if(!ext.match(/\.(gif|jpg|jpeg|tiff|png)$/i)){
      alert("Não é imagem");
      i.value = '';
      return;
   }

   alert("OK!");
}
<input type="file" onchange="isImagem(this)" />


Making Edittext an address and search bar in one Android Eclipse

Question: I am trying to make an edittext into both a search bar and address bar. Also I am not sure how to allow the user hit enter on their keyboard to initiate the search instead of manually touching the go button.
Answer: It sounds like you want to use IME actions for your case to allow the user to have a sort of "Go" button which is activated by the enter key.  This page on the official Android guide should help you: http://developer.android.com/guide/topics/ui/controls/text.html#Actions
To detect a URL, use the built in Java class to do it.  See here: How to detect the presence of URL in a string
Using those two methods, simply check if the entered text is a URL.  If it is, then use it, otherwise you call your search method passing in the entered text.


Did I discover something new? How do I prove it?

Question: I saw recently a post on a math page about the following interesting approximation:

Which made me play around with the number at the denominator, 123456789, and I discovered that if you multiply it by a multiple of 3 you are going to get a interesting number, which I believe an example might be worth in order to comprehend.
Let's multiply 123456789 by 12, a multiple of 3:

Take the result and add 12, the number that you multiplied 123456789 by:

See that division of the number in sequences of 3 digits from right to left? After 3 sequences of 3 digits, take what comes after (In this case, one) and add it to the previous result:

That same 3 sequences of 3 digits are going to be exactly the same after the process, which in this example was 481, and that's the problem: That same 3 sequences of 3 digits are going to be exactly the same after the process, which in this example was 481, and that's the problem: how do you prove that this is always going to happen (if it always does)? I've already tried to check the first 500 cases and I didn't see an exception.
Also, if we say that the number (r) we get after multiplying 123456789 by a multiple of 3 is:

And if we look at it's table of values, that means, a table of the corresponding r for a given n, we see that after 27 units, the 3 digit sequence that repeats is going to reset to the first one, when n=1, which is 370 (note that x=n and the huge equation is equal to the respective 3 digit sequence):

So, the graph of r(n) is going to be:
Comment: @Pedro Krause Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: Well, $12345679\cdot 9$ is...
Answer: $$\frac{10}{81}=0.1234567901234612345679012346\cdots=0.123456789+0.000000000123456789+\cdots$$
This fractional number has the period $9$. When you multiply it by $3$, you get a number with period $3$,
$$\frac{10}{27}=0.370370370370370370370370\cdots=0.370+0.000370+\cdots$$
and again by $3$,
$$\frac{10}{9}=0.111\cdots=0.1+0.01+0.001+\cdots$$
As you can imagine,
$$\frac{10}{243}=0.0411522633744855967078189300411522633744855967078189\cdots$$ has period $27$.
If you multiply these numbers by an integer which is not a multiple of $3$, the period remains unchanged. Sorry, there is no deep math here.
Comment: Interesting! However, I'm afraid I do not see the proof of the main question, which I cited in this paragraph: "That same 3 sequences of 3 digits are going to be exactly the same after the process, which in this example was 481, and that's the problem: how do you prove that this is always going to happen (if it does)? I've already tried to check the first 500 cases and I didn't see an exception."
Comment: @PedroKK: this is answered in my beforelast sentence, though maybe not in the way you wanted.
Answer: We have, exactly:
$\dfrac{0.\overline{098765432}}{0.\overline{012345679}}=8$
The numerator is $8/81$, the denominator is $1/81$.  Basically the quoted fraction follows this pattern except in the last couple digits if the numerator and denominator.
Similar constructions exist in other bases, the quotient being close to the base minus $2$.  For instance in base $5$:
$\dfrac{4321}{1234}\approx \dfrac{0.\overline{0432}}{0.\overline{0124}}=3$
In base $5$ we actually have $1234×3=4312$, so again we're off only in the last couple "digits".  However, with fewer "digits" overall the near-integer approximation is not as good.  It becomes more accurate in higher bases.
Answer: The basic operation you are doing to observe the pattern is to consider $3n\cdot 123456789 + 3n = n(3\cdot 123456789+3)$. Now $3\cdot 123456789+3 = 370 + 370\cdot 10^3 + 370\cdot 10^6$. There's nothing special about this number, so let's instead fix some positive integers $k$ and $N$ with $k < 10^N$ and $r$ and consider
$$y = \sum_{s=0}^r k10^{sN}.$$ In your example, $k = 370$, $N = 3$, and $r = 2$, so $y =  3\cdot 123456789+3$. We want to show that for $n \geq 1$ the quantity $ny +$ some leading digits of $ny$ has a pattern of $N$ digits repeating $r+1$ times. It turns out that this will be true provided that $ny \leq 10^{(2r+1)N}-3$. In your case, this means that this will be true so long as $n \leq 10^{6.4}$, so it's no wonder you didn't find a counterexample.
To be more explicit, in your example, $n = 4$, and $ny = 481481480$, and the leading digit we need to add is a $4$, and we repeat the sequence $481$ a total of $3$ times. If $n = 271$, then $ny = 100370370270$ and we need to add on the leading digits $100$ to get $ny + 100 = 100370370370$, and repeat the sequence $370$ a total of $3$ times.
Let's take a small detour before tackling the problem. Let $m$ be any integer with decimal expansion $d_1d_2\ldots d_M$ and consider the decimal expansion of $\frac{m}{10^M-1} = \frac{d_1\ldots d_M}{9\ldots 9}$. Recall that this is just $0.\overline{d_1\ldots d_M}$. Indeed, we can express this decimal as
$$(d_1\ldots d_M)(10^{-M}) + (d_1\ldots d_M)(10^{-2M}) + (d_1\ldots d_M)(10^{-3M}) + \cdots = \sum_{s = 1}^{\infty}m(10)^{-sM} = \frac{m 10^M}{1-10^{-M}} = \frac{m}{10^M-1}.$$
Now back to the original problem. By definition
$$ny = \sum_{s=0}^r (nk)10^{sN}.$$ Then, with $M = (r+1)N$
$$\sum_{t=0}^{\infty}ny 10^{-M} = nk\sum_{t=0}^{\infty}\sum_{s=0}^r 10^{sN}10^{-M} = nk \frac{10^{(r+1)N}-1}{(1-10^{-(r+1)N})(10^N-1)} = 10^{(r+1)N}\frac{nk}{10^N-1}.$$
Let us write $nk = p\cdot (10^{N-1}-1) + q$, where $q \leq 10^{N-1}-1$ (it's convenient to allow $q = 10^{N-1}-1$ if possible, so that $q \neq 0$ if $n \neq 0$). Thus
$$10^{(r+1)N}\frac{nk}{10^N-1} = 10^{(r+1)N}p + 10^{(r+1)N}\frac{q}{10^N-1}.$$
The first term is an integer with $N(r+1)$ tailing zeroes in its decimal expansion, say $e_1\ldots e_K0\ldots 0$. We we know from the detour that $\frac{q}{10^N-1}$ is a repeating decimal less than $1$, and each repeated block has length $N$; suppose it is $0.\overline{d_1\ldots d_N}$. Then the second term is $(d_1\ldots d_N)\cdots(d_1\ldots d_N).\overline{d_1\ldots d_N}$, where the block before the decimal point repeats $r+1$ times.
It follows that
$$\sum_{t=0}^{\infty}ny 10^{-M} = 10^{-M}10^{(r+1)N}\frac{nk}{10^N-1} = e_1\ldots e_K (d_1\ldots d_N)\cdots(d_1\ldots d_N).\overline{d_1\ldots d_N}.$$
However, notice that $\sum_{t=2}^{\infty} ny 10^{-M} = 10^{-2M}\frac{ny}{1-10^{-2M}} = \frac{ny}{10^{2M}-1} < 10^{-N}$ since $ny \leq 10^{(2r+1)N}-3$. Thus
$$\sum_{t=0}^{1}ny 10^{-M} = ny + ny/10^M = e_1\ldots e_K (d_1\ldots d_N)\cdots(d_1\ldots d_N).\overline{d_1\ldots d_N} - x$$, where $x$ is some positive number less than $10^{-N}$. In particular, so long as $d_1\cdots d_N$ is not identically $0$, $0 \leq 0.\overline{d_1\ldots d_N} - x < 1$ and so
$$ e_1\ldots e_K (d_1\ldots d_N)\cdots(d_1\ldots d_N) \leq  ny + ny/10^M < e_1\ldots e_K (d_1\ldots d_N)\cdots(d_1\ldots d_N) + 1,$$ and so $ny$ + some leading digits has the repeating pattern $d_1\ldots d_N$ a total of $r+1$ times.
However it's not possible for $d_1\cdots d_N$ to be identically $0$ unless $n = 0$, since this would necessitate $q = 0$.
This proof also predicts the periodicity of the pattern: just take $nk \pmod {10^N-1}$, with the usual residue class, except if $nk \equiv 0 \pmod {10^N-1}$, in which case the pattern is $99\ldots 9$. This explains the periodicity of your patterns, as well. In your example, $k = 370$, and $370\cdot 27$ is the lcm of $370$ and $999 = 10^3 - 1$, and so the pattern repeats each every 27 integers, except with $999$ instead of $000$. The occurrence of 27, which is about $10e$, appears to be purely coincidental.


On bounding a series

Question: We know the series
$$ \sum_{n=1}^{\infty} \frac{1}{(n+1)\sqrt{n}} $$
converges since we can compare with $1/n^{3/2}$ which is a convergent p-series.
Now, is it possible to show that
$$ \sum \frac{1}{(n+1)\sqrt{n}} < 2 $$
??
Answer: $$\sum_{n=1}^\infty \frac{1}{(n+1)\sqrt{n}} \leqslant \frac{1}{2} + \frac{1}{3\sqrt{2}} + \int_2^\infty \frac{dx}{\sqrt{x}(x+1)} \approx 1.9667$$

On bounding a series


Problem with scipy.optimize.fmin_slsqp when using very large or very small numbers

Question: Has anybody ever encountered problems with fmin_slsqp (or anything else in scipy.optimize) only when using very large or very small numbers?
I am working on some python code to take a grayscale image and a mask, generate a histogram, then fit multiple gaussians to the histogram.  To develop the code I used a small sample image, and after some work the code was working brilliantly.  However, when I normalize the histogram first, generating bin values <<1, or when I histogram huge images, generating bin values in the hundreds of thousands, fmin_slsqp() starts failing sporadically.  It quits after only ~5 iterations, usually just returning a slightly modified version of the initial guess I gave it, and returns exit mode 8, which means "Positive directional derivative for linesearch."  If I check the size of the bin counts at the beginning and scale them into the neighborhood of ~100-1000, fmin_slsqp() works as usual. I just un-scale things before returning the results. I guess I could leave it like that, but it feels like a hack.
I have looked around and found folks talking about the epsilon value, which is basically the dx used for approximating derivatives, but tweaking that has not helped.  Other than that I haven't found anything useful yet.  Any ideas would be greatly appreciated.  Thanks in advance.
james
Answer: I've had similar problems optimize.leastsq.  The data I need to deal with often are very small, like 1e-18 and such, and I noticed that leastsq doesn't converge to best fit parameters in those cases.  Only when I scale the data to something more common (like in hundreds, thousands, etc., something you can maintain resolution and dynamic range with integers), I can let leastsq converge to something very reasonable.
I've been trying around with those optional tolerance parameters so that I don't have to scale data before optimizing, but haven't had much luck with it...
Does anyone know a good general approach to avoid this problem with the functions in the scipy.optimize package?  I'd appreciate you could share...  I think the root is the same problem with the OP's.
Answer: Are you updating your initial guess ("x0") when your underlying data changes scale dramatically?  for any iterative linear optimization problem, these problems will occur if your initial guess is far from the data you're trying to fit.  It's more of a optimization problem than a scipy problem.
Answer: I got in trouble with this issue too, but I solved it in my project. I'm not sure if this is a general solution.
The reason was that the scipy.optimize.fmin_slsqp calculated the gradient by an approximate approach when the argument jac is set by False or default. The gradient produced from the approximate approach was not normalized (with large scale). When calculating the step length, large value of gradient would influence the performance and precision of line search. This might be the reason why we got Positive directional derivative for linesearch.
You can try to implement the closed form of the Jacobian matrix to the object function and pass it to the jac argument. More importantly, you should rescale the value of Jacobian matrix (like normalization) to avoid affecting line search.
Best.


how do i solve this problem on installing Cordova by cmd

Question: I am a new user. i am trying to export mu game in construdt2 to apk by Cordova cli.
when I want install Cordova in cmd, I see this:
enter image description here
please help me soon.
I tried more than 10 times to install it but I couldn't. at last time I saw theses errors.
best regards
ehsan
Answer: Looks like you already have a version installed and npm can't overwrite the cordova dir. Try to uninstall before, then reboot (just in case), then install again
<code> npm uninstall cordova -g
 reboot
 npm install cordova -g
</code>
Also make sure you run your prompt as admin


Using Riemann-Lebesgue Lemma to show a function is continuous

Question: I have been studying for a preliminary exam using old exams. Many of them ask the following question which we have unfortunately not talked about in the class at all. It would be nice to see an example of how the Riemann-Lebesgue lemma is applied.
$\textbf{Question:}$ Show that $f(t) = \int_E \sin(tx) dx$ is a continuous function where $E$ is a set of finite measure.
From what I read on wikipedia, the Riemann-Lebesgue theorem deals with Fourier transform of a function, I am not sure how to related this to the above problem.
Comment: How big is $E$?
Comment: Sorry, $E$ is a set of finite measure
Comment: If you rewrite $f(t)$ as $\int_\mathbb{R} h(x) \sin(tx)dx$ with $h=\mathbf{1}_E$ being the (integrable) indicator function of $E$, can you see how it could relate to the Riemann—Lebesgue lemma?
Comment: Yes. Thank you.
Answer: Let $g(x) = \chi_E(x)$. Note that $g\in L^1(\Bbb R)$ since it is just a characteristic function for a set with finite measure. Then we have that the Fourier transform of $g$ is (up to scalar multiple and conjugation depending on your definition of the Fourier transform)
$$\mathcal{F}g(x) = \int_{\Bbb R} e^{itx}g(t)\,dt.$$
Taking the imaginary part, we get $\int_E \sin(xt)g(t)\,dt.$ Since $g\in L^1(\Bbb R)$, the Riemann-Lebesgue lemma says that the Fourier transform of $g$ is continuous (and moreover it decays at infinity). A complex-valued function is continuous if and only if its component pieces are separately continuous. This supplies the proof.


Ignoring or skipping certain commits on Git

Question: I cloned a sample project, but when I check git log I see there are about 15 commits.
Commits 10 and 8 caused problems to the project and for now I would like to remove/ignore/skip changes made in commits 10 and 8.
How can I do this? (I don't want to merge or push these changes).
Comment: You are best off to `git revert` the specific commits. You can then revert the revert to put them back.
Answer: You can run git rebase -i hash_to_your_7th_commit and delete commits 8 and 10 but you are most likely going to get lots of conflicts.
Another option is git checkout -b 7th_commit and cherry-pick commits 9 and from 10 to 15.
Keep in mind that if you give a range 10..15 cherry-pick will start at 11.
I would recommend though to just revert these two commits because you may change your mind about pushing it someday.


Linear Algebra, find determinant with x1, x2,...,xn as scalars

Question:
I have no clue how to even begin solving for $\det(A)$ since $n$ is unknown, HELP!
Answer: If $n=1$ or $n=2$ then you can calculate the determinant explicitly. If $n> 2$, then take the difference of the first two rows and the difference of the first row and third row. You will get $(x_1-x_2,\ldots,x_1-x_2)$ and $(x_1-x_3,\ldots,x_1-x_3)$ which are linearly dependent (both multiples of $(1,,\ldots,1)$), so the first three rows are linearly dependent and thus the determinant is 0.
Answer: Denote $C_i$ the $i^{\text{th}}$ column of $A$ then we have
$$C_3-C_1=2(C_2-C_1)$$
hence the columns are linearly dependent and then the determinant is $0$.
Answer: Clearly
\begin{align}
\det\,\left(\begin{matrix}
x_1+1 & x_1+2 & \cdots & x_1+n \\
x_2+1 & x_2+2 & \cdots & x_2+n \\
\cdots & \cdots & \cdots & \cdots \\
x_n+1 & x_n+2 & \cdots & x_n+n
\end{matrix}\right)&=
\det\,\left(\begin{matrix}
x_1+1 & 1 & x_1+3&\cdots & x_1+n \\
x_2+1 & 1 & x_2+3&\cdots & x_2+n \\
\cdots & \cdots& \cdots & \cdots & \cdots \\
x_n+1 & 1 & x_n+3&\cdots & x_n+n
\end{matrix}\right) \\ {} \\&=
\det\,\left(\begin{matrix}
x_1+1 & 1 & 2&\cdots & x_1+n \\
x_2+1 & 1 & 2&\cdots & x_2+n \\
\cdots & \cdots& \cdots & \cdots & \cdots \\
x_n+1 & 1 & 2&\cdots & x_n+n
\end{matrix}\right)=0.
\end{align}
In the first equality we subtracted the first column from the second one, while in the second equality we subtracted the first column form the third one. The determinant of the last matrix is equal to zero as the third column is a multiple of the second one.


Distinct values from object property in array when property may not be present

Question: I'm creating an array of distinct values based on a single property in an array of objects. Nothing unusual, but the JSON I'm working with may not have that property. The result is I'm getting an item in the new array with a value of undefined. Is there a way to prevent this?

const cars = [{
    "name": "Toyota",
    "model": "Corolla"
  },
  {
    "name": "Toyota",
    "model": "Supra"
  },
  {
    "name": "Toyota",
    "model": "Rav4"
  },
  {
    "name": "Toyota"
  }
];

const distinctModels = [...new Set(cars.map(car => car.model))];

console.log(distinctModels);

EDIT - I should have mentioned that I'm interested to know if there's a way to do this whilst still utilising new Set.
Comment: So might be you will have to check for undefined!
Answer: You could post process the array and filter falsy values.

const cars = [{ name: "Toyota", model: "Corolla" }, { name: "Toyota", model: "Supra" }, { name: "Toyota", model: "Rav4" }, { name: "Toyota" }];

const distinctModels = [...new Set(cars.map(car => car.model))].filter(Boolean);

console.log(distinctModels);
Comment: Can you explain this: `filter(Boolean)`?
Comment: it takes `Boolean` as callback and it returns either `true` for all [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) values and `false` for all others. This allows to filter `undefined`, as well as empty strings.
Comment: Thanks, I guess I should have mentioned that I am doing this, just wondering if there's a way to avoid having to do that.
Comment: @Chris, no there is not. either filter in advance or at the end. i prefer at the end, because the amount of data is smaller to filter.
Comment: Ok, thanks Nina - yours is a more concise way than my current implementation so will use that. Thanks again.
Answer: Use .hasOwnProperty to check if a property exists in the object or not

const cars = [{
    "name": "Toyota",
    "model": "Corolla"
  },
  {
    "name": "Toyota",
    "model": "Supra"
  },
  {
    "name": "Toyota",
    "model": "Rav4"
  },
  {
    "name": "Toyota"
  }
];

const distinctModels = []
cars.forEach(function(e){
e.hasOwnProperty('model')?distinctModels.push(e.model):false;
});
console.log(distinctModels);
Answer: If you want to filter and map at the same time (ie in the one statement) you can instead use .reduce() to better control what goes into your output array:

const cars = [{
    "name": "Toyota",
    "model": "Corolla"
  },
  {
    "name": "Toyota",
    "model": "Supra"
  },
  {
    "name": "Toyota",
    "model": "Rav4"
  },
  {
    "name": "Toyota"
  }
];

const distinctModels = [...new Set(cars.reduce(
                         (a, car) => car.model ? [...a, car.model] : a, []
                        ))];

console.log(distinctModels);
Answer: You can use Array.prototype.flatMap to do it in one loop, by returning an empty array when value is not there.

const cars = [{
 "name": "Toyota",
 "model": "Corolla"
},
{
 "name": "Toyota",
 "model": "Supra"
},
{
 "name": "Toyota",
 "model": "Rav4"
},
{
 "name": "Toyota"
}
];

const distinctModels = [...new Set(cars.flatMap(car => car.model || []))];

console.log(distinctModels);