What is the default python version used by jenkins

Question: I am looking at jenkins failure, when running its "tests" stage, and noticed that the creation of the python virtual environment did not have a python version used.  I am wondering from that if the default version is the system version (2.7) or if the default version is based on the jenkins slave scripts.
I've added in pre-commit-hooks into my pycharm copy and those pass without issues (using python 3.6).  When I've pushed my code up and jenkins runs its tests, I get errors that point me to the direction that the default python is not 3.6 (does not recognize f-strings)
This is one of the current tests in the jenkins file:
virtualenv venv
source venv/bin/activate
pip install flake8
flake8 --ignore=E501 onboarding/ tests/

Answer: Jenkins does not come with Python. This completely depends on what version virtualenv installs (otherwise, it would be your operating system's python version).


Creating materialized view from a query in Azure Data Explorer (Kusto)

Question: Need some help with Kusto (Azure Data Explorer).
Is it possible to convert this query into a materialized view?
customobject
| join kind=inner (
    customobject
    | summarize max_dp_adf_copy_start_time = max(dp_adf_copy_start_time) by accountId, id
    )
    on
         $left.accountId == $right.accountId
         and $left.id == $right.id
         and $left.dp_adf_copy_start_time == $right.max_dp_adf_copy_start_time

I have tried this, but it comes back with Syntax Error Expected: ):
.create materialized-view mvw_customobject on table customobject
{
customobject
| join kind=inner (
    customobject
    | summarize max_dp_adf_copy_start_time = max(dp_adf_copy_start_time) by accountId, id
    )
    on
         $left.accountId == $right.accountId
         and $left.id == $right.id
         and $left.dp_adf_copy_start_time == $right.max_dp_adf_copy_start_time
}

Much help would be appreciated!
Best Regards :)
Answer: I have reproduced in my environment and below are my observations and followed Microsoft-Document:
I have got similar as you have at first:

Here, in yours and my query the problem was with summarize statement as summarize statement should come as last statement while creating the view and only one summarize statement should be used. When I made similar changes it got executed like below:
Example1:
.create materialized-view mvw_customobject5 on table chotu
{
    chotu
    | join kind = inner (chotu) on $left.EventId==$right.EventId
    |summarize take_any(*) by EventId
}

Example2:
.create materialized-view mvw_customobject00 on table chotu
{
    chotu
    | join kind = inner (chotu
    |project EventId) on $left.EventId==$right.EventId
    |summarize take_any(*) by EventId
}

You can clearly check the document which I have provided, try to follow the examples and do it, you will get view created as I have got mine.
Comment: Thank you for pointing to the docs. I've already researched them prior to creating my post. However, I've found the solution on my own later, before your response. Thank you for taking a look and trying to replicate my issue. ~Best.
Answer: I found the solution. To get the result I was looking for, in Kusto (ADX) I did not need the join:
.create materialized-view mvw_customobject on table customobject
{
customobject
    | summarize arg_max(dp_adf_copy_start_time, *) by accountId, id
}


Google Cloud Run - Create Services not working

Question: I've just started using Google Cloud Run for a work project. I'm trying to use API calls to spawn services on demand. I'm able through a simple python code to list the services my project has, but now I'm trying to create a new one. I got some 400 errors for field violation but when solved now get a 404 not found with no further explanation.
My code is the following:
 import requests

project_id = ****
region = ****
service_id = ****
# Set the URL for the Cloud Run service endpoint
url = f"https://run.googleapis.com/v2/projects/{project_id}/locations/{region}/services/{service_id}"

access_token = ****
# Set the Google Cloud credentials (authentication)
headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

body = {
    "name": "",
    "description": "test",
    "generation": "1",
    "labels": {
        "cloud.googleapis.com/location": "us-central1"
      },
    "template": {
    "containers": {
        "image": f"gcr.io/{project_id}/gcr.io/****/test1:v01"
    }
  }
}

# Make the API call to get details about the Cloud Run service
response = requests.post(url, headers=headers,json=body)

# Check if the request was successful
if response.status_code == 200:
    # Parse and print the response JSON
    service_details = response.json()
    print("Service Details:")
    print(service_details)
else:
    print(f"Error: {response.status_code} - {response.text}")

My GET code works like a charm but I'm having troubles with POST. The description of the service to create is barely detailed because for now I just need it to work, I believe that's not what is braking the code.
The response is:
Error: 404 - <!DOCTYPE html>
as I mentioned earlier.
I'm having such a bad time finding clear documentation or tutorials so please help me.
I tried switching around parameters and values. I expect someone that does this kind of implementation can help or guide me.
Comment: I recommend using the CLI `gcloud` and adding the command arg `--log-http` to see how Google executes commands. This will save you heaps of time trying to figure out URLs, query params, and request bodies. Also, see Ben's answer for the 404 error.
Answer: You have the wrong URL
So first, I'd recommend you use the client library instead of building the request manually if you can. But if you do want to craft it by hand, the documentation is here. You'll need to send a POST to https://run.googleapis.com/v2/projects/{project_id}/locations/{region}/services (note the service ID isn't included here) with the serviceId as a query param and the body being the Service resource.
Comment: Oh yeaaah, it's a query param! My bad. I'll try later and let you know. I tried with the client library but it would take me longer to figure out how to make it work and in the end I need a url query because it will need to be embedded on a web page.
Thank you so much!


How to print the first google search result link using bs4?

Question: I'm a beginner in python, I'm trying to get the first search result link from google which was stored inside a div with class='yuRUbf' using beautifulsoup. When I run the script output is 'None' what is the error here.
import requests
import bs4

url = 'https://www.google.com/search?q=site%3Astackoverflow.com+how+to+use+bs4+in+python&sxsrf=AOaemvKrCLt-Ji_EiPLjcEso3DVfBUmRbg%3A1630215433722&ei=CR0rYby7K7ue4-EP7pqIkAw&oq=site%3Astackoverflow.com+how+to+use+bs4+in+python&gs_lcp=Cgdnd3Mtd2l6EAM6BwgAEEcQsAM6BwgjELACECc6BQgAEM0CSgQIQRgAUMw2WPh_YLiFAWgBcAJ4AIABkAKIAd8lkgEHMC4xMC4xM5gBAKABAcgBCMABAQ&sclient=gws-wiz&ved=0ahUKEwj849XewdXyAhU7zzgGHW4NAsIQ4dUDCA8&uact=5'

request_result=requests.get( url )
soup = bs4.BeautifulSoup(request_result.text,"html.parser")
productDivs = soup.find("div", {"class": "yuRUbf"})
print(productDivs)

Answer: As you want first google search in which class name which you are looking for might be differ with name so first you can first find manually that link so it will be easy to identify
import requests
import bs4

url = 'https://www.google.com/search?q=site%3Astackoverflow.com+how+to+use+bs4+in+python&sxsrf=AOaemvKrCLt-Ji_EiPLjcEso3DVfBUmRbg%3A1630215433722&ei=CR0rYby7K7ue4-EP7pqIkAw&oq=site%3Astackoverflow.com+how+to+use+bs4+in+python&gs_lcp=Cgdnd3Mtd2l6EAM6BwgAEEcQsAM6BwgjELACECc6BQgAEM0CSgQIQRgAUMw2WPh_YLiFAWgBcAJ4AIABkAKIAd8lkgEHMC4xMC4xM5gBAKABAcgBCMABAQ&sclient=gws-wiz&ved=0ahUKEwj849XewdXyAhU7zzgGHW4NAsIQ4dUDCA8&uact=5'

request_result=requests.get( url )

soup = bs4.BeautifulSoup(request_result.text,"html.parser")

Using select method:

I have used css selector method in which it identifies all matching
divs and from list i have taken from index postion 1

And than i have use select_one to get a tag and find href
according to it!

main_data=soup.select("div.ZINbbc.xpd.O9g5cc.uUPGi")[1:]
main_data[0].select_one("a")['href'].replace("/url?q=","")

Using find method:
main_data=soup.find_all("div",class_="ZINbbc xpd O9g5cc uUPGi")[1:]
main_data[0].find("a")['href'].replace("/url?q=","")

Output [Same for Both the Case]:
'https://stackoverflow.com/questions/23102833/how-to-scrape-a-website-which-requires-login-using-python-and-beautifulsoup&sa=U&ved=2ahUKEwjGxv2wytXyAhUprZUCHR8mBNsQFnoECAkQAQ&usg=AOvVaw280R9Wlz2mUKHFYQUOFVv8'

Comment: Yes correct for above car URL it is identifies divs but problem is that URL containing in first index is not same as from Web page in that case you can use try and except block to first call URL from and if status_code is not 200 then you can go for next index
Comment: Find method works well but when I change the "url" again the output is invalid
Comment: beacuse the class name may be differ from that so it will not be always same class name
Comment: then what is solution that works with all url? when I inspect I get the same class on all page 'class="yuRUbf"
Comment: can you share URL again please for reference
Comment: here it is: https://www.google.com/search?q=site%3Astackoverflow.com+how+to+use+bs4+in+python&oq=&aqs=chrome.0.69i59i450l8.92637j0j1&sourceid=chrome&ie=UTF-8
Comment: it is working i have checked with above URL
Comment: can you please check with this one: https://www.google.com/search?q=cars&oq=cars&aqs=chrome.0.69i59j69i61j69i60l2.3087j0j1&sourceid=chrome&ie=UTF-8
Answer: Let's see:
    from bs4 import BeautifulSoup
import requests, json

headers = {
    'User-agent':
    "useragent"
}

html = requests.get('https://www.google.com/search?q=hello', headers=headers).text
soup = BeautifulSoup(html, 'lxml')
# locating div element with a tF2Cxc class
# calling for  tag and then calling for 'href' attribute
link = soup.find('div', class_='tF2Cxc').a['href']
print(link)

output:
'''
https://www.youtube.com/watch?v=YQHsXMglC9A


discord.js - bot get kicked out of voice channel event

Question: What I tried to do for my music bot was getting him to report when he gets kicked out of a voice channel, by saying for example "I was forcefully disconnected". I didnt find a useful property or method to check this, so I asked for help to some friends and tried this:
client.on('voiceStateUpdate', (oldMember, newMember) => {
      let newUserChannel = newMember.voiceChannel

      if (newUserChannel === undefined) return console.log("I was kicked from the voice channel")
    })

It didnt work.
So, is there any way to solve my problem?
Answer: I had the same proble some time ago.
This is the way i used to solve it:
Client.on('voiceStateUpdate', (oldState, newState) => {

  // Represents a mute/deafen update
  if(oldState.channelId === newState.chanelId) return console.log('Mute/Deafen Update');

  // Some connection
  if(!oldState.channelId && newState.channelId) return console.log('Connection Update');

  // Disconnection
  if(oldState.channelId && !newState.channelId){
    console.log('Disconnection Update');
    // Bot was disconnected?
    if(newState.id === Client.user.id) return console.log(`${Client.user.username} was disconnected!`);
  }
});

Since the voiceStateUpdate event is fired in everything related to voice channels, you should add as much scenarios as possible to make things work as intended.
Comment: sorry but this doesnt work, it doesnt give me any responses or errors, only the mute deaf works but I currently dont need it
Comment: Do you have GUILD_VOICE_STATES intent?


Mangled and flickering graphics on Yoga 910 with 1920x1080 resolution

Question: I've just installed Ubuntu 16.10 on a Lenovo Yoga 910 and have found that when I set the resolution to its native 1920x1080, the display immediately starts flickering and becoming mangled/visually corrupted. Moving the mouse around appears to sometimes make it less horrible, but it's essentially unusable. The same thing happens at the login screen and also when I switch to a different tty.
I'm running the latest Intel i915, updated with the Intel Graphics Update Tool for Linux, and I've tried running with the AccelMethod as both SNA and UXA.
IS there anything I can do to isolate the cause of the problem?
The output of lspci -nnk | grep -iA2 VGA gives me this:
00:02.0 VGA compatible controller [0300]: Intel Corporation Device [8086:5916] (rev 02)
Subsystem: Lenovo Device [17aa:3801]
Kernel driver in use: i915

Comment: Can you post a picture of your mangled screen? (Taken with a camera, because a screenshot is most likely to look just fine.)
Answer: As per this bug, the problem seems to be associated with a power saving feature of the GPU. Disabling this feature through the kernel parameter i915.enable_rc6=0 completely fixed the problem for me.
In my travels, I also found another kernel parameter people have also used to fix screen flickering issues (i915.enable_psr=0), however I didn't need this one.
Comment: nedned - the proposed solution causes my fan to run excessively (and excessively high) on the Yoga 910 running Ubuntu.  Do you have that issue as well?  Have you revisited this and/or found a different solution?
Comment: I haven't noticed this behaviour, and since it's all working fine for me, I haven't looked into any other solutions, sorry!
Comment: After posting a bug report, I learned that the upstream kernel (v4.13.0-041300rc4-(4.13.0-041300rc4.201708062231) fixes the screen tearing without the need to edit the boot parameter.  I still experience more fan use than under 16.04, but it is not as high and not entirely constant.
Comment: Scratch that prior post!! The upstream kernel l (v4.13.0-041300rc4-(4.13.0-041300rc4.201708062231) does not fix the problem.  Rather, reverting to kernel 4.4 does.  I had one to many bourbons when I did `uname -r`.
Answer: Here are two things you can try:

Try the other AccelMethod options, that partially or totally disable hardware acceleration: blt or even none. On modern hardware, this may be perfectly usable (did not try it myself).
Actually remove the xserver-xorg-video-intel driver! The Intel driver is made of three parts (the i915 kernel driver, the 3D driver in MESA, and the xserver-xorg-video-intel DDX driver that accelerates 2D rendering under X.Org). When the DDX driver is not installed, X.Org falls back to modesetting, which uses OpenGL to do the acceleration and should work fine on modern hardware.

Note that Debian discourages the use of the Intel DDX driver on post-2007 hardware, so removing it is not as crazy as it seems. I have not tried it myself (but I intend to, because I have issues on a NUC).
Comment: Then we need to investigate the `i915` driver and its options (kernel command-line).
Comment: Thanks heaps for the suggestions. Unfortunately, none of them seemed to help. I guess it does at least show that the problem is not with `xserver-xorg-video-intel`.
Comment: You are spot on! Just before you posted this comment, I came across an `i915` kernel parameter that fixed the problem. See my answer for the details. Thanks for all your help!!


If $\lim\limits_{n \to \infty} n^2(a_n)^2=5$, does $\sum_{n=1}^{\infty} a_n$ converge or diverge?

Question: If the limit given is equal to 5, then the series $\sum_{n=1}^{\infty} n^2(a_n)^2$ diverges. Also, the series  $\sum_{n=1}^{\infty} (a_n)^2$ converges through limit comparison test. But I don't know how to tie that in with  $\sum_{n=1}^{\infty} a_n$.
Comment: $n^2 a_n^2 \to 5$ means that $|a_n| \sim \frac{\sqrt{5}}{n}$ for large $n$. Now try to come up with a concrete $a_n$ which has the given limit and where the series converges and one where the series diverges. The first one should be easy. For the second one try to make an *alternating series*
Comment: @Winther so are you saying that depending on the value of $a_n$, the series either converges or diverges?
Answer: It may converge Or diverge. To see this consider the following two cases:
$${{a}_{n}}=\frac{\sqrt{5}}{n}$$   $${{a}_{n}}={{\left( -1 \right)}^{n}}\frac{\sqrt{5}}{n}$$


What is the lowest price that the Mega Stone man will sell the stones for?

Question: I'd like to buy the Mega Stones as cheap as possible. Like the title states, how low will the Mega Stone man in Lumiose City Stone Emporium drop his prices for the Starter Mega Stones?
Answer: The lowest he has gone so far for myself is $10,000. This is after I have:

Completed the Looker missions
Become a 'fully qualified attendant' at Hotel Richimme ($50,000 a job)
Completed all restaurant double/triple battle meals with the required number of moves (yet to do rotation battles)
Bought an outfit from Boutique Couture
Created 3 PR videos (one in each slot)
Received the Hatching O-power from Mr Bonding
Got a haircut
had my Furfrou styled

Here is a picture:
Comment: Pretty dang sure it's $10,000. And all you really need to do is do the "buy lots of pokeballs" at the pokeball emporium trick to get there
Comment: @BenBrocka This is what I did, you pointed this out to me before. I bought 100 premier balls, one at a time. And my style was then maxed so the price for the stones was $10K
Comment: @BenBrocka - yeah I bought about 70, and got from $100k to $50k, but I forgot to save and my battery ran out. So I avoided doing that again lol


Geometric proof of $\sin x \geq x - x^3 /6 $?

Question: We know (from Taylor expansion for example) that if $x \geq 0$, then $\sin x \geq x - \frac{x^3}{6}$.
In Prove that: $\sin(x) \cos(x) \geq x-x^3$ a geometric proof of the inequality $\sin x \geq x - \frac{x^3}{4}$ is given. Is there any geometric proof of the first one (which is slightly stronger ?
Comment: Seems like the first thing to try is to find better bounds on the red section of that drawing in the link. Have you pursued that route?
Comment: My memory is there is a sequence of decreasing values $a_i\to\frac{1}{6}$ defined inductively and geometrically so that $\sin x\geq x-a_ix^3.$ But I honestly can't recall it.
Answer: You meant this holds for acute $x$. Take a radius-$\sqrt{2}$ centre-$O$ circle of radii $OA,\,OB$ with $\angle AOB=x$. We'll work in Cartesian coordinates $X,\,Y$; rotate the diagram so the line segment $AB$, which is of length $2\sqrt{2}\sin\frac{x}{2}$, has endpoints at $$X=\pm\sqrt{2}\sin\frac{x}{2},\,Y=0,$$and let $M$ be the midpoint of the arc $AB$. The circular segment has area $x-\sin x$, which we wish to prove $\le\frac{1}{6}x^3$. We can asymptotically approximate the arc as a parabola passing through the aforementioned endpoints and $$M=\left(0,\,\sqrt{2}\left(1-\cos\frac{x}{2}\right)\right)=\left(0,\,2\sqrt{2}\sin^2\frac{x}{4}\right).$$The parabola has equation $$Y=\frac{\sqrt{2}\sin^2\frac{x}{4}}{\sin^2\frac{x}{2}}\left(2\sin^2\frac{x}{2}-X^2\right),$$so the area under the parabola is $$\frac{2\sqrt{2}\sin^2\frac{x}{4}}{\sin^2\frac{x}{2}}\frac{4\sqrt{2}\sin^3\frac{x}{2}}{3}=\frac{16}{3}\sin^2\frac{x}{4}\sin\frac{x}{2}.$$(Admittedly I had to use $\int_0^a (a^2-X^2)dX=\frac{2a^3}{3}$ there, but geometrically this is equivalent to a pyramid's volume, so look up your favourite "classical" proof of that.) Asymptotically this is approximately, but less than, $$\frac{16x^3}{3\times 4^2\times 2}=\frac{x^3}{6}.$$
Answer: Here's a simple proof,
not original by me, using calculus.
It can easily be extended
to show that the power series
for sine and cosine are enveloping,
that is successive terms
bracket the function.
Start with
this definition of
since and cosine:
$\sin' = \cos
$,
$\cos' = -\sin
$,
$\sin(0) = 0$,
$\cos(0) = 1$.
These imply
$\sin^2+\cos^2 = 1$.
For small $t$,
$1 \ge \cos(t)
\ge 0
$
so
$\sin(x)
=\int_0^x \cos(t)dt
\le x
$.
Therefore
$1-\cos(x)
=\int_0^x \sin(t) dt
\le \int_0^x t dt
= \frac{t^2}{2}
$
so
$\cos(t)
\ge 1-\frac{t^2}{2}
$.
Therefore
$\sin(x)
=\int_0^x \cos(t)dt
\ge\int_0^x (1-\frac{t^2}{2})dt
=x-\frac{x^3}{6}
$.
So we already have
$x-\frac{x^3}{6}
\le \sin(x)
\le x
$.
Answer: With reference to this link : https://youtu.be/x09IsbVZeXo you may see that the length $(x-x^3/6)$ is a bit less than sinx always , hence the result , equality when x is zero .
Comment: That video is awesome.. though on this site people prefer answers which are self contained T_T
Comment: I see yeah understandable , i just didnt want to take credit if i saw from some source
Comment: Retelling others' work is absolutely fine when attributed


Number of all squares placed side by side in a rectangle.

Question: I've been struggling lately to find out a way to calculate the number of squares in a given rectangle.
The thing is that I don't want to calculate the number of permutations of a NxN sized square in a rectangle but try to find out how many squares placed side by side of size NxN can fit into the rectangle.
For example let's assume there's given a 3x2 rectangle. That means that there can fit 6 1x1 squares and only one 2x2 square(you cannot place 2 2x2 squares at the same time without having them overlap) so the total is 7 squares.
Thanks in advance.
Answer: Suppose you have a rectangle $w$ units wide and $h$ units high,
and you place $2\times2$ squares in this rectangle.
Wherever there is an edge of any of these squares parallel to the
bottom edge of the rectangle, extend that edge into a line all the way
across the rectangle.
In this way you will divide the entire rectangle into horizontal strips
of which parts are covered by parts of the $2\times2$ squares and parts are not.
In the figure below, $2\times2$ squares
have been placed in a $9\times7$ rectangle.
The red lines cut the rectangle into strips of $9$ units from left to right
and various distances from bottom to top.

In this example the squares appear to be placed somewhat haphazardly,
but no matter how you place the squares, you cannot make more than
$4$ squares overlap any of the horizontal strips.
In general, if the width of the rectangle is $w,$
you can make at most $\lfloor w/2 \rfloor$ of the $2\times2$
squares overlap each strip.
This means that each horizontal strip contains at least
$w_2\Delta h$ area that is not covered by the
$2\times2$ squares, where
$w_2 = (w - 2\lfloor w/2 \rfloor)$ and
$\Delta h$ is the height of each strip.
(Some of the strips have an even larger area uncovered.)
If we add up the uncovered area over all the strips, we find that an
area measuring at least $w_2 h$ is uncovered.
Similarly, if we cut the rectangle into vertical strips by extending
every vertical edge of every square, we find that each strip has at least
$h_2 \Delta w$ uncovered area, where
$h_2 = (h - 2\lfloor h/2 \rfloor)$ and
$\Delta w$ is the width of the strip.
Adding this up, we find that an area of at least
$h_2 w$ is uncovered.
These two uncovered regions overlap, but only to a limited extent,
namely a total area of
$(2\lfloor w/2 \rfloor)(2\lfloor h/2 \rfloor) = (w - w_2)(h - h_2).$
The total uncovered area comes out to
$$
w_2 h + h_2 w - (w - w_2)(h - h_2) = wh - w_2 h_2.
$$
This is the same as you get if you simply arrange the $2\times2$
squares in an array $\lfloor w/2 \rfloor$ squares across and
$\lfloor h/2 \rfloor$ squares high in the lower left corner of the
rectangle.
That is to say, we have just shown (in a rigorous, though long-winded way)
that the best arrangement of the squares is just to stack them
in continuous rows, leaving a gap (if necessary) along two edges of
the rectangle.
The total number of squares in the array fitted in this way is
$\lfloor w/2 \rfloor \times \lfloor h/2 \rfloor.$
If we generalize this to $N\times N$ squares in a $w\times h$ rectangle,
the maximum number of squares of that size is
$\lfloor w/N \rfloor \times \lfloor h/N \rfloor.$

Now that we know how to count the number of squares of size $N\times N,$
we can write the algorithm to compute the total number of squares as
requested in the question. The answer is
$$ \sum_{N=1}^\infty \left(\left\lfloor\frac WN\right\rfloor \times \left\lfloor\frac HN\right\rfloor\right), $$
which counts all possible $1\times 1$ squares, then all possible $2\times 2$ squares, then $3\times 3,$ and so forth until we come to a square that is so large that not even one such square can fit in the rectangle.
For that $N$ and any larger $N$ the product
$\lfloor w/N \rfloor \times \lfloor h/N \rfloor$ is zero, so we only
need to add a finite number of terms.
Comment: You are justifying that the greedy algorithm works for packing a given size of square.  You just pack the squares as tightly as possible into one corner and when you can't pack any more you are done for that size.  Then you need to sum over sizes and you are done. +1
Answer: For a rectangle of size $M \times N$, maximum number $\mathcal{N}(n;M \times N)$ of $n \times n$ sized squares placed adjacent to each other is can be arrived at as :
$$\mathcal{N}(n;M \times N)=\mathcal{C}(M,n)\mathcal{C}(N,n),$$
where $\mathcal{C}(M,n)=\big[\frac{M}{n}\big]$ and $[]$ is the lower ceiling function.
Then total number of squares that can be placed is :
$$\sum_{n=1}^{\min\{M,N\}}\mathcal{N}(n;M \times N)=\sum_{n=1}^{\min\{M,N\}}\mathcal{C}(M,n)\mathcal{C}(N,n)=\sum_{n=1}^{\min\{M,N\}}\Bigg[\frac{M}{n}\Bigg]\Bigg[\frac{N}{n}\Bigg].$$
Comment: Is it obvious that the greedy algorithm you describe packs as many squares into the rectangle as possible?  I think it needs some support.  Having done that, yours is the only answer that reflects the sum over sizes of squares.  +1
Comment: @RossMillikan I had written it down based on intuitive observation. I don't know how to explain it.
Answer: $\require{begingroup} \begingroup
\newcommand{idiv}[2]{\left\lfloor\frac{#1}{#2}\right\rfloor}
\newcommand{R}{\mathcal R} \newcommand{L}{\mathcal L}
\newcommand{S}{\mathcal S}
$This answer is based on an answer to a related question,
but generalized to account for uniform squares of any size within a rectangle of any size. The sides of the rectangle do not even need to be commensurate with the sides of the squares.
It is assumed, however, that all squares placed in the rectangle are placed with their sides parallel to the sides of the rectangle.
(It seems intuitively obvious that rotating the squares will not enable more squares to fit in the rectangle, but proving it is another matter.)
Given a rectangle $\R$ of width $W$ and height $H,$ where $W$ and $H$ may be any real numbers, we first determine how many squares of side $N$ can fit in rectangle $\R$ without overlapping.
That is, the sides of squares may touch other squares or the edges of the rectangle, but the interior of any square cannot intersect another square or the boundary of the rectangle.
We can show that the maximum number of squares that can be arranged in rectangle $\R$ in this way is $\idiv WN \times \idiv HN.$
The following proof does this by constructing a rectangular lattice $\L$ of
$\idiv WN \times \idiv HN$ points such that in any such arrangement of squares inside $\R,$ each square must contain at least one point of $\L.$
Proof.
Choose a Cartesian coordinate system such that the vertices of rectangle $\R$ are at coordinates $(0,0),$ $(0,W),$ $(H,W),$ and $(0,H).$
Let
\begin{align}
w &= \frac{W}{\idiv WN + 1}, \\[0.7ex]
h &= \frac{H}{\idiv HN + 1},
\end{align}
and let $\L$ be the set of points $(jw, kh)$ where $j$ and $k$ are integers,
$1 \leq j \leq \idiv WN,$ and $1 \leq k \leq \idiv HN.$
In other words, we can tile rectangle $\R$ completely with rectangles of
width $w$ and height $h,$ and let the set $\L$ consist of all vertices of these rectangles that are in the interior of rectangle $\R.$
The points of $\L$ then form a rectangular lattice with
$\idiv WN$ points in each row and $\idiv HN$ points in each column,
a total of $\idiv WN \times \idiv HN$ points altogether.
Since $\idiv WN + 1 > \frac WN,$ it follows that $w < N,$ and similarly
$h < N.$
Therefore if we place a square $\S$ of side $N$ anywhere within rectangle $\R$ with sides parallel to the sides of $\R,$
at least one of the lines through the rows of points in $\L$ will pass through the interior of $\S,$ and at least one of the lines through the columns of points in $\L$ will pass through the interior of $\S;$ therefore $\S$ will contain the point of $\L$ at the intersection of those lines.
That is, the interior of $\S$ must contain at least one point of the set $\L.$
Suppose now we have placed some number of squares of side $N$ inside
rectangle $\R$ so that no two squares overlap
(their boundaries may touch but their interiors must be disjoint).
Then no two of these squares can both contain the same point of the set $\L.$
By the pigeonhole principle, we can place at most
$\lvert\L\rvert = \idiv WN \times \idiv HN$ squares in this way.
On the other hand, an array of squares with $\idiv HN$ rows
and $\idiv WN$ columns fits inside rectangle $\R$
(using the "greedy algorithm"),
so it is possible to achieve the upper bound of $\idiv WN \times \idiv HN$
squares. This completes the proof. $\square$
In the question, however, we are allowed to arrange squares of side $1$ inside the rectangle, then ignore them and arrange squares of side $2$ inside the rectangle, then ignore those squares and arrange squares of side $3,$ and so forth, as long as at least one square can fit inside the rectangle;
and then the answer is the total number of squares of all sizes that were arranged in this way.
The final answer therefore is
$$
\sum_{N=1}^\infty \left(\idiv WN \times \idiv HN\right).
$$
Note that this is actually a finite sum, since for $N > W$ or $N > H$
all terms will be zero.
The last non-zero term of the sum is the term for
$N = \min\{\lfloor W\rfloor, \lfloor H\rfloor\}.
\endgroup$
Answer: If the rectangle has size $ m\times n $ then you can fit in $ \lfloor m/N \rfloor × \lfloor n / N \rfloor $ squares of size $ N\times N $.
The idea: Fit as many squares as possible into the rectangle. Now look at the strip consisting of the top N rows. If a square meets this strip we can push it upwards so that it is fully contained in the strip. Therefore, by maximality, the strip contains $ \lfloor n / N  \rfloor $ squares.
Now remove the top strip altogether and proceed via induction.


Set place of each bar in matplotlib

Question: This is working code. It creates bars of specific length.
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30,
        'Python':35}
courses = list(data.keys())
values = list(data.values())

fig = plt.figure(figsize = (10, 5))

# creating the bar plot
plt.bar(courses, values, color ='maroon',
        width = 0.4)

plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()

But I need more options. In future I will create animation of these bars. They will move left and right. So I want to set place of bar on x axis.
How can I do it?
My desired result looks like this (when I set place by my own)
Answer: To do what you are looking for - setting each bar at a specific place in the x-axis, you need to use set_x() for each of the bars. You can get this using container.get_children() and then move it around.
Note that I have the data as a dataframe and added a column called pos. This will define the distance of each bar from x-axis - zero. Plot the bars, then use set_x() to move the bars and plt.xlim() and plt.xticks() to align the ticks and labels. Hope this is what you are looking for...
# creating the dataset - Using dataframe and adding pos column for distance from zero
data = {'courses' : ['C', 'C++', 'Java', 'Python'], 'values' : [20, 15, 30, 35], 'pos' : [2, 3, 5, 7]}
df=pd.DataFrame(data)

fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(df['courses'], df['values'], color ='maroon', width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")

## Set xlim from 0 to largest value plus 0.5 to show all bars
plt.xlim(0, df.pos.max()+0.5)

## Access each bar and set the position based on value in df.pos
for container in plt.gca().containers:
        for i, child in enumerate(container.get_children()):
            child.set_x(df.pos[i]-0.2) ## 0.2 as you set width=0.4

##Adjust ticks and ticklabels
plt.xticks(ticks=df.pos, labels=df.courses)
plt.show()

Answer: Maybe you just need to re-order the keys of your dictionnary ?
d = {k: data[k] for k in ["Java", "C++", "Python", "C"]} # <-- re-ordered `data`
P = [3, 5, 8, 13] # <-- positions of each bar/x-tick
W = 1.5 # <-- width of the bars

plt.figure(figsize=(7, 4))

plt.bar(P, d.values(), color="maroon", width=W)

plt.xticks(P, d.keys())
plt.xlim(0, max(P) + W)

Output :

Set place of each bar in matplotlib


SQL group dates as week date

Question: I have a table which contains func_id  and date in format like (07.06.14 ). I am trying to create a function that returns the number of dates that is the week day of a date (07.06.14 ) and the func_id will equals the func_id that I will write. For example:
My table:
         func_id   11 / date = 07.06.14
That will return 1 from 0. (Saturday code = 0);
I tried:
<code> function Get_weekday($data){
$dat = explode(".",$data);
$date = date("l", mktime(0, 0, 0, $dat[0]  , $dat[1], $dat[2]));
if($date == "Monday"){return 4;}
if($date == "Tuesday"){return 3;}
if($date == "Wednesday"){return 2;}
if($date == "Thursday"){return 1;}
if($date == "Friday"){return 0;}
if($date == "Saturday"){return 0;}
if($date == "Sunday"){return 0;}
}
function count_per_date($func_id,$day){
$result = mysql_query("SELECT COUNT(date) as data,date FROM entregas WHERE func_id = '$func_id' GROUP BY date");
while($row = mysql_fetch_assoc($result))
{
 //That part I dont really know what to do
}}
</code>
Sorry for my english, I dont speak very well ):
Comment: Which database/ what sql dialect are you using? In most cases there is predefined function which does exactly the thing you want
Answer: You're looking for DAYOFWEEK
Example
<code>SELECT DAYOFWEEK('2007-02-03');
</code>
Further info : DAYOFWEEK documentation

SQL group dates as week date


Run Command before automatic backup

Question: I've been using the Deja Dupe to run automatic backups on my system.  The problem I'm having is my server at work occasionally times out and essentially un-mounts my windows shares from Nautilus.  I'd like to find a way to run nautilus smb://windowsmountpoint before it Deja Dupe runs the automatic backup.  I can't imagine this feature not existing, I just don't know how to do it!
Answer: There probably is a way but it's probably not that pretty. I'd probably suggest making the connection to the server more reliable.
I'd suggest something like an /etc/fstab-cifs mount like this:
//servername/sharename  /media/mountname  cifs  guest,uid=1000,iocharset=utf8,codepage=unicode,unicode  0  0

You can tailor that to use credentials if you need.
If that's still dropping off, you can use autofs which is great for dynamically mounting things.
Comment: That way makes a lot more sense, however I get mount error(115) after running sudo mount -a with that in fstab.  Any ideas?

Run Command before automatic backup


Can I find unique dwellers in the outlands using the radio station?

Question: I was wondering, after I've received a unique dweller (Three Dog) in a lunchbox, if there is a way to attract those special/unique dwellers even through the radio stations from the outlands.
Do you ever have received some of the unique dwellers from the outlands?
Comment: I have the same question and I am not sure if they are an exclusive of the lunch boxes. I know I have gotten the rare gear from exploring which can also come out of the lunch boxes but so far, no rare/specific people have come to my vault. Interesting to see if they are only from the boxes.
Answer: I can confirm that you may attract unique dwellers on the radio as I got Butch just yesterday.
Comment: Also, if you think an existing answer is correct, the best way to show it is to upvote it.
Comment: I'm not sure what's wrong with his answer, he has addressed a part of the question the other answer didn't (unique dwellers via radio), and didn't address any other answers. I don't see that it's been edited either...?
Comment: Having someone who encounter that submit a screenshot would go a long way clearing this up.
Answer: I have found between 20 and 30 Dwellers via Radio Station signals, and none of them have been unique characters.  From what I have read on other sites, it appears unique dwellers can only be obtained via lunchboxes.  If I see or find out otherwise, I will change this answer.
As an interesting aside: "unique" characters are not actually unique. Somewhat amusingly, you can find multiples of the same unique character in lunchboxes.
Comment: I have 4 different (not so different) Eulogy Jones walking around my vault. So much for unique.
Comment: You could rename them to be unique. Did all 4 have the same starting stats? Same equipment?
Comment: Interesting to know. Well, they are some kind of unique like unique weapons in nearly all other games. :-D
Comment: That's why they're called [**Legendary** dwellers](http://www.bethblog.com/2015/06/30/fallout-shelter-a-legendary-dweller-from-the-commonwealth/comment-page-1/#comment-424313), and not "unique". :)
Answer: Unless you can get rare dwellers on the radio the only purpose for dwellers from the radio is to get new DNA in your vault. You can breed for better dwellers and their are some special pet that give +1-3 to the stats of a child and their are explorer quests and quests that give higher stat dwellers and breeding rare with rare seem to produce some more rares and i have had some luck with breeding new arrivals with the highest same stat to each other.


RemoteIO and Recording AAC on iOS 6

Question: Is anyone using RemoteIO for recording AAC audio on iOS 6? I've noticed that when I'm doing this, it kills the media server on interruption and my interruption callbacks are never called on iOS 6.0.
Also, because the media server goes down, it makes recovering a bit difficult.
Is anyone else seeing this or worked around it?
Comment: The AudioSessionInterruptionListener callback does get called for kAudioSessionBeginInterruption on my iOS 6 iPhone 5 test device.
Comment: Wished it worked for me. Even setting an interruptListenser doesn't get called... may be due to the fact that mediaserverd is crashing before it even gets to the callback. Wondering if there's something weird with my setup that causes it to crash on interrupts. Are you using RemoteIO in your app?
Comment: Yes, I'm using RemoteIO with a play-and-record audio session.  But the app is recording strictly raw audio.  No codec.
Comment: Yep, it has something to do with the codec. When I don't use the ExtAudioFile (which contains the converter), it hits the interrupts. Oy.
Answer: Problem solved. Use the software codec:
<code>// specify codec
UInt32 codec    = kAppleSoftwareAudioCodecManufacturer;
int codecSize   = sizeof(codec);
status          = ExtAudioFileSetProperty(recorderState.audioFile,
                                          kExtAudioFileProperty_CodecManufacturer,
                                          codecSize,
                                          &codec);
</code>
Before I was using kAppleHardwareAudioCodecManufacturer... evidently the hardware codec can't handle interruptions. Hope others find this useful!
Answer: I am having a similar problem.  I am trying to record AAC audio using remoteio, for pretty much all the same reasons you described here:
http://lists.apple.com/archives/coreaudio-api/2012/Oct/msg00135.html
My current problem isn't even with interuptions.  If I dispose of my audio unit and set my audio session to inactive on being moved to the background, I still have the media server get killed when I try to reactivate my session when the app reloads.
My basic flow that is dying is this:
- set up an active audio session for recording
- setup an audio unit & and file in preparation for the user pressing the 'record' button
- user backgrounds the app, in order to tear down everything I dispose of my audio unit and deactivate my session, but I don't clean up my extaudiofile at this point
- I open voice memos, and then immediately close it
- reopen my app and hit record.
- when I try and set the session to active, mediaserverd dies.  Switching to the software codec didn't fix it!
If you have learned any more about this craziness I would love to hear what you figured out.
Thanks.

RemoteIO and Recording AAC on iOS 6


how do I validate a JSON payload in OpenAPI 3.0 with Mule 4.4 Runtime

Question: I need to develop a Mule API ( 4.4 Runtime ) with openapi: 3.0.0
The endpoint is a POST with the following request payload :
{
  "Employee": {
     "Address": {
        "City": "a",
        "Country": "aaa"
      }
  }
}

Here is the relevant section of the OpenAPI 3.0 spec :
    openapi: "3.0.0"
paths:
  /search:
    post:
      tags:
      - SearchUser
      summary: Search for Users
      operationId: getUser
      requestBody:
        description: User Request Object
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RequestComp'
        required: true
      responses:
        '200':
          description: successful operation
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/ResponseComp'
        '400':
          description: Bad request
          content: {}
        '404':
          description: User not found
          content: {}
        '405':
          description: Validation exception
          content: {}

components:
  schemas:
    RequestComp:
      type: object
      properties:
        Employee:
          $ref: '#/components/schemas/EmployeeComp'
    EmployeeComp:
      type: object
      properties:
        Address:
          $ref: '#/components/schemas/AddressComp'
    AddressComp:
      type: object
      properties:
        City:
          type: string
          required: true
          nullable: false
          minLength: 1
        Country:
          type: string
          required: true
          nullable: false
          minLength: 1
    ResponseComp:
      type: object
      properties:
        City:
          type: string
        Country:
          type: string

So I can validate individual elements like 'City' and 'Country' to not be null  but how do I prevent following request ? ( presently its not being flagged as invalid : )
    {
        "Address": {
           "City": "a",
           "Country": "aaa"
        }
    }

Answer: You can define the Employee wrapper as a required property and also disallow unknown properties by adding additionalProperties: false. Note that required is not a property-level attribute, but an object-level attribute - it's a list of required properties.
components:
  schemas:
    RequestComp:
      type: object
      required: [Employee]         # <-----
      properties:
        Employee:
          $ref: '#/components/schemas/EmployeeComp'
      additionalProperties: false  # <-----

    EmployeeComp:
      type: object
      properties:
        Address:
          $ref: '#/components/schemas/AddressComp'
      additionalProperties: false  # <-----

    AddressComp:
      type: object
      required: [City, Country]    # <-----
      properties:
        City:
          type: string
          # required: true    # <-- remove this
          nullable: false
          minLength: 1
        Country:
          type: string
          # required: true    # <-- remove this
          nullable: false
          minLength: 1
      additionalProperties: false  # <-----


How does every real number have a decimal representation?

Question: I am a little bit confused at how every real number can have at least one decimal representation, because:

There are uncountable many real numbers
There are countable strings of infinite length over a finite alphabet

I would expect that there can be no injection from the real numbers to the infinite strings over <code>{0,1,2,3,4,5,6,7,8,9,.}</code>.
Is there a mistake in my assumption or reasoning? Does this only mean that some different real numbers must have the same decimal representation?
Comment: The second statement is false even for the alphabet {$0,1$} Cantor's diagonal method shows that there are uncountable many infinite long words. The set of finitely long words over some finite alphabet however is countable.
Answer: Your second point is not correct. There are uncountably many strings of infinite length, even though there are only countably many strings of finite but unbounded length. This makes sense because the latter correspond to terminating decimals, which are a subset of the rationals.
You can see by diagonal argument that the set of infinite strings is uncountable: assume it is countable, and order the strings $s_1,s_2,\ldots$, then construct a string which is different to $s_1$ in position $1$, different to $s_2$ in position $2$, and so on.
Answer: The number of digits in any given infinite decimal representation is countably infinite (and equal to the cardinality of the naturals).
The number of possible infinite decimal representations is uncountably infinite (and equal to the cardinality of the continuum).


How can I get Visual Studio Typescript 1.7 intellisense to work with nodejs libraries (angular2, rxjs)?

Question: [SOLVED]
I logged a bug against TypeScript and the fix should be rolled up into the next VS plugin release.  Essentially you can get intellisense to work if you specify your module resolution to be "NodeJs".  However the compiler doesn't like this because it expects it to be "node".  It looks like the fix they're making is to make everything work by specifying "Node".

I'm trying to build an Angular2 project with msbuild because I want to use ASP.Net Web API as my back-end.  The code compiles and runs fine, but my editor (SublimeText 3 or Visual Studio 2015) doesn't like the way I import the Angular2 libraries:
boot.ts:
import {bootstrap} from 'angular2/platform/browser';  // error: cannot find module
import {AppComponent} from './app.component';
bootstrap(AppComponent, []);

If I run the same example (Angular2 Hero Tutorial) using the TypeScript compiler directly with a tsconfig.json and node lite-server as documented, then SublimeText3 works and can recognize this syntax just fine.  However once I switch to msbuild, I get this intellisense error for some reason.  Here's other pieces of my project which I think are relevant:
Folder structure:
\
  - index.html
  - package.json
  \app
      - boot.ts
      - app.component.ts
  \node_modules
      \angular2
          \platform
              - browser.js
              - browser.d.ts

package.json:
{
  "name": "angular2-webapi",
  "version": "1.0.0",
  "scripts": {
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.0",
    "systemjs": "0.19.6",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.10"
  },
  "devDependencies": {
    "typescript": "^1.7.3"
  }
}

TypeScript compiler section from csproj file (most of this was copied from the Angular2 Hero tutorial tsconfig file, but some of these were set by VS automatically):
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
  <TypeScriptTarget>ES5</TypeScriptTarget>
  <TypeScriptJSXEmit>None</TypeScriptJSXEmit>
  <TypeScriptCompileOnSaveEnabled>True</TypeScriptCompileOnSaveEnabled>
  <TypeScriptNoImplicitAny>False</TypeScriptNoImplicitAny>
  <TypeScriptModuleKind>System</TypeScriptModuleKind>
  <TypeScriptRemoveComments>False</TypeScriptRemoveComments>
  <TypeScriptGeneratesDeclarations>False</TypeScriptGeneratesDeclarations>
  <TypeScriptNoEmitOnError>True</TypeScriptNoEmitOnError>
  <TypeScriptSourceMap>True</TypeScriptSourceMap>
  <TypeScriptExperimentalDecorators>true</TypeScriptExperimentalDecorators>
  <TypeScriptModuleResolution>node</TypeScriptModuleResolution>
  <TypeScriptEmitDecoratorMetadata>true</TypeScriptEmitDecoratorMetadata>
</PropertyGroup>

I've also tried changing the way I reference the Angular2 libraries like below since it matches the actual physical path of the browser script, but unfortunately the generated file doesn't add the ".js" extension to the generated dependency list for some reason.  This means that the browser will request the file "browser" instead of "browser.js".
This breaks the runtime:
import {bootstrap} from '../node_modules/angular2/platform/browser';

I'm actually not sure how the system is supposed to know how to resolve the 'angular2/platform/browser' syntax, but it seems to work if I don't use msbuild.  And given the fact that this code compiles and runs properly, it seems like it should work in my editor as well.  Anyone have any ideas?
Comment: Webstorm EAP does that out of the box, and its free because its a pre-release version -> https://confluence.jetbrains.com/display/WI/WebStorm+EAP
Comment: Thanks.  I'm actually only using Visual Studio because I want to be able to debug my ASP.Net Web API project locally.  I also want to point out that this appears to be build-specific and not editor specific since I run into this problem with SublimeText which normally works if I don't use msbuild.  I've updated the question to reflect that information.
Answer: As far as project property group is set to
<TypeScriptModuleResolution>NodeJs</TypeScriptModuleResolution>

there is a workaround is to modify Microsoft.Typescript.targets.
It makes compiler to work:
<TypeScriptBuildConfigurations Condition="'$(TypeScriptModuleResolution)' != ''">$(TypeScriptBuildConfigurations) --moduleResolution $(TypeScriptModuleResolution)</TypeScriptBuildConfigurations>

hardcoded as
<TypeScriptBuildConfigurations Condition="'$(TypeScriptModuleResolution)' != '' and '$(TypeScriptModuleResolution)' != 'NodeJs'">$(TypeScriptBuildConfigurations) --moduleResolution $(TypeScriptModuleResolution)</TypeScriptBuildConfigurations>
<TypeScriptBuildConfigurations Condition="'$(TypeScriptModuleResolution)' == 'NodeJs'">$(TypeScriptBuildConfigurations) --moduleResolution node</TypeScriptBuildConfigurations>

PS make sure to take a backup of Microsoft.Typescript.targets
Comment: Thanks Andrew.  It looks like that would probably work as a short term solution, but I don't think I'm going to use it because it would require modifying a global targets file.  Since I'm going to be publishing this to a hosted service, I won't have access to that file.  For now I'll probably just use Sublime with a tsconfig file and wait for an update to the TS plugin for VS.  I appreciate the help though.
Answer: This does appear to be a bug in typescript tooling as @AndrewSorokin describes, but instead of editing Microsoft.Typescript.targets, you can override the incorrect code in your project file.  Add the following lines to the end of your project file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <TypeScriptModuleResolution>NodeJs</TypeScriptModuleResolution>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
    <TypeScriptModuleResolution>NodeJs</TypeScriptModuleResolution>
  </PropertyGroup>

  <PropertyGroup>
    <CompileTypeScriptDependsOn>
      SpoofTypeScriptModuleResolution;
      $(CompileTypeScriptDependsOn)
    </CompileTypeScriptDependsOn>
  </PropertyGroup>
  <Target Name="SpoofTypeScriptModuleResolution">
    <PropertyGroup>
      <TypeScriptBuildConfigurations>$(TypeScriptBuildConfigurations.Replace('--moduleResolution NodeJs', '--moduleResolution node'))</TypeScriptBuildConfigurations>
    </PropertyGroup>
    <Message Text="Options: $(TypeScriptBuildConfigurations)" />
  </Target>
</Project>


Sequelize: how to set PK of join table as pair of foreign keys to be able to use save() on the join table instance without triggering 'no PK error'?

Question: How to make Sequelize treat foreign keys of join table as composite primary key? I thought that it is done by default, but when I tried to save my UserMenuItem instance (which is join table between User and MenuItem),  got this error: Error: You attempted to save an instance with no primary key, this is not allowed since it would result in a global update.
My associations are defined as follows:
 models.User.hasMany(models.UserMenuItem, { foreignKey: 'userID', onDelete: 'CASCADE' });
 models.UserMenuItem.belongsTo(models.User, { foreignKey: 'userID', onDelete: 'CASCADE' });

 models.MenuItem.hasMany(models.UserMenuItem, { foreignKey: 'menuItemID', onDelete: 'CASCADE' });
 models.UserMenuItem.belongsTo(models.MenuItem, { foreignKey: 'menuItemID', onDelete: 'CASCADE' });

 models.MenuItem.belongsToMany(models.User, { through: models.UserMenuItem, foreignKey: 'menuItemID', onDelete: 'CASCADE' }); // I tried adding "otherKey: 'userID'" as well
 models.User.belongsToMany(models.MenuItem, { through: models.UserMenuItem, foreignKey: 'userID', onDelete: 'CASCADE' }); I tried adding "otherKey: 'menuItemID'" as well

I'm not including models definitions as I don't think they are relevant. User and MenuItem have a PK called ID and the join table has some additional data fields except for FKs.
Is it at all possible, or do I have to add unnecessary PK to the join table?
Answer: You cannot define composite primary key.

Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using uniqueKey option.

See BelngToMany in official docs
Comment: Ok, thanks. Another disappointment from Sequelize. I'll add the PK separately then...
Answer: Even I had this same situation I got it solved by passing id whenever we save the model instance.


Re-order and re-id existing records into a new table of same structure

Question: I have a table named "table_name" with several columns, including id (type=INT, autoincrement, primary) and date (type=datetime formatted Y-m-d h:m:s).
The id don't match the chronological order of the datetime column, because once the table was merged with another table. I don't mind having gaps in the id count, but I'd like to have it at least chronological based on the column "date".
In case that might help, I have already prepared an empty table with the exact same format as the original reference table, named let's say "table_name_new".
So how is it possible to achieve the reassigning of the index id values?
PHP or SQL, both are welcome.
Current state (example):
+----+--------+---------------------+
| id | color  | date                |
+----+--------+---------------------+
| 1  | blue   | 2019-05-06 20:30:00 |
| 2  | orange | 2019-05-12 10:30:00 |
| 8  | yellow | 2019-05-18 22:30:00 |
| 4  | white  | 2019-05-29 12:30:00 |
| 9  | black  | 2019-06-10 09:30:00 |
| 10 | green  | 2019-06-14 08:30:00 |
| 3  | red    | 2019-06-24 17:30:00 |
| 5  | purple | 2019-07-05 10:30:00 |
| 7  | brown  | 2019-08-09 19:30:00 |
| 6  | grey   | 2019-09-12 20:30:00 |
+----+--------+---------------------+

Desired result:
+----+--------+---------------------+
| id | color  | date                |
+----+--------+---------------------+
| 1  | blue   | 2019-05-06 20:30:00 |
| 2  | orange | 2019-05-12 10:30:00 |
| 3  | yellow | 2019-05-18 22:30:00 |
| 4  | white  | 2019-05-29 12:30:00 |
| 5  | black  | 2019-06-10 09:30:00 |
| 6  | green  | 2019-06-14 08:30:00 |
| 7  | red    | 2019-06-24 17:30:00 |
| 8  | purple | 2019-07-05 10:30:00 |
| 9  | brown  | 2019-08-09 19:30:00 |
| 10 | grey   | 2019-09-12 20:30:00 |
+----+--------+---------------------+

Comment: `I don't mind having gaps in the id count, but I'd like to have it at least chronological based on the column "date".` Why?
Comment: @Daniel Do you have these id(s) used anywhere else in other tables as well ? (like a Foreign Key)..if yes, then this isn't really a good idea to rearrange id values.
Comment: Do you need to retain anything other than the colors? If not, export the data as `INSERT` queries and replace `id` with `NULL` and the date as `NOW`.
Comment: From what you wrote, there's no real reason why you want to tamper with synthetic primary key except personal OCD. If you do nothing, everything works. If you tamper with it, stuff dies. How about you do nothing? In 100 cases out of 100, trying to "force" auto_increment to re-use numbers or don't have gaps results in catastrophe. Why don't you add an additional column, call it `number_to_satisfy_my_ocd`, and maintain its value sequentially? You're using the wrong column to play with - `auto_increment` is not for humans to touch.
Comment: The feature is available in the deprecated MyISAM, but not in InnoDB.  See also:  http://mysql.rjweb.org/doc.php/myisam2innodb#index_issue_2_column_pk
Comment: To answer your questions: the ids of the table are not used anywhere else, so dont panic. The reason is for estethics, and for having a chronological table select, in case I miss to add "ORDER BY date" in my PHP selections. I appricate your careness. I used the solution of Koala Yeungs answer by considering the additional infos of my comment.
Answer: The Query
The query that you asked for is:
INSERT INTO `table_name_new` (`color`, `date`)
  SELECT `color`, `date` FROM `table_name` ORDER BY `date`;

Further documentation here describes other variations of similar operation in MySQL.
But as many comments stated, it is not recommended to mess with id after they are defined. Some other part of your code might expect the id to have a certain meaning. Plus it is pretty trivial to re-order your records with ORDER BY clause when needed.
So unless you're sure that id is absolutely trivial / meaningless in your entire code base, you're advised against this kind of operation.
Please consider carefully.
How to prevent manually building column list to just omit 1 column?
Unfortunately, there is no MySQL syntax that directly support selecting table columns by defining which to omit. We may, however, build our own SQL query to run by other MySQL queries.
Assuming,

you have the right permission; and
you are already in the correct database;

then,
--
-- Build a comma separated column list (omitting "`id`," and ",`id`")
-- as session variable "@columns"
--
-- @column would be "`color`,`date`" for the example table in our question.
--
SET @columns = (
  SELECT
    REPLACE(REPLACE(GROUP_CONCAT(CONCAT('`', COLUMN_NAME, '`')), '`id`,', ''), ',`id`', '')
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_NAME = 'table_name' AND TABLE_SCHEMA = (SELECT DATABASE())
);

--
-- Build a SQL query string @sql according to @columns
--
SET @sql = CONCAT(
  'INSERT INTO `table_name_new` (',
  @columns,
  ') SELECT ',
  @columns,
  ' FROM `table_name` ORDER BY date;'
);

--
-- Prepare and execute the SQL statement
--
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

Comment: Is it possible that you confused table_name and table_name_new, since I actually want to Insert into the new one?
Comment: Btw, your solution works perfectly when I switch the table names. I hoped for a general solution where I didn't have to write down all column names, since there are quite a few in the actual original table, but nevermind. Once you corrected your post, I can approve it.
Comment: @DanielM: Added way to build the column list automatically with MySQL.


ARCore – 3d object rendered in front of my face

Question: I have a glass model that's rendered with Augmented Faces API. This works correctly when my face is in front. But when my face in half-profile the model is renderer on my face.

How can I fix this?
Comment: GLES20.glDepthMask(true); works for me, make sure there's no GLES20.glDepthMask(false); anywhere else in your code
Answer: Augmented Faces API can be run with its new companion – Depth API that is a part of ARCore 1.18. Depth API gives ARCore developers Occlusion feature for selfie front camera or for rear camera working with iToF laser sensor. For this you need a device that supports Depth API (look at the last column of the list of ARCore supported devices).
However, due to sensors' and technologies' imperfectness, sometimes artifacts are possible. That's why temples of glasses are composited in front of your face, not behind it. So occlusion is not working properly even Depth API is turned on. At the moment you can't ged rid of these nasty artifacts.
Comment: thanks , sorry my reputation less for reputation and can not click (this answer is useful).. if possible more explain or send document for depth api selfi camera
Comment: https://developers.google.com/ar/develop/java/depth/overview
Answer: it looks like occlusion Material bug in sceneform deprecated sdk
(with filament render inside). https://github.com/google/filament/issues/1994
Comment: Please read [answer]. Currently your answer contains a brief attempt to answer, and a much longer question. You should [edit] your answer to remove the question, then ask it as your own question.


Why cast to Closeable first?

Question: While reading some Java source, I came across this line:
((Closeable) some_obj).close();

some_obj is obviously an instance of a class which implements the Closeable interface. My question is, why do they first cast some_obj to Closeable before invoking close().
Couldn't I just do
some_obj.close();

Answer: Assuming the compile-time type of some_obj implements Closeable, then yes, you could.
You'd only need this if you had an object which you knew implemented Closeable, but where the compile-time type was something more general (the most obvious example being Object) or otherwise "different" (e.g. a different interface).
Just as a matter of interest, in C# a cast to an interface type can make a difference, even if the compile-time type is known to implement the interface, due to explicit interface implementation. I can give more details if anyone cares, but I just thought I'd throw it out there.
Comment: technically, it might not be something "more general", just something "different" (a sibling type to Closeable).
Comment: technically, technically, it might not be related to Closeable at all (in the non-cast version) ;-)
Answer: If the known compile-time type of the variable some_obj contains the method close(), then yes.
Answer: It sounds like typecast is unnecessary.  (You could confirm this by trying to compile the class with the supposedly redundant typecast removed.)
We may never know why the code was written that way.  It might be left over from a previous incarnation of the code where the declared type of some_obj was different.  It might be that the developer had some stylistic issues ...
While it would (probably) the code's improve readability if the redundant cast was removed, it is not actually doing any harm.  I expect that the Java compiler or the JIT compiler will optimize it away.  And even if it doesn't, the cost of a redundant typecast is most likely insignificant.

Why cast to Closeable first?


Describe the identification space $\mathbb{R}^2 / \sim $

Question: Define a relation $\sim$ on $\mathbb{R}^2$ by $(x_1,y_1) \sim (x_2,y_2)$ provided $x_1+y_1^2=x_2+y_2^2$, and I have to describe the identification space $\mathbb{R}^2 / \sim $. \
I take a open set in $\mathbb{R}^2 / \sim $, then $p^{-1} (U)$ is open in $\mathbb{R}^2$, where $$p: \mathbb{R}^2 \to \mathbb{R}^2 / \sim $$ defined as $p(x,y)=[(x,y)]$. But I don't know how to do. Can anybody give me an Idea please
Answer: HINT: I'm assuming that you meant to define $\langle x_1,\color{red}{y_1}\rangle\sim\langle x_2,y_2\rangle$.
Let $\langle a,b\rangle\in\Bbb R^2$. Then $[\langle a,b\rangle]=\left\{\langle x,y\rangle\in\Bbb R^2:x+y^2=a+b^2\right\}$. Now $a+b^2$ could be any real number, so the $\sim$-equivalence classes all have the form
$$\left\{\langle x,y\rangle\in\Bbb R^2:x+y^2=c\right\}$$
for some constant $c$. What does such a set look like? Consider the graph of $x=c-y^2$. You can worry about the topology on $\Bbb R^2/\sim$ after you know what the quotient space is.
Added in response to comment:
For any open interval $(a,b)$ let $U(a,b)=\{[\langle x,y\rangle]:x+y^2\in(a,b)\}$. Then
$$p^{-1}[U(a,b)]=\left\{\langle x,y\rangle\in\Bbb R^2:a<x+y^2<b\right\}\,,$$
and it's not too hard to show that this set, which is the open space between the parabolas $x=a-y^2$ and $x=b-y^2$, is open in $\Bbb R^2$.
Suppose that $\langle x,y\rangle\in p^{-1}[U(a,b)]$, and let $$\epsilon=\min\left\{\left(x+y^2\right)-a,b-\left(x+y^2\right)\right\}\,.$$
Let $\langle u,v\rangle=\langle x+h,y+k\rangle$, and suppose that $|k|<\min\left\{\frac{\epsilon}{6|y|},\sqrt{\frac{\epsilon}3}\right\}$ and $|h|<\frac{\epsilon}3$; then
$$\begin{align*}
\left|u+v^2-\left(x+y^2\right)\right|&=\left|x+h+(y+k)^2-x-y^2\right|\\
&=\left|h+2ky+k^2\right|\\
&\le|h|+2|ky|+k^2\\
&<\frac{\epsilon}3+\frac{2|y|\epsilon}{6|y|}+\left(\sqrt{\frac{\epsilon}3}\right)^2\\
&=\epsilon\,,
\end{align*}$$
so $a<u+v^2<b$, and $\langle u,v\rangle\in p^{-1}[U(a,b)]$. In other words, if we set $\delta=\min\left\{\frac{\epsilon}3,\min\left\{\frac{\epsilon}{6|y|},\sqrt{\frac{\epsilon}3}\right\}\right\}$, then $(x-\delta,x+\delta)\times(y-\delta,y+\delta)$ is an open nbhd of $\langle x,y\rangle$ contained in $p^{-1}[U(a,b)]$, and $p^{-1}[U(a,b)]$ is therefore open in $\Bbb R^2$.
It follows immediately that if $V$ is any open subset of $\Bbb R$, then
$$p^{-1}\left[\left\{[\langle x,y\rangle]\in\Bbb R^2/\!\sim\,:x+y^2\in V\right\}\right]\tag{1}$$
is open in $\Bbb R^2$ and hence that $\left\{[\langle x,y\rangle]\in\Bbb R^2/\!\sim\,:x+y^2\in V\right\}$ is open in $\Bbb R^2/\!\sim$. To finish the job you need to show that if $V$ is not open in $\Bbb R$, then the set in $(1)$ is not open in $\Bbb R^2/\!\sim$; you can use the same sorts of ideas.
Another way to say this is that the function
$$f:\Bbb R^2/\!\sim\;\to\Bbb R:[\langle x,y\rangle]\mapsto x+y^2$$
is continuous. (In fact $f$ is a homeomorphism.)
Comment: @AlejandraBenítez: More to the point, the $\sim$-classes are a pairwise disjoint family of parabolas that cover $\Bbb R^2$. If $U$ is an open set in $\Bbb R^2/\sim$, $p^{-1}[U]$ is going to be a union of some of those parabolas. When is such a union open in $\Bbb R^2$? Look at the constants $c$ for the parabolas: try to show that $p^{-1}[U]$ is open if and only if the set of constants $c$ of the parabolas are an open set in $\Bbb R$.
Comment: Okay I understand
Comment: I know that is a parabola. And know what is the topology on $\mathbb{R}^2 / \sim$?
Comment: I was trying what you told me but I couldn't prove it. Can you help me please?
Comment: @AlejandraBenítez: I've done much of what's needed; see if you can finish it off.


Using a while loop to count instances in a string in java

Question: Problem
How many instances of a certain character are there between the beginning of the string and a break point?
The break point is the first instance of another character.
For example, my string could be

hi, I need help! with this problem!

and I want to use a while loop to count the h s from the beginning to the !, so the output would be 2.
I am extremely new to java so I only know how to use a while loop to count up to a certain number but I don't know how to break or how to ask it to count just a certain character. Any hint in the right direction would be great.
My idea is to do something like:
while(character equals 'h', count)
else(don't count)
break if(character equals !)
print

But I don't know how to translate that to java
Comment: You should do your homework first.  This is straightforward.
Comment: Your idea sounds right. Try it. Read tutorials about while loops, conditionals and variables.
Answer: Here is a quick code snippet:
/**
 * Method Name: countChars
 * Arguments: 4 (Original String, Character to be found, Start Index,
 *               Stop/Terminate Character)
 * Returns: Character Count
**/
public int countChars(String str, char c, int start, char e) {
     char[] chr = str.toCharArray();
     /* Initialize Count Counter */
     int count = 0;

     /* Initialize Counter With Start Index */
     int i = start;
     /* Iterate String For Positive Matches */
     while(i < chr.length) {
          /* Core Logic */
          if(chr[i] == e) {
               /* Terminate Character Found : Break Loop */
               break;
          } else if(chr[i] == c) {
               /* Match Found : Increment The Counter */
               count++;
          }
          /* Increment Loop Counter */
          ++i;
     }

     /* Return Character Count */
     return count;
}

You can call this method as follows:
int count = countChars(myString, 's', 0, '!');

Comment: Code dumps without explanation are not helpful to a beginner. Please explain what you are doing in this code.
Comment: Also, I don't think this quite does what is being asked - it should go to the first instance of "another character", not within a certain range.
Comment: @Andy Thanks for your response. Added Comments & Changed the Terminate Condition.
Comment: Those for loops makes sense to me and I've done some before.  The book I'm working from specifically asks for a while loop though and to use a string variable, any way to do it that way?
Comment: @Nick94107 Changed it to use `while` instead of `for`.
Comment: @user2004685 Thank you!  The comment lines are very helpful and will definitely help me going forward


Are all Stochastic Processes "Automatically" Markov Chains?

Question: I was reading these notes on Stochastic Process over here (http://faculty.washington.edu/yenchic/18A_stat516/Lec3_DTMC_p1.pdf). Over here, the following claim is stated:

The way this claim is written, it seems to suggest that there might be some Discrete Time Stochastic Process that might not be a Markov Chain if the stated condition is not satisfied (i.e. P(Xn = i conditional on Xn-1 = j....) only depends on P(Xn = i conditional on Xn-1 = j....) ). In this case, I believe that this stated condition is sometimes also called the "Markov Property".
However, I tried to think of counterexamples but I could not seem to think of a counterexample of a Discrete Time Stochastic Process that does satisfy the stated condition - suggesting that perhaps every Discrete Time Stochastic Process is "automatically" a Markov Chain.
I am aware that there are some Markov Chains in which the probability of the chain being in some state at a future time does not necessarily only depend on the current state - but rather, might depend on some finite history of states. For instance, a Markov Chain can be classified as a "Second Order Markov Chain" in which the probability of being in some state depends on the previous two states instead of only the previous state (What is an example of a second-order markov chain?).

But in general, can all Discrete Time Stochastic Processes be considered as "some type of Markov Chains" (e.g. if not 1st order, perhaps 2nd order, 3rd order, etc.)?

Is this just a formality, or are there actually some Discrete Time Stochastic Processes that can fundamentally not be considered as Markov Chains?
Thank you!
Answer: Take $X_0$ to be a random (uniformly distributed) irrational number in $(0,1)$, and for $i>0$ let $X_i$ be the $i$th binary digit of $X_0$.
Comment: Thank you for your answer! I think you changed your answer - I liked the previous one better... is it possible to see the older one? Thank you so much!
Comment: The previous one was incorrect.
Comment: The point is that you need to carry "new random information" arbitrarily far forward.  The old answer carried random information forward from X_0 to X_i but it was not new, it could be deduced from X_{i-1}.  In this one the new information is really new.
Answer: You could have a process that looks at the history arbitrarily far back. For example, you could have a coin that respects the gambler's fallacy: after a streak of $n$ times coming down one side, it has a $\frac1{n+1}$ probability of landing on that side again, and a $\frac{n}{n+1}$ probability of landing on the other side.
Then no $k^{\text{th}}$ order Markov chain can properly describe it. For any $k$, we can consider two situations: a streak of length $k$, and a streak of length $k+1$. These give different probabilities ($\frac1{k+1}$ and $\frac1{k+2}$) that the streak continues, but the $k^{\text{th}}$ order Markov chain can only treat them the same.
Comment: Thanks Misha! Can you please explain why there is no "k-th" order Markov Chain that can properly describe this situation? Thank you so much!
Comment: I've elaborated on the answer; does it help?
Comment: Thanks Misha! I think now I get it! Just one question: In the case of the Brownian Motion - can we say that the Brownian Motion is a Stochastic Process and is modelled using a Markov Chain?
Comment: Brownian motion is a continuous-time and continuous-space stochastic process, which changes the rules significantly, and I'm not super comfortable with the new rules. I am told that it's generally non-Markovian.
Comment: @ Misha: Hi Misha! I am trying to teach myself about Continuous Markov Chains - can you please take a look at this question if you arent too busy? https://math.stackexchange.com/questions/4458150/properties-of-continuous-time-markov-chains Thank you so much!


df2gspread Type Error when uploading DF to Google sheets

Question: I'm getting the following error when trying to use d2g.upload() to save a DF back to a Google sheet:
TypeError: '<' not supported between instances of 'str' and 'int'
It is saving the index and the DF column names to the Google sheet, but not actually populating the data into the sheet.
No idea what's causing it, has anyone else encountered this same problem? Below is the code I'm using to save the DF back to Google sheets. I've used the same code for several other DF's and it works, I just don't know what's unique and this specific DF that's causing the issue. The Dtypes are all object / float. Any help would be greatly apprecaited!
<code>from df2gspread import df2gspread as d2g
wks_name = 'Linkedin_Campaign_Ad_Daily_Clean'

d2g.upload(li_ad_link_clicks, spreadsheet_key, wks_name, credentials=credentials, row_names=True)
</code>
Answer: I fixed this by deleting duplicate columns in my dataframe:
df = df.loc[:,~df.columns.duplicated()]


C++: Determining whether a variable contains no data

Question: I've been messing around in C++ a little bit but I'm still pretty new. I searched around a little bit and even using the keywords of exactly the problem I am trying to tackle yields no results. Basically I am just trying to figure out how to tell if a variable has no data. I have a file that my program reads and it searches for a specific character within that file and basically uses delimiters to determine where to store the actual data in a variable. Now I added some comments in the file saying that it should not be edited which has caused me some problems. So I pretty much want to count the number of comments, but I'm not sure how to do it because the way I had it set up was resulting in huge numbers being returned. So I figured I would attempt to fix it with a simple if statement to see if there was any data in the array while it was running the loop, and if there was then simply add +1 to my variable. Needless to say it did not work. Here's the code. And if you know a better way of doing this, by all means please do share.
size_t arySearchData[20];
size_t commentLines[20];
size_t foundDelimiter;
size_t foundComment;
int commentsNum;

foundDelimiter = lineText.find("]");
foundComment = lineText.find("#");

if (foundComment != std::string::npos) {
    commentLines[20] = int(foundComment);

    if (foundComment = <PROBLEM>){
        commentsNum++;
    }
}

So it successfully gets the two comments in my file and recognizes that they are located at the first index(0) in each line but when I tried to have it just do commentsNum++ in my first if statement it just comes up with tons of random numbers, and I am not sure why. So as I said my problem is within the second if statement, I need a void or just a better way to solve this. Any help would be greatly appreciated.
And yes I do realize I could just determine if there 'was' data in the there rather than being void or null but then it would have to be specific and if the comment (#) had a space before it, then it would render my method of reading the file useless as the index will have changed.
Comment: I changed the tag to regular C++ as there does not seem to be anything CLI specific here.
Comment: All in all, your question is very unclear. I have no idea what you are actually trying to do and how your code is related to that. Could you clarify that?
Comment: @Space_C0wb0y: and the code is buggy too, out of bounds access + assignment in `if` make me cringe. It also looks very C-ish.
Answer: A variable in C++ always contains data, just it may not be initialised.
int i;

It will have some value, what it is can't be determined until you do something like
i = 1337;

until you do that the value of i will be what ever happened to be in the memory location that i has been assigned to.
The compile may pick up on the fact that you are trying to use a variable which you have not actually given a value your self, but this will normally just be a warning, as their is nothing wrong as such with doing so
Comment: "the value of i will be what ever happened to be in the memory location" -> No, reading from an uninitialized local variable actually yields undefined behavior.
Comment: really? I have once or twice read an uninitialised variable like this, and just ended up with a more or less random value being used. My program did not crash, but I just ended up with 'strange' results...
Comment: Undefined behavior includes any effects that you might consider reasonable.
Answer: You do not initialize commentsNum. Try this:
int commentsNum = 0;

Answer: In C++  other than static variables, other variables are assigned undetermined values. This is primarily done to adhere to underlying philosophy -- "you don't pay for things you don't use", so it doesn't zero that memory by default." However, for static variables, memory is allocated at link time. Unlike runtime initialization, which would need to happen in local variables, link time allocation and initialization incur low cost.
I would recommend hence setting  int commentsNum = 0;


construct a string with the index the composition of an integer array

Question: i've code for indexes string. What should I add to the code so that the results of the string become.

if string "hello" to "loleh"

this the code :
public void IndexesString()
{
    string karakter = "hello";
    int [] IP = {4,5,3,2,1};
    string Result;
    txtResult.Text = Result; // Result = "loleh"
}

Comment: @MaxMommersteeg the indices are given in the `IP` array with a +1 offset.
Comment: Are you always expecting "hello" to turn into "loleh", or does it need to be random or?
Comment: How did you come from the string "hello" to "loleh" given those indices? If you can describe the steps you took you can probably code it too.
Comment: @Max I just illustrate, if a string is compiled using an existing index on the variable `IP`
Comment: @Dirk Yes, I get what I mean, look at the first answer.
Answer: You can use foreach loop and StringBuilder (especially for long strings)
var stringBuilder = new StringBuilder();

foreach(var i in IP)
{
    stringBuilder.Append(karakter[i-1]);
}

Result = stringBuilder.ToString();

Comment: `ToString()` call is superfluous here.
Comment: @Dennis yeah, thanks :) I've copied it from previous version where I was using `+=` at string
Answer: string str = "hello";

string result = new string(new[] { str[3], str[4], str[2], str[1], str[0], });

More generally, substitute the indices 3, 4 etc. with ip[n] or similar. Can be done in loop of course.
Or what about this:
string str = "hello";

int[] ip = { 3, 4, 2, 1, 0, };

var result = new string(Array.ConvertAll(ip, idx => str[idx]));

The old ConvertAll method of .NET 2 is similar to Linq's Select method, but with arrays.
Answer: Possible Linq solution
  string karakter = "hello";
  int[] IP = { 4, 5, 3, 2, 1 };

  String result = new String(IP.Select(i => karakter[i - 1]).ToArray());

Comment: This is the same as the last part of my answer, however with `Array.ConvertAll` it is known from the outset that we will need a list/array of a specific length, while Linq's `ToArray` cannot know that. However, if one prefers to always stick to the Linq methods (for clarity of the code), your code is really fine.


jQuery Mobile selectmenu focus and blur event won't fire

Question: I am trying to hide a footer when a  form element is given focus.  I also want to show a footer when a  form element loses focus, which the blur event should handle.  I can't get the focus or blur event to fire on a jQuery Mobile selectmenu  form element.
Here is an example of one of my  form elements -
<select id="radiology-study-provider" class="selectList"></select>

Here is the jQuery code that is supposed to hide my footer on focus and show it on blur (it is inside DOM ready) -
  $('.selectList').change(function(){
      console.log("the change event is firing");
  });
  $('.selectList').focus(function(){
      $('div:jqmData(role="footer")').hide(); // hide the footer
  });
  $('.selectList').blur(function(){
      $('div:jqmData(role="footer")').show(); // show the footer
  });

It is strange that the change event handler fires but focus and blur will not.
I have tried this below and it won't work -
  $('.selectList').on('focus', function(){
      $('div:jqmData(role="footer")').hide(); // hide the footer
  });
  $('.selectList').on('blur', function(){
      $('div:jqmData(role="footer")').show(); // show the footer
  });

I also tried this -
   $('.selectList').bind( "focus", function(event, ui) {
       $('div:jqmData(role="footer")').hide(); // hide the footer
  });
   $('.selectList').bind( "blur", function(event, ui) {
       $('div:jqmData(role="footer")').hide(); // hide the footer
  });

I also tried the focusin() and focusout() events with no luck either.  I tried dozens of selectors (div.ui-select was one of them).  I don't think it is an issue with the selector I am using.
I am using jQuery Mobile 1.1.0 and jQuery 1.7.1 - I have checked the jQuery Mobile selectmenu documentation at http://jquerymobile.com/test/docs/forms/selects/events.html, talked to the google, searched here, and can't find this issue out.
Comment: Hey mate, does your change method `$('.selectList').change` work at least?
Answer: This is what ended up working for me.
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady () {
    document.addEventListener("hidekeyboard", onKeyboardHide, false);
    document.addEventListener("showkeyboard", onKeyboardShow, false);

}

function onKeyboardHide() {
    $('div:jqmData(role="footer")').show(); // show the footer
}

function onKeyboardShow() {
    $('div:jqmData(role="footer")').hide(); // hide the footer
}

I came across this here on stack - Show hide keyboard is not working propery in android phonegap and noticed there are those 2 events you can listen for.
Answer: Try commenting out the focus event and try.. Sometimes when the focus event fires it is fired multiple times because of which you don't see the code that is executed...
$('.selectList').change(function(){
      alert("the change event is firing");
  });

 // $('.selectList').focus(function(){
 //    $('div:jqmData(role="footer")').hide(); // hide the footer
 //    alert("Focus event is firing");
 // });

  $('.selectList').blur(function(){
      //$('div:jqmData(role="footer")').show(); // show the footer
      alert("Blur event is firing");
  });

I commented out the focus event and the other two events seem to fire..
Remove the comments and you see the focus event getting fired multiple times..
Check FIDDLE
Comment: Thank you for your suggestion.  Unfortunately the blur event won't fire.  I need to somehow know when the android keyboard is present and this is possible by the focus and blur event handlers on form elements.
Answer: This worked for me using the following example:
JS:

where #my_footer is the id of my footer (check the HTML below).
HTML:

            <select id="radiology-study-provider" class="selectList">
                <option value="1">A</option>
                <option value="2">B</option>
                <option value="3">C</option>
            </select>

You may have a try at this example and see if this works for you mate :S
Hope this helps. Let me know about your results.
Comment: Thank you so much for your help.  Once again though, only the change event wanted to fire.  I figured out a solution though, I'm going to post what worked for me.
Comment: Your welcome mate :). I'm curious to see what was the problem :S... I'll be waiting for your solution :P
Comment: I gotta wait 5 more hours to self-answer because I have less than 10 reputation.  I'll post it up here tomorrow.  Thank you again.


The G/M/1 Queue

Question: Please help me with the following. For a long time I am trying to understand the part of the example:

The part I don't understand I marked by the red line. It has no sense to me, why the sum is for $k\geq i$. To be more specific. Take for example $X_n=1$ for some $n$ and ask about $P(Y_n=1|X_n=1)$. In this particular case at most $1$ customer can be served, so why the sum take into account all posibilities $k\geq 1$?
Answer: I think the idea is that the Poisson departure process do not directly correspond to the actual customer departure process, because the latter depends on the arrival process. You can think of it as letting a Poisson process run in the background, and whenever there is at least one customer in the queue, the next Poisson departure actually causes an actual customer departure.
Going back to your question, let there be $i$ customers, but assume the arrival process is much slower on average than the service process. Then the next customer will take a long time to arrive, during which there might be an arbitrarily large number of Poisson "departures" (I put this in quotes because there is no actual departure). The summation from $i$ to $\infty$ counts all these events. Note that the actual customer departures are denoted by $Y_{n}$, that is why the probability is zero when $j>i$.
Answer: Misunderstanding is due to the errors in the source you are using.

If $X_n$ is the number of customers in the system after the $n$-th customer arrives, including the $n$-th customer, then the recursion (5) is wrong.
Recursion (5) is true only if $X_n$ is the number of customers in the system after the $n$-th customer arrives, excluding the $n$-th customer.
The expression for $P(Y_n=j|X_n=i,...)=...$ is wrong. For the correct expression and the proper explanation you may have a look at section 6.4 of P.P. Bocharov, C. D'Apice, A.V. Pechinkin and S. Salerno: Queueing Theory, Modern Probability and Statistics, VSP, The Netherlands, 2004.

The G/M/1 Queue


How to transfer credentials to Glass from Web

Question: Since the "preview" of the GDK is out, I was wondering how we could transfer the credentials of OAuth (say from Twitter) from an AppEngine project (or anything else, open to suggestions) to the APK on Glass. I haven't seen anything on this, and since authentication on Glass would be very hard, how would we do this? I know that I could create a database, but I'm not sure how to make a lightweight version of that. Any other ideas besides a database would be welcome. Thank you for your help.
Answer: The easiest way is to have user login on a website, then save OAuth token into a QR code and let the user scan the QR code with Glass.
I have used it in my app Glasquare (Foursquare for Glass), it's all open-sourced:
https://github.com/destil/glasquare
EDIT: There is official way now: https://developers.google.com/glass/develop/gdk/authentication
Answer: Maybe you could login from the smartphone version of your app, and transfer those credentials to your glass generating a QR code and reading that QR first time you enter to your Glass app
Answer: The video that was published implied there was a authentication step during install but he also said that 'it was still beign worked out'
The bike app (Streva? May have the spelling wrong) does request some kind of authentication
I should add I'm pretty interested in how to deal with oauth in glass also


How to sort object by key date?

Question: I have the following object:
   var obj = {
  "2019-01-28 00:00:00.000": [],
  "2019-01-29 00:00:00.000": [],
  "2019-01-30 00:00:00.000": [],
  "2019-02-02 00:00:00.000": []
}

How sort this object by key/date?
I tried iterate all element and convert to new Date(element) then compare with prev value.
Comment: Order of keys in objects is not guaranteed in JavaScript [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795)
Comment: Did you try [this](https://stackoverflow.com/a/17685499/9368703)?
Comment: This works when you know name of property, my case is different
Comment: You would have to split this object into a sorted array of objects for it to work properly.
Comment: [This](https://stackoverflow.com/a/14528472/9368703) will work then
Comment: You don't need to convert into Date instances here, these values are sortable using simple string comparison already.
Comment: @adiga actually, it's been a while the order is guaranteed: http://2ality.com/2015/10/property-traversal-order-es6.html#traversing-the-own-keys-of-an-object and you can rely on that (but I would strongly suggest to use `Map` if the order is mandatory).
Comment: @adiga as said, better use `Map` IMVHO, however, the order is predictable and the OP doesn't actually deal with "numerical keys" – they're string, and "a String property name `P` is an array index if and only if `ToString(ToUint32(P))` is equal to `P` and `ToUint32(P)` is not equal to `2^32-1`", and definitely this is not the case of the OP.
Comment: @ZER0 In that case [the mdn documents](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Deleted_added_or_modified_properties) need to be updated.
Comment: @HMR definitely! Although the `for…in` and `Reflect.enumerate` is different from `Object.keys`, `Object.getOwnPropertyNames` and `Reflect.ownKeys`; the order is still defined.
Comment: @ZER0 yes, I should've read [this section](http://2ality.com/2015/10/property-traversal-order-es6.html#integer-indices) more carefully.
Answer: Order of keys is not fixed in javascript. You could extract the keys, sort the keys and then run a function for each key
var objKeys = Object.keys(obj);
objKeys.sort();
objKeys.forEach( (value) => {
    // do something with obj[value]
});

Answer: You can use this:
var keys= Object.keys(obj).sort(function(a,b){
    // Probably you cast the Date applying a new Date()
    // Also you can use > to order DESC
    // You can create a function to order ASC or DESC
    return a<b;
});

// Now you could iterate your object ordered
keys.foreach(function(k) {
    // This your fist element ordered obj[k]
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

How to sort object by key date?


How many people must be present at a party to guarantee that at least three of their birthdays are in the same month?

Question: I keep getting 36 as an answer since if 36 people were present at a party, 36/12 (for the months in a given year) = 3. But this is incorrect. Any help would be appreciated.
Comment: The "worst case" would be two born in each month, hence $24$.  One more than that guarantees that some month (at least) must have (at least)  three birthdays.
Answer: This can be done using the Pigeonhole principle which says that if you have $m$ cages and you want to put $n>m$ pigeons in  those cages, then at least one of the cages must contain more than one pigeon. Let me give you an example. If you have $3$ cages, then at least how many pigeons should you have such that if you put them in those $3$ cages then at least $2$ pigeons must be in the same cage$?$ it can be easily answered, and the answer is $4$. Because if you try to put exactly one pigeon in those cages then after putting three pigeons in three cages one pigeon is left, and you have to put that in one of the cages which already contain one pigeon.
Similar is the case here. You have $12$ months, so if there are $24$ people in the party then it is possible that every two them has birthday in the same month. But if you take $25$ people then by Pigeonhole principle birthday of $3$ of them must be in the same month.
Answer: If you had $24$ people you could have every month with two people having their birthdays then
But if you had $25$ then at least one month must have at least three people having their birthdays then, since the average number of birthdays per month would be $\frac{25}{12}>2$


Attempt to invoke virtual method 'void android.widget.ListView.clearTextFilter()' on a null object reference

Question: Now im making searchview in my listview
and here is my code
package intikom.streammobile.Customer;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.util.ArrayList;
import java.util.List;

import intikom.streammobile.Index;
import intikom.streammobile.R;
import intikom.streammobile.Utility.BigProccess;
import intikom.streammobile.Utility.RESTClient;
import intikom.streammobile.Workflow.MyRequest.ListRequestItem;
import intikom.streammobile.Workflow.WorkflowActivity;

public class ListCustomer extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private static final String ARG_SECTION_NUMBER = "section_number";
    private static String URLService;
    private static String rowsPerPage;
    private static ListView lv;
    private static SharedPreferences pref;
    private List<ListCustomerItem> mItems;
    private List<ListCustomerItem> mItems2;
    private ListCustomerItem item;
    private static String customerID;

    public ListCustomer() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_customer);

        URLService = getString(R.string.URLService);
        final ListView lv = (ListView)findViewById(R.id.lvCustomerList);
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                item = new ListCustomerItem();
                item = mItems.get(position);
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();
                editor.putString("CustomerID", item.CustID);
                editor.putString("CustomerName", item.CustName);
                editor.commit();

                Intent i = new Intent(getApplicationContext(),WorkflowActivity.class);
                i.putExtra("CustomerName", item.CustName);
                setResult(1000, i);
                finish();

            }
        });

        getCustomer();
        getLocal();
        if (mItems==null)
        {
            if(mItems2==null) {
                Toast.makeText(this, "Internet connection appears to be offline",
                        Toast.LENGTH_LONG).show();
            }
            else
            {
                lv.setAdapter(new ListCustomerAdapter(this, mItems2));

            }
        }
        else
        {
            lv.setAdapter(new ListCustomerAdapter(this, mItems));

        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.searchbox, menu);

        SearchManager searchManager =
                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText))
        {
            lv.clearTextFilter();
        }
        else
        {
            lv.setFilterText(newText.toString());
        }

        return true;
    }
}

and this is the XMl Layout menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="collapseActionView|always"
        android:title="Search"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

and in logcat says :

Attempt to invoke virtual method 'void
  android.widget.ListView.clearTextFilter()' on a null object reference

Can you tell me where i am wrong?
Answer: change this line:
 final ListView lv = (ListView)findViewById(R.id.lvCustomerList);

with this:
 lv = (ListView)findViewById(R.id.lvCustomerList);

you already declaring your listview instance as global and again you are defining it as a local variable that is why your global instance in null always.


Specify prefix for Django auth tables

Question: Can I specify a prefix for auth_*   tables of Django Auth. I want to add django_ to all django tables
Answer: Not sure if it's a good and right thing to do, since specifying/setting table prefixes was proposed and rejected several times:

https://code.djangoproject.com/ticket/388
https://code.djangoproject.com/ticket/891
https://code.djangoproject.com/ticket/5000
https://code.djangoproject.com/ticket/13176
https://code.djangoproject.com/ticket/15238

Though there are some third-party apps that uses class_prepared signal in order to change table names while models are defined and registered, take a look:

https://github.com/benslavin/django-db-prefix
https://github.com/pydevua/django-table-prefix

Hope that helps.

Specify prefix for Django auth tables