php redirect and google analytics

Question: Hi I see there are some topics on this but can't really relate them to my question.
I have a domaina.com that I use for an email campaign.
This domain only has one page (index.php) and it redirects to my real website that is domainb.com
When I go into analytics I want to be able to see under referals that they came from domaina.com
There are so many ways of redirecting and I cant really figure out the right way to do it to make sure its looked at as a refereal by google analytics so I can use the data to analyse the outcome.
Can anyone give me a hint on how to do this?
Thanks
Comment: So what ways have you tried and what was wrong with each of your attempts?
Answer: if you're using PHP header to redirect to domainb.com then you can tell it to redirect to a certain page which is solely for recording Google Analytics, this page loads, and using a meta refresh or a javascript you can tell it to immediately forward on to the index.php page of DomainB.com.
For example:
     domainA.com/index.php:
---> redirects to domainB.com/redirect.php
---> loads the google analytics and a very bare minimum of HTML code including a meta or javascript redirect which then:
---> redirects todomainB.com/index.php
---> displays standard website.

This will then be tracked by Analytics on page visits, each visit to the redirect.php page can be judged as a visit FROM domainA.com
Comment: Hi I tried that. No luck
On domaina i added a php forward to rederect.php on domainb.
Then on domainb i edited redirect.php and added the following code to it:

however when i check analytics for today under pages. I search redirect.php and there are no hits. Do i do this correct?
Comment: @morten44, by default GA will show the referring domain (so you would look for domaina.com, not redirect.php). If you want to see the referring filename you need to select either "referral path" or "full referrer" as second dimension (this is true no mater if you use Martin's or my solution).
Comment: I was meaning you goto `GA --> (domainB) --> Behaviour --> Sitecontent --> landing Pages` and in this find `redirect.php` from which you can count the number of visitors to redirect.php. @morten44
Answer: I frankly do not think it's possible to set a referrer with a PHP redirect (AFAIK the referrer header is set by the browser, not by PHP).
However you can use campaign parameters and set the medium to "referrer", the source to domaina.com and campaign to "(not set)". So you would set your redirect url to:
http://www.domainb.com/?utm_source=http%3A%2F%2Fwww.domaina.com&utm_medium=referral&utm_campaign=(not%20set)

After GA evaluated the campaign paramters this should produce the result you want.
Comment: Hi. Does this require any other setup of campaign etc in Analytics?
The referal patch you give, I should be able to make php referal page on domaina.com using the URL you have posted. Is that correct?
Comment: Yes - as long as the campaign parameters are registered by the code on domainb.com this requires no further setup.

php redirect and google analytics


simple-image-reducer does not start / ImportError: No module named Image

Question: Problem:
~$ simple-image-reducer

Traceback (most recent call last):

  File "/usr/bin/simple-image-reducer", line 28, in <module>
    import Image

ImportError: No module named Image

Reason:
Image != image
Comment: What is your Ubuntu version?
Answer: It is a bug 1825832.
Please login to launchpad and click "This bug affects you and 1 other person" to confirm that this bug affects you.
The solution from proposed patch is simple - use PIL instead of Image.
We can apply the patch programmatically without installing other stuff:
sudo sed -i "s/^import Image/from PIL import Image/" /usr/bin/simple-image-reducer

Answer: 1) make sure it is available
python -m pip install  Image

2) where is it available?
sudo find ~ -name image -type d

-->> directory /home/MyHomeDir/.local/lib/python2.7/site-packages/image
->> OK
3)  Tell simple-image-reducer via link:
ln -s ~/.local/lib/python2.7/site-packages/image ~/.local/lib/python2.7/site-packages/Image

4)
invoke simple-image-reducer  again.
Works:-)
Rem: Ubuntu 19.10, 19.04
Comment: the solution from n0rbert https://askubuntu.com/users/66509/n0rbert is more generic and applies to all users. As long as it works it may be preferrable. As long as there is no new installation of old simple-image-reducer code making it void. However, the issue seems to be related to the upper / lower case writing of "Image" vs "image". This might happen again (simple-image-reducer is not maintained while python is progressing).


Html attributes: quoted or unquoted?

Question: For some html attributes, I can use quotes around the values, or not:
For example, I can do

Or

Is there any difference between these two ways? Which is the more conventional way of doing things?
Comment: And although this is a good question, it may be considered to be off-topic because it can lead to a subjective discussion, which is not something that SO is focused on.  Cheers.
Comment: Related: [Do you quote HTML5 attributes?](http://stackoverflow.com/q/6495310)
Comment: Related: [HTML properties without quotation marks?](http://stackoverflow.com/questions/9837063/html-properties-without-quotation-marks)
Comment: To play nice with your fellow programmers and reduce errors, always use some form of quotes to delineate the values you are setting for your attributes.
Comment: Thank you, the above links are very informative.
Answer: Wrap your values in quotes (single or double, just don't mix them):

It's necessary for many values ( class="container modal warning" )
It prevents confusing values with later attributes ( class="foo"id="bar" )
People will like you, and treat you kindly.

During Tokenization, all three are considered (single, double, and none).

Html attributes: quoted or unquoted?


How to vertically scale google cloud instance without stopping running app

Question: I have a Node.js app that provides a service which cannot be interrupted.
However the load to the app varies overtime and to save cost I would like the vm instance machine type to autoscale in function of the load (ie when over 80% CPU utilisation, scale up from 1 vCPU(3.75 GB memory, n1-standard-1) to 2vCPU(7.5 GB memory, n1-standard-2))
Is this possible?
PS: I have looked at using the container engine and kubernetes but due to how the app operates, the app cannot be replicated to multiple pods and continue working
Comment: You can instantiate the new vm and run the app on that (without killing the old vm), then route all traffic to the new vm, and then finally kill the old vm. Since you say "app cannot be replicated to multiple pods", not sure if this setup is possible for you. Is it?
Comment: This setup isn't really possible for me but I will probably have to change my app to work like this. Thanks for the help @NikhilJindal
Answer: You can only change the machine type of a stopped instance and an instance is considered stopped only when the instance is in the TERMINATED state. It is not possible to change the machine type of a running instance.
https://cloud.google.com/compute/docs/instances/changing-machine-type-of-stopped-instance


Mobile First Platform Failed to create an ILMT record

Question: My current MFP 7.1 setup is using relational database for WL and WLADMIN database.  This a brand new setup, clean DB, clean server (linux), etc...
When I start my MFP server up, I am getting the following:

Jul 28, 2016 2:28:32 PM com.worklight.core.ilmt.WorklightILMTLogger
  dumpLicense INFO: FWLSE0277I: Creating an ILMT record in the file
  '/app/user/catalina_base/logs/16e25eeec7bed9508cb5168efcaeaa4c.slmtag'.
  Jul 28, 2016 2:28:32 PM com.worklight.core.ilmt.WorklightILMTLogger
  dumpLicense SEVERE: FWLSE0367E: Missing License Report data. Failed to
  create an ILMT record.

Does anyone from Mobile First Platform support know how to resolve this?
Answer: The error is due to a problem in writing this ILMT file, but it doesn't affect any behavior other than ILMT.
If you don't need the ILMT, you can ignore it.


How should I configure my Rock Band 3 pro drum kit for the most authentic experience?

Question: I purchased the Rock Band 3 pro drums (the ones that come with the cymbal attachments). I'm wondering what cymbal to color configuration I should use for a drumming experience most comparable to an actual drumkit.
The instruction booklet said one option was to set up yellow->blue->green from left to right (when sitting in front of the kit), however, I have also seen photos on the internet with a setup of blue->yellow->green. There's even someone who's used a setup of yellow->green->blue in this question.
For what it's worth, I am right-handed and I also have an additional bass pedal from my RB1 kit. My only drumming experience is through Rock Band, so I have no "real world" preferences I need to cater to.
Answer: I actually asked this on music.stackexchange and what I learned is that this is the most standard and typical rock drum layout:

You can of course have more drums and cymbals, absurdly more, but that's the layout which most closely approximates a 'typical' or 'normal' rock drum kit. Anything less is a bit barebones, so the above picture is what you should be shooting for in your layout.
Answer: I'm no drummer, but from what I've seen from actual drum kits, the biggest differences to Rock Band drums are the toms' positions, which you can't change. The hi-hat is closer (and to the left) to the snare, as in the question you've linked, so people can play with the hands crossed as you may be used to see, but I'm not sure about using yellow->green->blue: even though it simulates a musical instrument, Rock Band is still a videogame, and the cymbals positions are as important as the colors when playing, so moving the hand from right to left to hit the crash is unintuitive.
I am not sure if moving the yellow cymbal to the left of the snare tom is a good idea. The game was designed as to keep the color/position codes in the same order (red->yellow->blue->green for toms, yellow->blue->green for cymbals, cymbals parallel to the toms), so I think that's how you should play them.


How can I extract a satellite image from google maps given a Lat Long Rectangle?

Question: How can I extract a satellite image from google maps given a Lat Long Rectangle? (or, two (lat,long) points that form a bounding box).
Comment: If one of these answers worked for you, please accept it so this won't show as an open question.
Answer: Your question sounds to me like you want to extract the raw satellite tiles used on Google Maps. That's against the Terms of Use and if you insist in doing I'm pretty sure you'll get blocked out of the service, so... don't ;)
Instead, use the Static Maps API as Mano points out. If you don't want to compute the values from the center and zoom parameters, you can use the visible parameter like this:
http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=640x400&maptype=satellite&visible=29.64,-13.09&visible=27.38,-18.53&markers=color:red%7Ccolor:red%7Clabel:A%7C27.38,-18.53&markers=color:red%7Ccolor:red%7Clabel:B%7C29.64,-13.09
Bear in mind the visible parameter (of which you can provide more than two values) does not guarantee that the corners of the map will be on any of them. They will be visible, which often means the map will include some area around them, in addition to the area among them. Here's is the image:
Answer: How to use Google maps static API to extract a Terrain(Satellite), Road,...etc map?

You need a google account & an API_KEY to use the google maps static API
Login to your google account
After login open another tab and browse the google developer console.
    https://console.developers.google.com
Create or use an existing API key
4.1 Once you are in the console dashboard, navigate to
"Enable APIs and get credentials like keys"
4.2 In the API manager tab, select Credentials
4.3 Once you are in the Credentials menu, select "Add credentials" and select API key in the drop down
4.4 In the next menu select key type as Browser
4.5 Provide a name to your key and click create.
4.6 Copy the key value and use it in all request to google maps API
Go to Google maps static API for google developers documentation.
https://developers.google.com/maps/documentation/static-maps/intro?hl=en
This documentation explains everything you need to know about the maps API
The Google Maps API is a web service that we can call by using a URL shown in the following example. Use the URL with your API_KEY to get the map of New York city

Google Static Map API Service URL
https://maps.googleapis.com/maps/api/staticmap?parameters
Replace the parameters with your prefered location parameters & your API key
https://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=YOUR_API_KEY

To find the parameters like "center" for your preferred location

Go to google maps
https://www.google.lk/maps
Search for your prefered location with name of a city, road or another significant location information. I have searched for my home town main junction "Kurunegala Junction"
Once you have found the location on google maps, copy the browse URL into text file
https://firstname.lastname@example.com,80.3402663,14z/data=!4m2!3m1!1s0x0000000000000000:0x4ef85a8455d1d21c
In the copied URL, copy the Longitude & Latitude into the Google static map API URL as depicted in the below URL(size parameter is required)
https://maps.googleapis.com/maps/api/staticmap?center=7.480785,80.3402663&zoom=12&size=400x400&key=YOUR_API_KEY
Now modify the above URL with other parameters that are required
If you want both terrain and roadmap, set the parameter "maptype" as hybrid
https://maps.googleapis.com/maps/api/staticmap?center=7.480785,80.3402663&zoom=12&size=400x400&maptype=hybrid&key=YOUR_API_KEY
To get a list of available parameters, refer the google map static API documentation.
https://developers.google.com/maps/documentation/static-maps/intro?hl=en
Answer: You can use the Google Static Maps API. You just need one Lat Long pair for the center and set the zoom and size of image. It's one URL that you can place in your web page.
Answer: try with:
URL

https://maps.googleapis.com/maps/api/staticmap?center=17.053828,+-96.700116&zoom=17&scale=1&size=600x300&maptype=satellite&format=png&visual_refresh=true

Result

you can change lat, lng params in your app =).
Add your key API.
https://maps.googleapis.com/maps/api/staticmap?center=17.053828,+-96.700116&zoom=17&scale=1&size=600x300&maptype=satellite&format=png&visual_refresh=true&key=YOUR_KEY_API
Links:

https://developers.google.com/maps/documentation/static-maps/
https://staticmapmaker.com/google/


$1000!$ is divisible by $4^a$, Find the highest value of $a$

Question: As the question goes ,
I tried to solve for $2^{2a}$ first but all I got was a mess. If anyone could kindly solve this for me I would be grateful .
Edit :
Thanks for the replies. I tried the problem on my own and went with this approach,
$1000! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 \cdot \dots \cdot 1000$
I want to solve for $2^{2a}$ first so I consider the even numbers only
Hence,
$$1000!=(2\cdot4\cdot6\cdot8 \dots 1000) \cdot (1 \cdot 3 \cdot 5 \cdot 7 \cdot 9 \cdot \dots 999)$$
Since, odd numbers cannot be factored by $2$, they will be ignored (in the following steps).
$$1000! = 2^{500}(1 \cdot 2 \cdot 3 \cdot \dots \cdot 500) \\ = 2^{500}(2 \cdot 4 \cdot 6 \cdot 8 \cdot 10 \cdot \dots \cdot 500) \\ = 2^{500} \cdot 2^{250} \cdot (1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 \cdot \dots \cdot 250) \\ = 2^{500}2^{250}(2 \cdot 4 \cdot 6 \cdot 8 \cdot 10 \cdot \dots \cdot 250) \\ = 2^{500}2^{250}2^{125}(1 \cdot 2 \cdot 3 \cdot 4 \cdot \dots \cdot 125)$$
I repeat this process and what i get at the end is
$2^{500} \cdot 2^{250} \cdot 2^{125} \cdot 2^{62}
\cdot 2^{31} \cdot 2^{15} \cdot 2^{7} \cdot 2^{3} \cdot 2^{1} = \mathbf{2^{994}}$
Therefore, the answer to the original question would be 497
Is this process correct?
Comment: Welcome to [math.se] SE. Take a [tour]. You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit]): What you understand about the problem, what you've tried so far, *etc.*; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: The question itself is interesting. If the asker would show any effort at all in trying to answer it, I would probably upvote.
Comment: @AdamRubinson It would then still be an abstract duplictate. More annoying is that such questions are still answered.
Comment: For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: Probably not what you meant: $a = \log_4(1000!)$.
Comment: Could you determine the valuation of $1000!$ with respect to the prime $p=2$ ? Then, the rest is easy.
Comment: My first thought: Same problem for $(2n)!$, small values of $n$. You get the sequence
$$
1,~3,~4,~7,~8,~10,~11,~15,~16,~18, \ldots
$$
Comment: @everyone I am sorry that I asked the question in such a vague manner . I am new to this thing so I didnt know how to ask the questions properly . I have now edited the question and added my method of trying to solve the question. If it is correct or if its wrong , let me know kindly .
Comment: @Peter can you provide a link to the duplicated question? If so, I'll vote to close.
Comment: Previous question about $1000!$ and base $4$: [What is the maximum value of $n$ if $4^n$ divides $1000!$ without a remainder?](https://math.stackexchange.com/q/3133488/89922)
Comment: @peterwhy It does. Thank you, could you check my process and see if it has any faults in it ?
Comment: No need to check my process the same process is at that question
Comment: @IftekharAlamBhuiyan I think your approach is good, until you wrote your "answer to the original question": the highest value of $a$ should be $\frac{994}2$, not the $4^{994/2}$ that you wrote.
Comment: Oh I see now , thanks for correcting
Answer: For a number $n$, denote by $v_2(n)$ the highest power of 2 which divides it, such that $v_2(1) = 0$, and $v_2(2^k) = k$ and so on.
Then it is clear that $v_2(1000!) = \sum_{n=1}^{1000}v_2(n)$.
To count the latter, there is a simple trick one can use: write $v_2$ as a sum of indicators. Write $I_k(n) = 1$ if $2^k$ divides $n$ and $0$ otherwise.
Clearly,
$v_2 = \sum_{k=1}^{\infty}I_k$.
Now plug this identity into the previous sum:
$$v_2(1000!) = \sum_{n=1}^{1000}v_2(n) = \sum_{k=1}^{\infty}\sum_{n=1}^{1000}I_k(n).$$
The inner summation is simply $[1000/2^k]$, hence the largest power of $2$ that divides $1000!$ is
$$[1000/2] + [1000/4] + ... + [1000/512]$$
This is something you can do by hand or plug in a calculator. The point is that it gives you a number $b$ which has the property that $2^b | 1000!$ but $2^{b+1}$ does not divide $1000!$.
The maximal $a$ for which $4^a | 1000!$ is then $[b/2]$.
Comment: Iftekhar, if you accept the answer, you should also upvote it.


Notations that are mnemonic outside of English

Question: Some conventional math notations seem arbitrary to English speakers but were mnemonic to non-English speakers who started them. To give a simple example, Z is the symbol for integers because of the German word Zahl(en) 'number(s)'. What are some more examples?
Comment: i'm not sure if this is a relevant example, but this TED talk explains (more or less accurately, apparently) why $x$ prevailed for the unknown in equations http://www.ted.com/talks/terry_moore_why_is_x_the_unknown.html
Comment: a latin scholar will explain better, but the $p$ is from "impetus", a modified "petere"
Comment: @MJD that claim is made in a footnote (typeset humorously in fraktur) in paolo aluffi's algebra book
Comment: Why does $p$ stand for momentum?
Comment: @MJD : https://www.math.duke.edu//education/webfeats/Slope/Slopederiv.html
Comment: @exitingcorpse John Derbyshire in his _[Unknown Quantity](http://www.johnderbyshire.com/Books/Unknown/page.html)_ has a much more plausible explanation for _x_, quoting from Art Johnson's _Classic Math_: Descartes invented the convention of using letter from the beginning of the alphabet to represent _data_ and letters from the end for _quaesita_. The printer asked him if the specific letter-choice mattered. Descartes said no. The printer chose _x_, since French uses the letters _y_ and _z_ heavily so he did not have as many spare punches for them.
Comment: That is a lovely-sounding theory, except that x is much more common in French than either y or z.
Comment: Common in Physics . . .
Comment: I don't know for sure, but I guess the use of the notation $Z(G)$ for the center of the group $G$ is because "center" in German is *Zentrum*.
Comment: Why does $m$ stand for slope?
Comment: Astounding.  Thanks! (It says «I was told by [Mary Dolciani](http://en.wikipedia.org/wiki/Mary_P._Dolciani) herself, that the SMSG group "decided" to use y=mx+b because of the French (Descartes, I presume)-"montant"»)
Answer: In topology the letter $F$ is commonly used to denote a closed set, from French fermé 'closed [set]'. The common use of $K$ to denote a compact set is probably from German kompakt, as in kompakte Menge 'compact set' and kompakter Raum 'compact space'. The common use of $k$ to denote an arbitrary field is probably from German Körper 'field'. The common use of $G$ for an open set is probably from German Gebiet 'region', though as a mathematical term it now means 'non-empty, connected, open set'. The notation $G_\delta$-set for the intersection of countably many open sets combines this $G$ with $\delta$ for German Durchschnitt 'intersection'. Presumably $F_\sigma$-set for the union of countably many closed sets is from the $F$ above and $\sigma$ for French somme 'sum'. The $T$ in the names of the separation axioms $T_1,T_2$, etc. is from German Trennungsaxiom 'separation axiom'.
Comment: @MTurgeon: Very unlikely: one speaks of *eine offene Menge*, not *eine geöffnete Menge*.
Comment: The use of $U$ for open sets probably comes from the German _Umgebung_ "neighbourhood".
Comment: And $G$ as in $G_\delta$ sets is probably from the German "Gebiet" (domain). I've also heard the $\delta$ being short for "Durchsnitt". I've always found it funny that $F_\sigma$ and $G_\delta$ are from French and German respectively.
Comment: @SamiBenRomdhane: I suspect that most English speakers who use $O$ for an open set do so on account of *open* and aren't even aware of *ouvert*. (I prefer not to use $O$ at all, for anything, owing to its resemblance to $0$.)
Comment: And in algebra $K$ is often used to denote a field from the German _körper_ if I'm not mistaken.
Comment: @Stefan: I believe that you're right; I'll add that.
Comment: Could $G$ be for *geöffnet*?
Comment: As you said F comes from the French word *fermé* to denote a closed set  but also O comes from the French word *ouvert* to denote an open set and this is not remarkable since the English word   starts with the same letter.
Answer: Eigen (as in the eigen vectors of a matrix) is Dutch/German for "own".
Comment: + for mentioning Dutch ;)
Answer: $\ln()$ for "logarithmus naturalis"?
My advisor also told me that the "socle of a ring" makes a little more sense when you know that "socle" is an architecture term for the support underneath a column or pedastal, and so the socle of a ring acts as a kind of "support for the ring." In some languages, the word for "pedestal" is something like "socle," so the meaning is less hidden there.
Added
When I put "socle" into google translate, it autodetects it as "plinth" which is a relatively better-known word in English. It turns into "zócalo" in Spanish, sòcol in Catalan, Sockel in German, zoccolo in Italian, cokół in Polish, soco in Romanian, and 虹晶 in Mandarin.
Comment: Not quite true: [*socle*](http://www.merriam-webster.com/dictionary/socle) has that meaning in architecture, but the Latin base is actually *socculus*, a diminutive of *soccus* 'a slipper, a sock'.
Comment: the Dutch "sokkel" means pedestal
Comment: I made changes to pacify those with a deep knowledge of Latin roots. Apparently Latin roots are completely useless for understanding words if you go back far enough.
Comment: @JyrkiLahtonen Yeah it *does* mean that in English, but English speakers hardly ever use it unless they know about architecture.
Comment: I always wondered what socle was supposed to mean!
Comment: I am surprised to hear that. May be because the Finnish word "sokkeli" (obviously with the same root as the Dutch "sokkel" mentioned by ratcher freak) borrowed from a germanic language) meant something like plinth/die/footing/parapet (=the part of a house in contact with the ground). I just assumed that's what socle means in English as well :-)
Answer: A function is often called càdlàg if it is right-continuous and admits left limits. This term is from the french continue à droite, limite à gauche.
Comment: See also càglàd (obvious) and càllàl (*continue à l'une, limite à l'autre*, meaning continuous on one side, limit on the other side, and which side is continuous can depend on the point).
Answer: The Klein $V$-group is  the four-element group with generators $a$ and $b$ and $a^2 = b^2 = (ab)^2 = 1$.  The $V$ is for vierergruppe = "four-group".
Answer: The reason the "Klein bottle" is called a bottle has its origin in something of a German pun on Fläche/Flasche; see here
Comment: To a German speaker, Fläche and Flasche are quite different words. According to your link, it may be that 'Fläche' was mistranslated into English (by an English speaker) as 'bottle', and then back-translated into German as 'Flasche' -- which is undeniably a snappier name for it.
Comment: this is also why when one wants to talk about two surfaces, one uses $S$ and $F$
Comment: Similarly, the Witch of Agnesi takes its English name from a pun in Italian, at least according to Wikipedia.
Comment: These answers should be posted as a separate answers to give them proper visibility.  Not everybody is aware of these facts.
Comment: Well, I thought about it, but it isn't really a piece of notation or a mnemonic as such, more an interesting tidbit (although I don't want to imply disapproval of your choice to post yours as an answer).
Comment: @TonyK, you are right, I should have called it an *English* pun (on a pair of German words).
Answer: Łukasiewicz notation for logic represents $\land \lor \leftrightarrow$ with the letters $K A E$ respectively, so that for example $r\lor(p\land q)$ is $ArKpq$.  $K A E$ are the initials of the Polish words koniunkcja, alternatywa, ekwiwalencja.
I don't know why Łukasiewicz used $C$ to represent material implication.
Comment: $p \implies q$ ------ $p$ czyli $q$
Comment: I had read that when I posted my comment above. I also consulted with Maciej Cegłowski, who though not a linguist is a native Polish speaker, and who agreed with me that it seems unlikely. My own suspicion is that $C$ is short for "conditional".
Comment: Are you sure this is the reason? I am not a Polish speaker, but the examples I have found of *czyli* do not seem very much like material implication.
Comment: It's synonymous with 'therefore' and definitely can be used in this  context. Whether this was his reason for $C$ I can't say, but it certainly is a (perhaps somewhat archaic) way of expressing implication.
Comment: I am a Polish speaker, and it certainly seems reasonable. Here's a link to the relevant Wiktionary article: http://en.wiktionary.org/wiki/czyli
Answer: Gabriel introduced the notation $\text{Sex}(\mathcal A,\mathcal B)$ to denote the category of left exact functors from $\mathcal A$ to $\mathcal B$. This because the Latin word for left (which is sinister) starts with an S.
Comment: Is the category of right exact functors called $\text{Dex}(\mathcal A,\mathcal B)$ from *dexter*?
Answer: In homology one has a sequence of "differentials". Their images are usually denoted $B(X)$, apparently from the german word for "images", and their kernels $Z(X)$ from the german word for "cycles".
Comment: I always thought $B$ stood for "boundary".
Comment: @ZhenLin i think that's more of an ad-hoc thing that we do when working in english, to try to make more sense of it. one could then say we use $Z$ to stand for "zeroes", which is actually kind of pleasant
Answer: The etymology of the $\sin$ function has a colorful history - it comes from sinus, the latin word for... well, bosom.  This was due to a mistranslation from Arabic text in the 12th century:  The word jaib means bosom, and since Arabic is written without short vowels, it was written essentially as jb.  But jb was also the spelling of jiba, which was a transliteration of the Sanskrit word for chord (the mathematical chord, ie a line passing through a circle, half the length of which is the sine of the angle from the center of the cicle).
Comment: According to my Latin dictionary, *sinus* also means "curve". Which might be a simpler explanation than the mistranslation one.
Comment: @detly but much less funny
Comment: All those meanings are present in Spanish: "[seno](http://lema.rae.es/drae/?val=seno) = concavity, bosom, and trig $\sin$"
Comment: And I doubt it's a mistranslation, the relation of meanings ("curved things") is apparent. See also this figure: http://1.bp.blogspot.com/-DniqyzYnS0Y/Tf5Xx7mpoLI/AAAAAAAAANo/DOZbOj3WxMw/s1600/math.jpg
Comment: Interesting, I wasn't aware of this.  I'd be interested to see if there's more reasoning behind scholars believing that this was a mistranslation, but I don't have access to the sources in the wikipedia article: http://en.wikipedia.org/wiki/Sine#Etymology
Comment: It could still be a mistranslation even if they meant sinus = curve.
Answer: The logical-or symbol $\lor$ is a stylized letter 'V', the first letter of the Latin word vel.
(The $\land$ symbol arose later, derived by analogy from $\lor$.)
Comment: I always remember "and" because it looks like an "A". And "or" because it's an upside-down "and".
Answer: QED comes from the latin quod erat demonstrandum
Comment: In french, it's CQFD for "ce qu'il faut démontrer" == "Which had to be demonstrated". Just for your curiosity.
Comment: @Fabinout Being french, I know that, although I'd say "Ce qu'il fallait démontrer". ;)
Answer: The identity element of a group is $e$ for einheit, the German word for "identity".
Comment: I wondered about this just yesterday.
Answer: In old Polish textbooks for secondary school complex numbers were denoted $\bf Z$, as zespolone and integers — $\bf C$, as całkowite.
Comment: Heresy ^^ ${}{}{}$
Answer: The center of a group $G$ is denoted $Z(G)$.  The $Z$ is for "Zentrum", which is the German word for 'center'.
Answer: Most of the good examples have been mentioned already.

$+$ probably comes from Latin et, "and"
$\tau$ is sometimes used for the golden ratio, from Greek tomos, "section" (same root as atom).
$\sinh$ from Latin sinus hyperbolus (and so on)
$\in$ from Latin est.
$M$ for an arbitrary set from German Menge, crowd.
$\mathrm E[x]$ for expectation is from German Erwartung or French éspérance.
$\aleph$ (the cardinality of the countable numbers) is maybe from Hebrew einsof, infinity, or maybe just because it's the first letter of the Hebrew abjad.
$m$ for slope may be from Latin modulus, "quantity", or French monter, "to climb".
$e$ may be from German Einheit, "unity", because $\ln e = 1$.
$c$ for the speed of light from Latin celeritas, "swiftness".

If you want to be pedantic, you could point out that there are a large number of mnemonics from other languages which also happen to work in English. For example

$\mathbb{Q}$, $\mathbb{R}$ from German Quotient, Reel
$\pi$ from Greek perimitron or from Latin peripheriam
$I$ from French intensite de courant
$\%$ comes from Italian per cento, "per hundred"
$x$ is used for variables because it's uncommon in French

You might also count all symbols for the SI prefixes (atto-, yotta-, etc.) except the ones which have become productive in English (micro-, mega-, etc.) But that would be far too pedantic, even for me
Comment: As long as we're here, we might as well include the [actual reason](https://www.ted.com/talks/terry_moore_why_is_x_the_unknown?language=en) that $x$ is used for variables.
Answer: In Polya's enumeration theorem the letter $Z(G)$ which is used for the cycle index of the permutation group $G$ originates with the German word Zyklenzeiger, I think.


Parallel projection is special case of perspective projection

Question: I synchronized with @David k's first and second answer regarding perspective and parallel projection. From the first question I understand that the image on the screen is typically described in horizontal and vertical coordinates, that is 2D points. But from the second question, I understand that images on the screen are realistic if they use perspective projection which has 3D coordinates.
My confusion is that how we show the image on the screen with 2D points by perspective projection?
The point $(x,y,z)$ is projected to position $(x_p,y_p,z_{vp})$ on the view plane. Since the view plane is placed at position $z_{vp}$ along the $z_v$ axis. So when $z_{vp}=0$ projectors (projection vectors) do not converge towards a projection reference point in parallel projection. But in perspective projection, when $z_{vp}=0$, it is reduced to parallel projection, but the projectors converge at the centre of projection. Am I correct above these concepts?
The vanishing point in perspective projection which is 3D coordinates could be represented in the projective plane as $(x, y, z, 0).$ Am I correct?
Answer: Let's try to reign stuff in a bit. In practical applications, we do not deal with infinites. Because that would mean we would need to use some kind of symbolic solver for all of our stuff. We couldn't afford to do this in many practical applications.
Because of these practical considerations, I need to have a near and far plane for my camera rasterizer. If I were to make some kind of vector graphics I most likely wouldn't have infinite objects (or at least deal with this in the scenegraph) and if we would do some sort of tracing we would have a hard time deducing intersections near infinity.
Also because of practical considerations, we do not generally * turn the data into 2D coordinates. What we conceptually do is transform the points so that they seem like something that looks like a perspective projection from a parallel projection in our z-direction. We then use this view to build out the data that we need. During this building process, we are free to discard any data that we don't need. So think of this as a preliminary sorting so that I can really do what I intended easily.
Now usually we have access to both the transformed data and untransformed data so that being terribly concerned about deducing something from the projection, that we can simply read it from the 3D space directly or from our scene graph for that matter, is a priority. But both the z and even the fourth component data could be useful for building my next stage primitives.
Ok so at this point we are done with projecting and now we can start building our output. But this has nothing to do with any of the math you asked so far. The next stages are about triangle barycentric coordinates, shading, intersection finding, depth sorting, etc. The math that you have gone through so far doesn't really help with this step.
* It is hard to generalize somebody might be doing this but I wouldn't because it's a waste of my time.
PS: there's no need to know where vanishing points lie since the projection stage has solved both ends of the line.
Comment: can you tell what is form of vanishing point in projection plane? It is normal $(x, y, z)$ in projection plane?
Comment: @User4567 im not sure it is a valid question. A vanishing point is caused by two coplanar lines. Any picture can have arbitrarily many vanishing points. Knowing what it is is meaningless for rendering. Projecting is a alternative way of constructing 3d from the way art books teach you to do stuff.
Comment: but the such image where vanishing point already exist in iamge, like railway track,, so what could be the form of that points?
Comment: @User4567 Does not matter its just a point like everything else. practical implementations work on practical data. The data you usually have tells how to connect consequtive points. Theres no way to know what form it takes it depends on the implementation details of my rendering engine and how i want to encode my data.
Comment: first of all your answer is very difficult to understand.. And I am struggling to understand vanishing point which is already existing in image and it's form.
Comment: @User4567 vanishing points are abstract concepts they dont actually exist in any real data.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/130940/discussion-between-joojaa-and-user4567).
Comment: So how it world co-ordinate to projection plane and it's form? I seem it projects like normal point projection, $(x, y, z) $to $(x_p, y_p, z_p)$?
Comment: @User4567  it is typically just transformed to that point trough a matrix ultiplication a divide by z.
Comment: what about vanishing point?
Comment: @User4567 please join the chat started above. No wanishin point anywhere in any operation
Comment: you mean vanishing point doesn't exists. Actually when two parallel lines intersects in infinity they are not actually intersects. During projection normal point projection is possible but vanishing point projection not possible because it is theoretical concepts but practically it isn't exists. And during projection thoses points are actually normal point... Am I correct?
Comment: @User4567 Sure, its a asymptotic behaviour. But in practice any point far enough probably qualifies as a vanishing point, because you dont need infinite precision
Comment: one thing tell theoretically those point we said vanishing point during projection they actually projects like normal point?
please reply.. I am waiting for your reply.
Comment: one thing tell , suppose I have the two parallel lines we see intersects at point X at infinity. It's is theoretical concepts. But when we do projection in practically this X can be treated as normal point. No vanishing point exists.am I correct?
Answer: All viewing projections are from 3D to 2D. The parallel projection is just a limit case of perspective.
Writing the equation of a ray from the focal point $(0, 0, -f)$ and intersecting with the viewing plane $z=0$, you have
$$\begin{cases}x'=\dfrac{fx}{f+z}\\y'=\dfrac{fy}{f+z}\end{cases}$$ where the magnification factor $f$ in the numerator compensates the minification with distance.
If you let $f$ tend to infinity, the equations simplify to
$$\begin{cases}x'=x\\y'=y\end{cases}$$
which means that the effect of depth is cancelled and projection is achieved by dropping the $z$ cordinate.

Addendum:
There is a way to replace a perspective projection by a parallel one, using 4D homogeneous coordinates and represent the points as $\left(x,y,z,1+\dfrac zf\right)$, which is equivalent to $\left(\dfrac{fx}{f+z},\dfrac{fy}{f+z},\dfrac{fz}{f+z},1\right)$. By considering the 3D components, you obtain a deformed 3D scene which you can render using a parallel projection, while the depth information is preserved to allow hidden parts removal. Again, when $f$ tends to infinity, the transformation becomes trivial.


SQL WHERE IN taking a long time to process SELECT statement

Question: I would like to refactor the following query as it is taking a while to process:
SELECT `user_product`.* FROM `user_products` AS `user_product`
INNER JOIN `items` ON (`user_product`.`item_id` = `items`.`id`)
INNER JOIN `user_tags` ON (`items`.`id` = `user_tags`.`item_id`)
INNER JOIN `tags` ON (`user_tags`.`tag_id` = `tags`.`id`)
WHERE `tags`.`title` IN ('tag3', 'tag')
GROUP BY `items`.`id`
ORDER BY `items`.`created_at` DESC

When I EXPLAIN I get the following results:
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
| id | select_type | table        | type   | possible_keys | key     | key_len | ref                  | rows  | Extra                           |
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+
| 1  | SIMPLE      | user_tags    | ALL    | NULL          | user_id | 12      | NULL                 | 27802 | Using temporary; Using filesort |
| 1  | SIMPLE      | user_product | ALL    | NULL          | NULL    | NULL    | NULL                 | 22676 | Using where; Using join buffer  |
| 1  | SIMPLE      | items        | eq_ref | PRIMARY       | PRIMARY | 4       | user_product.item_id | 1     | Using where                     |
| 1  | SIMPLE      | tags         | eq_ref | PRIMARY,title | PRIMARY | 4       | user_tags.tag_id     | 1     | Using where                     |
+----+-------------+--------------+--------+---------------+---------+---------+----------------------+-------+---------------------------------+

The query takes 17 seconds with two tags in the WHERE IN and 0.009 with one. What would be the best way to optimise the query?
Comment: Do you have indexes on the columns used in the joins?
Comment: The common indexing on a junction (many-to-many) table is to have 2 compound indexes: both `(item_id, tag_id)` and `(tag_id, item_id)`. But your table name suggets that your design is more complex.
Comment: Have you tried splitting the WHERE IN out into separate WHERE, OR clauses?
Comment: Maybe an EXPLAIN without the WHERE IN part could be useful for comparison
Comment: @ypercube thanks for the nudge - it's much faster with an index on ``user_tags`.`item_id``
Answer: Try adding an index on user_tags.item_id and also user_products.item_id
Comment: Thanks, this is what I needed to do. I was also missing one from ``user_tags`.`tag_id``
Answer: MySQL should handle a set of constants just fine in an in statement.  Have you timed the query for each tag independently?  One of the tags might have a lot of data.
It would probably also help if you had an index on tags.title.
Comment: Just tried querying for each tag and they both come back under 0.2. There is a unique index on `tags.title`.
Comment: I'll be curious what others come up with.  Clearly this is somehow triggering an inferior execution plan.  Are statistics up to date on the table?


Citrix Workspace Chrome extension keyboard layout messed up

Question: I am using Ubuntu 20.04.4 LTS as host and Citrix Workspace Chrome extension (since it is the only installation that I got working with HDX).
Unfortunately, when I start the Windows 10 client I cannot use my keyboard because the key assignment seems random but consistent, meaning it is always the same but I cannot associate it with any country layout.
For example, key z gives y and vice versa, key "-" gives "ö" but key "ö" also gives "ö". "ß" is there twice as well...
Things I've tried:

changing the layout on the client side. This did not work. Although in the taskbar it says "DEU" for German layout, the keyboard is still messed up.
I changed the wfclient.ini (KeyboardLayout = German), but still not working (and I am not sure if this is only relevant for the Citrix Receiver installation)

I am not sure if cthe wfclient.ini file is for the Chrome Workspace App tbh.
Also I cannot find (through google and looking on my machine) a way to configure the Chrome Workspace App. So if anybody knows how to do it: please help!
Any help would be highly appreciated.
Comment: What do you understand by "a scrambled keyboard layout"? Use "edit" and try to be more precise.
Comment: @vanadium I tried to be more specific. Hope it helps.
Answer: I experienced a similar issue using the Citrix WS app on Ubuntu:

My keyboard layout on the host (Ubuntu) is set to a general Hungarian keyboard layout (correctly recognized as the real one)
Same keyboard layout is set on the VM (Windows 10): Hungarian general
When I type in the VM, it does not use the set layout, but some hybrid one (EN/HU mixed, EN where it has matching key with HU layout, HU, where it does not. I have HU letters, but special characters are mixed).
When I use the On-screen keyboard of the VM, that shows the correct layout and works as expected.

The solution for me was that I needed to set the LANGUAGE=hu_HU environment variable (in .bashrc). Now the keyboard layout in Citrix is correct.
NOTE This might change the display language for other applications (e.g., MS Teams).
Another suggestion from the community was to update Chrome display language to the same as the keyboard layout. That might work, but for me, it was not necessary.


How to access webpage from R

Question: I am trying to access a webpage from R without any success -
> readLines('https://www.nseindia.com')
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") : InternetOpenUrl failed: 'The operation timed out'

Below is my session information-
> sessionInfo()
R version 4.0.1 (2020-06-06)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows Server x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] httr_1.4.1

loaded via a namespace (and not attached):
[1] compiler_4.0.1 R6_2.4.1       tools_4.0.1    curl_4.3

I am using R in Windows from Amazon AWS.
However when I use the same code from my local Mac, I have no problem.
Any pointer how to resolve this issue will be highly helpful.
Thanks,
Answer: setInternet2(TRUE)

Or try to run R in administrator mode.
Comment: The setInternet2() function appears to be defunct. Running in Admin mode is not helping either

How to access webpage from R


What does nC0 signify?

Question: I was wondering what "nC0", or taking n objects zero times at once, really means. I could not really find an answer to this elsewhere, except for a place which sort of represented this as the number of sets containing zero elements. Sort of like the empty set which is there always. I could only faintly connect to this idea though; a much clearer explanation would be much appreciated.
Edit: Seems I should have asked this in a better way. As I say in a comment, I am not much into mathematical definitions, I was just thinking of it in a practical way, like if I have "n" things how do I choose from them while taking none of them in any case. What "nC0" would represent in such situations is what drove me to ask this question.
Edit 2: My doubt has been clarified, thanks @5xum :)
Comment: It answers the question "You have a set of $n$ elements. In how many ways can you choose exactly zero elements from it?". The answer is quite clearly 1, because there is only one empty set that you can make.
Comment: @Matti P Thanks for the response, helps clear things a bit. I am not much into mathematical definitions, I was just thinking of it in a practical way, like if I have "n" things how do I choose from them while taking none of them in any case. What "nC0" would represent in such situations is what drove me to ask this question.
Answer: $${n\choose k}$$ denotes the number of $k$-sized subsets of a $n$-sized subset. That is, taking a set $A$ such that $|A|=n$, the number of distinct subsets of $A$ which have $k$ elements is ${n\choose k}$. Since the particular elements of $A$ do not matter, we can therefore say that $${n\choose k} = \left|\{X\subseteq\{1,2,\dots, n\}| |X| = k\}\right|$$
Therefore, ${n\choose 0}$ is the number of subsets of $A$ that have size $0$. There is only one such set, the empty set $\emptyset$, that is, for every $n$, we have
$${n\choose 0} = \left|\{X\subseteq\{1,2,\dots, n\}| |X| = 0\}\right|=|\{\emptyset\}| = 1$$
 therefore, for every $n$, we have $${n\choose 0} = 1$$
Comment: @ShefaliPatra My pleasure. Don't forget to upvote and accept if the answer is what you were looking for!
Comment: @ShefaliPatra Well, there is only one way you can select $0$ things out of a basket of $n$ things - by not picking any of the things.
Comment: Thanks for the response. Actually I have edited the question a bit, could you check it again and help me out? :D
Comment: Had never identified that as a "way" to make a choice, guess that's why I didn't get it. Thanks :)

What does nC0 signify?


How can I send the state (useState) of one file component to another file's component?

Question: REACT.js:
Let say I have a home page with a search bar, and the search bar is a separate component file i'm calling.
The search bar file contains the useState, set to whatever the user selects. How do I pull that state from the search bar and give it to the original home page that
SearchBar is called in?
The SearchBar Code might look something like this..
import React, { useEffect, useState } from 'react'
import {DropdownButton, Dropdown} from 'react-bootstrap';
import axios from 'axios';
const StateSearch = () =>{
    const [states, setStates] = useState([])
    const [ stateChoice, setStateChoice] = useState("")

    useEffect (()=>{
        getStates();
    },[])

    const getStates = async () => {
        let response = await axios.get('/states')
        setStates(response.data)
    }

    const populateDropdown = () => {
         return states.map((s)=>{
            return (
                 <Dropdown.Item as="button" value={s.name}>{s.name}</Dropdown.Item>
             )
         })
    }
    const handleSubmit = (value) => {
        setStateChoice(value);
    }
    return (

            <DropdownButton
             onClick={(e) => handleSubmit(e.target.value)}
             id="state-dropdown-menu"
             title="States"
             >
                {populateDropdown()}
            </DropdownButton>

    )
}

export default StateSearch;

and the home page looks like this
import React, { useContext, useState } from 'react'
import RenderJson from '../components/RenderJson';
import StateSearch from '../components/StateSearch';
import { AuthContext } from '../providers/AuthProvider';

const Home =  () => {
  const [stateChoice, setStateChoice] = useState('')
  const auth = useContext(AuthContext)
  console.log(stateChoice)
  return(

Welcome!

 Hey there! Glad to see you. Please login to save a route to your prefered locations, or use the finder below to search for your State

      <StateSearch stateChoice={stateChoice} />

  )
};

export default Home;

As you can see, these are two separate files, how do i send the selection the user makes on the search bar as props to the original home page? (or send the state, either one)
Answer: You just need to pass one callback into your child.
Homepage
<StateSearch stateChoice={stateChoice} sendSearchResult={value => {
   // Your Selected value
}} />

Search bar
const StateSearch = ({ sendSearchResult }) => {

..... // Remaining Code

const handleSubmit = (value) => {
   setStateChoice(value);
   sendSearchResult(value);
}

Answer: You can lift the state up with function you pass via props.
const Home = () => {

  const getChoice = (choice) => {
    console.log(choice);
  }

  return <StateSearch stateChoice={stateChoice} giveChoice={getChoice} />
}

const StateSearch = (props) => {
  const handleSubmit = (value) => {
    props.giveChoice(value);
  }

  // Remaining code ...
}

Actually there is no need to have stateChoice state in StateSearch component if you are just sending the value up.
Comment: Hey thanks! The other posts worked too but yours was the most simple and easiest to understand answer. Thank you.
Answer: Just pass a setState to component
parent component:
const [state, setState] = useState({
   selectedItem: ''
})

<StateSearch state={state} setState={setState} />

change parent state from child component:
const StateSearch = ({ state, setState }) => {

const handleStateChange = (args) => setState({…state, selectedItem:args})

return (...
    <button onClick={() => handleStateChange("myItem")}/>
...)
}

Comment: Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
Answer: I'd recommend using the below structure for an autocomplete search bar. There should be a stateless autocomplete UI component. It should be wrapped into a container that handles the search logic. And finally, pass the value to its parent when the user selects one.

// import { useState, useEffect } from 'react' --> with babel import
const { useState, useEffect } = React  // --> with inline script tag

// Autocomplete.jsx

const Autocomplete = ({ onSearch, searchValue, onSelect, suggestionList }) => {

  return (

      <input
        placeholder="Search!"
        value={searchValue}
        onChange={({target: { value }}) => onSearch(value)}
      />
      <select
        value="DEFAULT"
        disabled={!suggestionList.length}
        onChange={({target: {value}}) => onSelect(value)}
        >
        <option value="DEFAULT" disabled>Select!</option>
        {suggestionList.map(({ id, value }) => (
          <option key={id} value={value}>{value}</option>
        ))}
      </select>

  )
}

// SearchBarContainer.jsx

const SearchBarContainer = ({ onSelect }) => {
  const [searchValue, setSearchValue] = useState('')
  const [suggestionList, setSuggestionList] = useState([])

  useEffect(() => {
    if (searchValue) {
      // some async logic that fetches suggestions based on the search value
      setSuggestionList([
        { id: 1, value: `${searchValue} foo` },
        { id: 2, value: `${searchValue} bar` },
      ])
    }
  }, [searchValue, setSuggestionList])

  return (
    <Autocomplete
      onSearch={setSearchValue}
      searchValue={searchValue}
      onSelect={onSelect}
      suggestionList={suggestionList}
    />
    )
}

// Home.jsx

const Home = ({ children }) => {
  const [result, setResult] = useState('')

  return (

      <SearchBarContainer onSelect={setResult} />
      result: {result}

  )
}

ReactDOM.render(<Home />, document.getElementById('root'))


My wired internet connection has stopped working

Question: For a few days I haven't been able to connect to internet through a wired connection to my router on my Ubuntu 14.04 LTS.
I only have the problem when trying to use Ubuntu: the same desktop connects to the internet on Windows7; another desktop a laptop using Windows7 also connect wirelessly through the same router and a Windows 8 laptop is fine as well...
How should I proceed?
Answer: In Ubuntu does the router assign your computer an IP address? If you open a terminal and type ifconfig you should see something like:
<code>eth0      Link encap:Ethernet  HWaddr 01:02:03:04:05:06
          inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::42:5dff:fe30:2342/64 Scope:Link
          inet6 addr: 2a02:1024:2048:3096:221:5dff:fe30:2342/64 Scope:Global
          inet6 addr: 2a02:1024:2048:3096:5015:f0ad:4336:5938/64 Scope:Global
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:424242 errors:0 dropped:0 overruns:0 frame:0
          TX packets:424242 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:20 Memory:f4600000-f4620000
</code>
If the "inet addr" shows a 192.168.x.x or 10.0.x.x address then you're at least getting an address from the router (meaning DHCP is working).
If you're not getting an IP address from the router, check your network connection settings: click the networking up/down arrows

click Edit

When the window appears click the Wired Connection 1 and Edit

Change to the IPv4 Settings tab and make sure it's set to Automatic (DHCP) (provided you're using DHCP). Also check the checkbox that says Require IPv4 addressing for this connection to complete is selected.

In your case it looks like you are getting an IPv6 address, but no IPv4 address. Some VOIP routers have issues with their IPv6 implementation. Windows tends to default to IPv4 which might explain why things work when you use Windows and not when you use Linux (which seems to be ONLY getting IPv6). Much of the world is moving to IPv6 but there are still some broken/buggy routers out there with bad implementations of IPv6. (Note: I'm using Xubuntu, your screens might be slightly different for Ubuntu).
Comment: Good first answer! ;-) Have a look at my edits and learn...  >:)
Comment: Thanks to Fabby and Charles for response. I really don't understand what is significant or not, so pls bear with me :-
Comment: :- when I enter ifconfig I get the following:
eth0      Link encap:Ethernet  HWaddr 6c:62:6d:d4:d1:66
          inet6 addr:fe80::6e62:6dff:fed4:d166/64  Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:426 errors:0 dropped:0 overruns:0 frame:0
          TX packets:386 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:54813 (54.8 KB)  TX bytes:91969 (91.9 KB)
Comment: AND l0        Link encap:Local Loopback
          inet addr: 127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:56 errors:0 dropped:0 overruns:0 frame:0
          TX packets:56 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:4448 (4.4 KB)  TX bytes:4448 (4.4 KB)
Comment: Sorry about lack of carriage returns - how do I add these into comments? Thx


When to have @types

Question: As I am reading some tutorials just like this one here
I noticed the author has introduced @type
as I am new into vue, I do not know what @type is! and iI do not have it in my .vue project.
would you please tell me in what scenario or case I would need to have @type and what it should container
Comment: The question is worded incorrecty as `@/types` != `@types`. The latter refers to scoped npm packages that augment the libs that don't have their own types
Answer: @/types refers to a folder called  types the @ means the folder is non-npm packages (see more at the following link for more information)
Usually you create this folder in order to store your interface/types related to your application. (see more at the following link for more information)
In the tutorial you can see that is importing a type called Product from this folder.
I hope I was able to help you.
good luck for the future !
Edit :
Historically, Vue used javascript as the programming language in its framework. In addition to this, Microsoft has developed Typescript which, as its name suggests, is a language similar to Javascript but with types. You can read the documentation on this subject in the link in my second reply.
As mentioned in the tutorial in your post, Typescript is now supported in version 3 of Vue. In the tutorial of your post, the author makes the choice to use Typescript and thus Types/Interface that Typescript propose as I was able to explain it in my answer.
I hope this is clearer for you.
I can only advise you to read the Typescript documentation and to use this language in the development of your future Vue applications.
In addition, the vue documentation is very well provided with examples using Typescript.
Comment: execuse me please, is vue a type-script?
Comment: I edited my post in order to explain more in details what Typescript is, because my text was too long I edited my post. I hope it can help you.
Comment: `@/types` != `@types`

When to have @types


communication between grandparentVC and rootVC

Question: My project is like this: rootVC(map) -> childVC(sidebar) -> grandchildVC(tableview)
I want to send data from grandchildVC -> rootVC but with a delegate it doesn't work.
if I transport the data via delegates like this: grandchildVC -> childVC -> rootVC it works...
but this cannot be the solution, it seems really dirty...
so..
1) can somebody help me to understand why i cant communicate directly?
2) are there some better solutions to send data from the grandchildVC to rootVC?
Comment: you can communicate directly can we see some code ??
Answer: You don't tell use what messages you are trying to send, but notifications (NSNotification) may be the solution you are looking for. The grandchild can post notifications without caring who is listening, or even how many.
Comment: i'm passing an array with objects to define and set annotations on my root(map)
Comment: i tried it with the notification and it works fine. thank you
Answer: Make sure that the rootVC is the delegate of the child and implements the delegate protocol.


Counting contiguous numbers within a list

Question: I am completely new to the topic of programming but interested.
I am coding in python 3.x and have a question to my latest topic:
We have a list, containing a few tenthousands of randomly generated integers between 1 and 7.
import random

list_of_states = []
n = int(input('Enter number of elements:'))

for i in range(n):
    list_of_states.append(random.randint(1,7))

print (list_of_states)

Afterwards, I would like to count the contiguous numbers in this list and put them into an numpy.array
example: [1, 2, 3, 4, 4, 4, 7, 3, 1, 1, 1]

1    1
2    1
3    1
4    3
7    1
3    1
1    3

I would like to know whether someone has a hint/an idea of how I could do this.
This part is a smaller part of a markov chain wherefor I need the frequency of each number.
Thanks for sharing
Nadim
Answer: Below is a crude way of doing this. I am creating a list of lists and then converting it to a numpy array. Please use this only a guidance and improvise on this.
import numpy as np

num_list = [1,1,1,1,2,2,2,3,4,5,6,6,6,6,7,7,7,7,1,1,1,1,3,3,3]

temp_dict = {}

two_dim_list = []

for x in num_list:
    if x in temp_dict:
        temp_dict[x] += 1
    else:
        if temp_dict:
            for k,v in temp_dict.items():
                two_dim_list.append([k,v])
            temp_dict = {}
        temp_dict[x] = 1

for k,v in temp_dict.items():
    two_dim_list.append([k,v])

print ("List of List = %s" %(two_dim_list))

two_dim_arr = np.array(two_dim_list)

print ("2D Array = %s" %(two_dim_arr))

Output:
List of List = [[1, 4], [2, 3], [3, 1], [4, 1], [5, 1], [6, 4], [7, 4], [1, 4], [3, 3]]
2D Array = [[1 4]
 [2 3]
 [3 1]
 [4 1]
 [5 1]
 [6 4]
 [7 4]
 [1 4]
 [3 3]]


Google App Script findText regex not working for new line character

Question: I'm trying to locate/modify text in my Google Document where the text has been broken across a full line break. My regular expression below works when I manually find text in the Google document (CTRL+F) and then search via the regular expression dialog. What is baffling is why the exact same regex doesn't work in the code below on full line breaks, i.e. "\n" (note: the soft line "\v" breaks are ok).
The second approach finds the text but I'm unable to do anything with it as I need the element object in-order to manipulate the text.
  //Test document 1Q6v8ipqA81LoPtpk71NdqTaIEqMjki1KIJbrm0bILBg contains the following text:
  //
  //This Agreement shall not be assigned by either party without the prior\n
  //written consent of the parties hereto

  var doc = DocumentApp.openById('1Q6v8ipqA81LoPtpk71NdqTaIEqMjki1KIJbrm0bILBg');

  //Method 1 - does NOT locate the text
  var body = doc.getBody();
  var pattern = "prior[\s]*written";
  var foundElement = body.findText(pattern);
  while (foundElement != null) {
    var foundText = foundElement.getElement().asText();
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    foundElement = body.findText(pattern, foundElement);
  }

  //Method 2 - locates the text, but I cannot acquire the element object
  var body2 = doc.getBody().getText();
  var pattern2 = /prior[\s]*written/;
  while (m=pattern2.exec(body2))
  {
    Logger.log(m[0]);
  }
}

Comment: I'm still fighting with this simple use-case.  Is it really not possible to search for text that is broken across a hard line break and subsequently highlight that text?  Seems like a basic use-case
Comment: Possible duplicate of [Eliminate newlines in google app script using regex](https://stackoverflow.com/questions/37771381/eliminate-newlines-in-google-app-script-using-regex)
Comment: Just to make sure: did you try adding `\r`? `"written[ \r\v\n]*consent"`?
Comment: yeah, tried both  \r and  \r\n
Comment: Try that on `.getBody().editAsText()`
Comment: no joy with
  .getBody().editAsText
using
  [ \r\v\n]*
Comment: Please share the document.
Comment: https://drive.google.com/open?id=1_gdcD0jT0jRVf0E3MfTqSZi_5gryznPYdNUoe-89Ors

The carriage return is after the text "prior":

This Agreement shall not be assigned by either party without the prior
written consent of the parties hereto.
Comment: should be visible now
Comment: It works like `var body = doc.getBody().getText(); var pattern = /written\s*consent/g; while (m=pattern.exec(body)) { Logger.log(m[0]);  }`
Comment: The "\s" switch kind-of works.  Problem is that it just returns the found string.  I need the getStartOffset and getEndOffsetInclusive values in-order to locate/manipulate the text
Comment: @PaulBrown, have you ever found an answer? Struggling as well! Thanks
Answer: If this were ever going to work, you would need the regex to be in s (single line) mode.  Per https://developers.google.com/apps-script/reference/document/body#findtextsearchpattern,

A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.

So it looks like they have in fact chosen not to support multi-line matches in any way.


Change entry file path of android and ios in react-native project

Question: After starting a new project with react-native init awesomeProject, i try to restructure my project, putting index.ios.js and index.android.ios inside a common folder named src.
When i execute react-native run-android, i get the following error:

Where i have to change to react-native search for entry files in the right path?
Comment: iOS can see http://stackoverflow.com/questions/30694367/how-to-rename-react-native-entry-file-index-ios-js
Answer: I've used the following steps on react-native 0.35
For development you need to open a file
MyProject/android/app/src/main/java/com/MyProject/MainApplication.java
and override a method of ReactNativeHost called getJSMainModuleName:
package com.MyProject;

// ...

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    // ...

    // ADD THE LINES BELOW

    @Override
    protected String getJSMainModuleName() {
      return "src/index.android";
    }

    // ADD THE LINES ABOVE

  };

  // ...
}

This way the app will know where to fetch the module from a packager server.
For production, when you build your APK using cd android && ./gradlew assembleRelease you'll have to modify a file
MyProject/android/app/build.gradle
and add custom build options, make sure to place them before apply from: "../../node_modules/react-native/react.gradle" line:
apply plugin: "com.android.application"

import com.android.build.OutputFile

// ...

// ADD THE LINES BELOW

project.ext.react = [
    // the entry file for bundle generation
    entryFile: "src/index.android.js",
]

// ADD THE LINES ABOVE

// ...

apply from: "../../node_modules/react-native/react.gradle"

Unfortunately I don't have iOS setup right now, I can't help you with that yet.
Comment: I consolidated `index.android.js` and `index.ios.js` into `index.js`. For me it was `entryFile: "index.js",`. Worked very well btw!
Comment: Worked very weel on dev setup. I don't need the production setup now, but i think will work when i need it. Thank you so much.
Answer: Thanks for Michael's info!
I did the case for iOS and make the answer complete for both Android and iOS.
As the same as Android,  the answers for development and production are different.

For Development (debug mode)
go to AppDelegate.m
set parameter jsBundleURLForBundleRoot as the path of entry file and moduleName as the component you registered in RN js. For example, if I want to change the entry js file to js/screen/LoginScreen.js and the component to LoginScreen, do the following:
jsCodeLocation = [[RCTBundleURLProvider sharedSettings]
    jsBundleURLForBundleRoot:@"js/screen/LoginScreen"
    fallbackResource:nil];
rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
    moduleName:@"LoginScreen"
    initialProperties:nil
    launchOptions:launchOptions];

For Production (release mode)

for production mode, Xcode generates a jsbundle file while building. Besides what we did for debug mode, we need to tell Xcode the entry file of jsbundle.
go to the "Build Phases" tab of current target.
in the "Bundle React Native code and images" phase, append your entry file to end of the shell

Info about how to run development/produc mode on iOS here


How to keep dictionaries of multiple models for CV (and use them in loop)

Question: I want to have a process which as result gives me a list of machine learning models and their accuracy score but only for the set of params which gives the best result of that type of model.
As example, here just the CV for XGBoost:
dataset:
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
data = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

from sklearn.model_selection import train_test_split
X = data.drop(['target'], axis=1)
y = data['target']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

function for finding best params:
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score, make_scorer
accu = make_scorer(accuracy_score) # I will be using f1 in future

def predict_for_best_params(alg, X_train, y_train, X_test):
    params = {'n_estimators': [200, 300, 500]}
    clf = GridSearchCV(alg, params, scoring = accu, cv=2)
    clf.fit(X_train, y_train)
    print(clf.best_estimator_)
    y_pred = clf.predict(X_test)
    return y_pred

using it on one model:
from xgboost import XGBClassifier
alg = [XGBClassifier()]
y_pred = predict_for_best_params(alg[0], X_train, y_train, X_test)

from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))

What I want to achieve is something like:
from xgboost import XGBClassifier
from sklearn.ensemble import RandomForestClassifier

alg = [XGBClassifier(), RandomForrest()] # list of many of them

alg_params = {'XGBClassifier': [{'n_estimators': [200, 300, 500]}],
             'RandomForrest': [{'max_depth ': [1, 2, 3, 4]}]}

def predict_for_best_params(alg, X_train, y_train, X_test, params):
    clf = GridSearchCV(alg, params, scoring = accu, cv=2)
    clf.fit(X_train, y_train)
    print(clf.best_estimator_)
    y_pred = clf.predict(X_test)
    return y_pred

for algo in alg:
    params = alg_params[str(algo)][0] #this won't work because str(algo) <> e.g. XGBClassifier() but XGBClassier(all default params)
    y_pred = predict_for_best_params(algo, X_train, y_train, X_test, params)
    print('{} accuracy is: {}'.format(algo, accuracy_score(y_test, y_pred)))

Is this a good way to achieve it?
Comment: Please refrain from asking for "the best way of [doing something]" - asking how to do it should be more than enough...
Answer: If you are only worried about how to put the key, then you can use
params = alg_params[alg.__class__.__name__][0]

This should return only the class name for the alg object
For an alternate approach, you can look at my other answer :

https://stackoverflow.com/a/51629917/3374996

That answer makes use of the fact that GridSearchCV can take a list of dicts of paramter combinations, in which each list will be expanded separately. But note the following things:

This can be faster than your current for-loop if you use n_jobs > 1 (use the multi-processing).
You can then use the cv_results_ attribute of the completed GridSearchCV to analyse the scores.
To calculate the y_pred for individual estimators, you can filter the cv_results_ (maybe by importing it in a pandas DataFrame), and then fitting the estimator with best found parameters again, and then calculating the y_pred. But should be pretty easy.
Comment: Hi. I think your answer(s) will be helpful for my question also - https://stackoverflow.com/questions/55468376/how-do-i-change-using-for-loops-to-call-multiple-functions-into-using-a-pi - Can you please have a look at it? I think my trouble right now is the `y_pred` part.


Threejs/ WebGL: Most performant way for just cubes?

Question: In Threejs, what is the most performant way to display a large number of cubes on an xyz grid for the WebGL renderer, in terms of which rendering methods/ lights/ settings/ material to use? The cubes should support receiving and casting shadows based on a directionLight -- or I can precalculate the side colors if that helps and is possible -- but they don't have any texture or special rotation. Thanks!
Answer: Be sure to merge your geometry. It helps a LOT. up to 60times more code. here is a post explaining why. It contains a demo actually showing the difference
http://learningthreejs.com/blog/2011/10/05/performance-merging-geometry/
Another things is to remove the duplicated faces when applicable. For example three.js minecraft demo remove the faces from the geometry. http://mrdoob.github.com/three.js/examples/webgl_geometry_minecraft.html for the demo and https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_minecraft.html#L106 for the source


How to pass data between activity using parcelable in android studio

Question: i have a recyclerview shows the list of movie,
i want when the item movie clicked can pass data to detail using parcelable
this my viewHolderAdapter
public class MovieVHolder extends RecyclerView.ViewHolder {

        TextView mTxtTitleMovie, mTxtDescriptionMovie, mTxtDateMovie;
        ImageView mImgPosterMovie;

        public MovieVHolder(@NonNull final View itemView) {
            super(itemView);
            mTxtTitleMovie = itemView.findViewById(R.id.txt_title_movie);
            mTxtDescriptionMovie = itemView.findViewById(R.id.txt_desc_movie);
            mTxtDateMovie = itemView.findViewById(R.id.txt_date_movie);
            mImgPosterMovie = itemView.findViewById(R.id.img_movie);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(context, DetailActivity.class);
                    context.startActivity(i);
                }
            });

        }

        public void bind(ListMovieEntity listMovieEntity) {
            mTxtTitleMovie.setText(listMovieEntity.getMovieTittle());
            mTxtDescriptionMovie.setText(listMovieEntity.getMovieDescription());
            mTxtDateMovie.setText(listMovieEntity.getMovieDate());
            Glide.with(context)
                    .load("https://image.tmdb.org/t/p/w185/"+listMovieEntity.getMoviePosterPath())
                    .into(mImgPosterMovie);
        }
    }

and I've added parcelable in model class
Comment: Does this answer your question? [Android: How to pass Parcelable object to intent and use getParcelable method of bundle?](https://stackoverflow.com/questions/10107442/android-how-to-pass-parcelable-object-to-intent-and-use-getparcelable-method-of)
Answer: change itemviewclick like this
itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(context, DetailActivity.class);
    //addthis       i.putExtra(DetailActivity.MOVIE, entListMovie.get(getPosition()));
                    context.startActivity(i);
                }
            });

and in the detail make like this
add this
public static final String MOVIE = "movie";

in method onCreate() add this
YourList yourList = getIntent().getParcelableExtra(MOVIE);

after that, just set the data
textview.setText(yourList.getBlaBla());

Comment: @AlFajri you also need to override `writeToParcel` method in your model
Comment: @MohitAjwani ya i've added that using generator parcelable
Answer: Intent supports three ways to pass data:
Direct: put our data into intents directly
Bundle: create a bundle and set the data here
Parcelable: It is a way of "serializing" our object.
Passing data: Direct
 Intent i = new Intent(context, DetailActivity.class);
i.putExtra("title", mTxtTitleMovie.getText().toString();
i.putExtra("surname", edtSurname.getText().toString();
i.putExtra("email", edtEmail.getText().toString();
context.startActivity(i);

Bundle
Intent i = new Intent(context, DetailActivity.class);
Bundle b = new Bundle();
b.putString("name", edtName.getText().toString());
b.putString("surname", edtSurname.getText().toString());
b.putString("email", edtEmail.getText().toString());
i.putExtra("personBdl", b);

context.startActivity(i);

Passing data: Parcelable
Let's suppose we have a class called Person that contains three attributes:name, surname and email.
Now if we want to pass this class it must implement the Parcelable interface like that
public class Person implements Parcelable {
private String name;
private String surname;
private String email;
// Get and Set methods

@Override
public int describeContents() {
return hashCode();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(email);
}

// We reconstruct the object reading from the Parcel data
public Person(Parcel p) {
name = p.readString();
surname = p.readString();
email = p.readString();
}

public Person() {}

// We need to add a Creator
public static final Parcelable.Creator<person> CREATOR = new Parcelable.Creator<person>() {

@Override
public Person createFromParcel(Parcel parcel) {
return new Person(parcel);
}

@Override
public Person[] newArray(int size) {
return new Person[size];
}
};

Now we simply pass data like that:
Intent i = new Intent(EditActivity.this, ViewActivity.class);
Person p = new Person();
p.setName(edtName.getText().toString());
p.setSurname(edtSurname.getText().toString());
p.setEmail(edtEmail.getText().toString());
i.putExtra("myPers", p);
startActivity(i);

As you notice we simply put our object Person into the Intent. When we receive the data we have:
Bundle b = i.getExtras();
Person p = (Person) b.getParcelable("myPers");
String name = p.getName();
String surname = p.getSurname();
String email = p.getEmail();


Right XPath syntax for getting nodelist of two types of elements by an ID

Question: I have an XML file with two types of elements, both have IDs. I would like to get a NodeList with the ones that have a specific ID.
<code>    StringBuffer exp = new StringBuffer("//wert[@ID='");
    exp.append(elementId);
    exp.append("'] or //feld[@ID='");
    exp.append(elementId);
    exp.append("']");
    XPathExpression expr = xpath.compile(exp.toString());
</code>
By doing this, however I get boolean as a return value. What would be the correct syntax, so that I could get a NodeList of the elements. Thanks!
Al
Answer: You want the union operator, <code>|</code>. The XPath you build should look like
<code>//wert[@Id='id']|//feld[@Id='id']
</code>


Alternative Wubi for Ubuntu 14.04

Question: I search alternative Wu bi ... I would Install Ubuntu in Disk C:\  with Files Windows.. in Wubi it's very awkward (Wubi is discontinued so..)
Someone have any  form?
Comment: Possible duplicate of [Is there a replacement for WUBI?](http://askubuntu.com/questions/751182/is-there-a-replacement-for-wubi)
Comment: Possible duplicate of [Wubi: Cannot download metalink and therefore the ISO (Change?)](http://askubuntu.com/questions/661729/wubi-cannot-download-metalink-and-therefore-the-iso-change)
Answer: Do a proper dual boot or use a virtual machine if your hardware is powerful enough.
Comment: There are no other software but using a virtual machine should give pretty much The same performance.
Comment: Why anyone would choose wine over vbox or vmware is beyond me :P
Comment: Thanks,  but i Look for alternative for wubi ( other programs work as Wubi)

Alternative Wubi for Ubuntu 14.04


MVC SelectLists using ViewBag SelectedItem not being set

Question: I have the following code:
public class OrganisationController : Controller
        {
            //
            // GET: /Organisation/

            public ActionResult Update()
            {
                var fisherman = new RoleType {Id = 1, Name = "Fisherman"};
                var manager = new RoleType {Id = 2, Name = "Manager"};
                var deckhand = new RoleType {Id = 3, Name = "Deckhand"};

                var roleTypes = new List<RoleType>
                    {
                        fisherman, manager, deckhand
                    };

                ViewBag.Roles = new SelectList(roleTypes, "Id", "Name");

                return View(
                    new Organisation
                        {
                            Name = "Fish Co.",
                            People = new List<Person>
                            {
                                new Person
                                {
                                    Name = "Squid",
                                    RoleType = fisherman
                                },
                                new Person
                                {
                                    Name = "Michael",
                                    RoleType = manager
                                },
                                new Person
                                {
                                    Name = "John",
                                    RoleType = deckhand
                                }
                            }
                        });
            }

            [HttpPost]
            public ActionResult Update(Organisation org)
            {
                return View();
            }

        }

    public class Organisation
        {
            public string Name { get; set; }
            public IList<Person> People { get; set; }
        }

public class Person
    {
        public string Name { get; set; }
        public RoleType RoleType { get; set; }
    }

public class RoleType
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

In Update.cshtml
 @model Models.Organisation

    <form action="" method="post" enctype="multipart/form-data">
        @Html.EditorFor(x => x.Name)
        @Html.EditorFor(x => x.People)
        <input type="submit"/>
    </form>

In the EditorTemplates Person.cshtml:
@model Models.Person

@Html.EditorFor(x => x.Name)
@if(Model != null)
{
    @Html.DropDownListFor( x => x.RoleType.Id, (SelectList)ViewBag.Roles)
}

I was expecting to be able to get to a page where I can update the organisation name, the people names and their roles. The trouble is that I can't get the selected item to be set for the dropdowns. I thought x => x.RoleType.Id would do this for me.
Does anyone know how I can get this to work?
Answer: Try this constructor: SelectList Constructor (IEnumerable, String, String, Object)
public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    Object selectedValue
)

Something like this:
@Html.DropDownListFor( x => x.RoleType.Id, new SelectList((List<RoleType>)ViewBag.Roles, "Id", "Name", Model.RoleType.Id))

Comment: Tried that but got, DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'.
Comment: @user2005657 add cast for `ViewBag`
Comment: Strange now it does Cannot convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.List' I don't know why it wouldn't be able to perform the cast


How to use RtlDecompressBuffer without knowing the size of the uncompressed data?

Question: I would like to use the WINAPI RtlDecompressBuffer in User Mode to decompress a buffer previously compressed using RtlCompressBuffer. I have the code for compression but it seems that in order to decompress I need to know the size of the uncompressed data as the function needs it as a parameter.
How can I do this without knowing the size of the uncompressed data?
Perhaps I should use RtlDecompressFragment.
A code sample would be great!
Thanks in advance.
Answer: You don't need to know the size of the uncompressed data. All you have to do is reserve enough memory to hold all the uncompressed data and pass that to the API.
If your buffer isn't big enough, the API will return STATUS_BAD_COMPRESSION_BUFFER and you then have to allocate a bigger buffer for the uncompressed data.
Comment: Thanks, this will do, although not perfect.
Comment: Hi, apparently, this is not quite correct. It seems that sometimes the function will return STATUS_SUCCESS even if there is still data left to be decompressed. The only solution I have found is to preallocate 13 times more than the compressed buffer which is based on the assumption that you cant compress anything by more than 92%.
Answer: Why not adding (while compressing) a simple header (first 4 bytes) to the buffer with the uncompressed size?


Unique set of words from string C++

Question: I am trying to write a function that inputs an array_string and finds unique words, then copies them over to unique_array. This is a bit over my head I feel like and need some advice on where to go from here..
void unique140(string str_array[], int array_size, string unique_array[], int&unique_size)
{
  int i = 0;
  int j = 0;

for(i = 0; i < array_size; i++)
{
  for(j = 0; j < unique_size; j++)
  if (str_array[i] != unique_array[j])
  {unique_array[i];}
  if(str_array[i] == unique_array[j]
  break;
 }

Comment: @gongzhitaao, Rather, `std::unique_copy`.
Comment: [`unique`](http://www.cplusplus.com/reference/algorithm/unique/) function.
Comment: I forgot to say that I cannot use that function. I have to make one myself.
Answer: Try something like:
void unique140(string str_array[], int array_size,
                 string unique_array[], int&unique_size)
{
    unordered_map<string,int> count;
    for(int i=0; i<array_size; i++) {
        count[str_array[i]]++;
    }
    unique_size = 0;
    for(auto it=count.begin(); it!=count.end(); ++it) {
        if(it->second==1) {
            unique_array[unique_size++] = it->first;
        }
    }
}

use a std::map if you dont have a std::unordered_map.
Answer: You're not a million miles away, the loops look good. Now you have to use those loops to make a decision, is the word str_array[i] present in the unique_array or not? Now just a minutes thought will tell you that str_array[i] is present if any one of the equality tests str_array[i] == unique_array[j] is true. Here's how to code that
for(i = 0; i < array_size; i++)
{
    bool in_unique_array = false;
    for(j = 0; j < unique_size; j++)
       if (str_array[i] == unique_array[j])
           in_unique_array = true;
    ...
}

Next we have to add str_array[i] to unique_array if it's not already there. So that's
for(i = 0; i < array_size; i++)
{
    bool in_unique_array = false;
    for(j = 0; j < unique_size; j++)
       if (str_array[i] == unique_array[j])
           in_unique_array = true;
    if (!in_unique_array)
    {
        ...
    }
}

Finally having decided to add the string to unique_array we have to do that
for(i = 0; i < array_size; i++)
{
    bool in_unique_array = false;
    for(j = 0; j < unique_size; j++)
       if (str_array[i] == unique_array[j])
           in_unique_array = true;
    if (!in_unique_array)
    {
        unique_array[unique_size] = str_array[i];
        unique_size++;
    }
}

Comment: when `present`, you could `break` :)
Comment: @gongzhitaao Yes, I'll leave that as an exercise for the OP
Comment: So this is saying.. if the element is not in unique array, copy it to unique_array[j]?       if (!in_unique_array) { unique_array[j]}    Still confused :(
Comment: This is still bad code. its O(N^2), when it could easily be N(logN) or even O(N)
Comment: @RichardPlunkett Given that the OP is struggling to understand this code do you think a more efficient version would be more useful to him?
Comment: @user3042929 Are you saying you're not sure how to copy from str_array to unique_array? That's very easy just use `=` to copy the string and then adjust the size. Or are you saying that I've misunderstood what you are trying to do? In any case I've editted the above post.
Comment: @john a fair enough thought. The map based answer seems to me to be simpler code, though introducing another type may dwarf that for OP.

Unique set of words from string C++


"No font found in Rcairo_set_font"

Question: I have the following error while trying to use Cairo: No font found in Rcairo_set_font
Here is the log:
> library(Cairo)
> Cairo.capabilities()
   png   jpeg   tiff    pdf    svg     ps    x11    win raster
  TRUE  FALSE  FALSE   TRUE   TRUE   TRUE   TRUE  FALSE   TRUE
> Cairo(600, 600, file="plot.png", type="png", bg="white")
Error in Cairo(600, 600, file = "plot.png", type = "png", bg = "white") :
  No font found in Rcairo_set_font

I'm using R version 3.2.1 on CentOS 7 (in a Docker container).
Does someone knows how I could avoid this error?
I didn't find anything on the web to fix this...
Answer: I've managed to fix this by installing the xorg-x11-fonts-Type1 package:
yum install xorg-x11-fonts-Type1

"No font found in Rcairo_set_font"


iOS designated initializer issues during assignment

Question: I have three properties defined in my header file as follows:
@property (nonatomic,strong) NSNumber *forCount;
@property (nonatomic,strong) NSNumber *againstCount;
@property (nonatomic,strong) NSNumber *neutralCount;

In my .m file I have then being synthesized using:
@synthesize forCount = _forCount;
@synthesize againstCount = _againstCount;
@synthesize neutralCount = _neutralCount;

My designated initializer is defined as:
- (id)initWithCounts:(NSNumber *)forInitCount
       againstCount:(NSNumber *)againstInitCount
       neutralCount:(NSNumber *)neutralInitCount
{
    NSLog(@"entering chartView initialization");

    NSLog(@"chartView initialization. data being sent: forCount:%@, againstCount:%@, neutralCount: %@",forInitCount,againstInitCount,neutralInitCount);

    if (self = [super init]) {

        [self setForCount:forInitCount];
        [self setAgainstCount:againstInitCount];
        [self setNeutralCount:neutralInitCount];

    }

    NSLog(@"chartView initialization. forCount:%@, againstCount:%@, neutralCount: %@",self.forCount,self.againstCount,self.neutralCount);

    [self setup];
    return self;
}

I'm drawing charts in the view in setup.
The assignment to the properties doesn't seem to be working. This is what my log looks like:
2013-11-21 03:13:20.897 testProj[4744:70b] entering chartView initialization
2013-11-21 03:13:20.897 testProj[4744:70b] chartView initialization. data being sent: forCount:10, againstCount:1, neutralCount: 5
2013-11-21 03:13:20.931 testProj[4744:70b] ChartView forCount: (null), againstCount: (null), neutralCount: (null)
2013-11-21 03:13:20.933 testProj[4744:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'

Any idea why the properties still remain as (null)?
Commenting out the [self setup] method also leads to the same (null) assignment. - Hence, I can rule out the setup method acting up.
I'm calling the method like so:
 NSLog(@"chartViewAtIndex about to be called. forCount:%@, againstCount:%@ and neutralCount:%@",self.forVotes[index],self.againstVotes[index],self.neutralVotes[index]);

ChartView *chartView = [[ChartView alloc]initWithCounts:self.forVotes[index] againstCount:self.againstVotes[index] neutralCount:self.neutralVotes[index]];

The log shows:
2013-11-21 09:43:46.551 testProj[5284:70b] chartViewAtIndex about to be called. forCount:10, againstCount:1 and neutralCount:5

A break statement after assignment, just before the NSLog line reveals that the assignment is correct:
_forCount   __NSCFNumber *  (int)10 0xb0000000000000a2
_againstCount   __NSCFNumber *  (int)1  0xb000000000000012
_neutralCount   __NSCFNumber *  (int)5  0xb000000000000052

Comment: Can you please add the code for `setup` method? Also code for calling method `initWithCounts:againstCount:neutralCount:`?
Comment: There is something U R not telling us, I made a copy of your code ind it works, show us the calling method, the allocation of your custom object
Comment: debug this 3 `[self setForCount:forInitCount];
        [self setAgainstCount:againstInitCount];
        [self setNeutralCount:neutralInitCount];` and see what happens in them. Write back the logs. Are they setting the values of `forCount, againstCount, neutralCount`?
Comment: Works fine here. Just called the method by sending in the 3 values as [NSNumber numberWithInt:]
Comment: what is super ? NSObject or some faillible class ?
Comment: This gets even weirder. I basically, created a new project and after importing my classes the code works. I still have the old project stored - puzzled!
Answer: Solved.
For anyone else have initialization issues double check what [super init] is going to do. In my case, I had another initializer which was being called and hence it messed things up. The other initializer called [self setup] without assigning values and hence the crash.


Referencing ranges from Excel call to change formats

Question: I am trying to create a call from a spreadsheet that will change to the format of a cell. When I explicitly enumerate the range (i.e. "C7") my code works. When I make it implicitly within the excel function call, it does not:
If I put =call_color in a cell, "C7" turns green. If I put =Color_Green(C7) in the same cell, it does not work.
Sub call_color()
    Dim TestVal As Range
    Set TestVal = Range("C7")
    Call Color_Green(TestVal)
End Sub
Sub Color_Green(ByRef MyRng As Range)
   ' Color Green Macro
    MyRng.Select
    With Selection.Interior
       .Color = RGB(0, 250, 0)
    End With
End Sub

I would like to be able to make some calculations in vb, and format a cell based on those calculations. How do I pass a range that will allow .interior functions to work?
Comment: You can do this with a sub but you cannot use a UDF called from a worksheet to alter the format of a cell, or the value of any cell but the caller.
Answer: Don't use select or selection and provide a parent worksheet reference.
Sub call_color()
    Dim TestVal As Range
    Set TestVal = worksheets("sheet1").Range("C7")
    Color_Green TestVal
End Sub

Sub Color_Green(ByRef MyRng As Range)
   ' Color Green Macro
    MyRng.Interior.Color = RGB(0, 250, 0)
End Sub


paypal integration for android and iOS, possible?

Question: in our apps, (versions for both OS), we want to allow the user to pay for subscription.
my app is being developed in Titanium for iOS, and native for android.
can i integrate paypal payments from them?? is posible?
or the solutions is redirect to a web-app (in safari mobile) to make payment, and then redirect to app??
i dont know if we can implement this as a "native" experience, using titanium+addons and paypal mobile sdk api.
if someone have experience, please show me some light....
Answer: Yes,paypal integration is possible in android  as well as iPhone.
Comment: thank you, so i assume that using paypal as "native" payment its ok for both.

will try it
Comment: http://stackoverflow.com/questions/4036494/how-can-i-integrate-paypal-to-payout-users-when-a-button-is-clicked, See this link it is helpful
Comment: thank you!! altough i've read in several forums that apple/google didnt like that we use a different payment method :( maybe i'll give a try...
Comment: try this link, http://stackoverflow.com/questions/3587060/android-and-paypal-api-integrationu need sandbox account as test account to test the paypal integration
Comment: simple answer for simple question. :-)
Answer: Using anything apart from Google Wallet as an in app Payment system on Android is a breach of the Google terms of service, so no
Answer: This is the Resolution for Paypal (Sandbox) Error "589023" in iPhone Application
<code>-(void)payWithPayPal{

PayPal *payPal=[PayPal getPayPalInst];

payPal.shippingEnabled = FALSE;

payPal.dynamicAmountUpdateEnabled = NO;

payPal.feePayer = FEEPAYER_EACHRECEIVER;

PayPalPayment *payment = [[[PayPalPayment alloc] init] autorelease];

payment.recipient = @"email@example.com";//mail id of the paypal account

payment.paymentCurrency = @"USD";

payment.description = @"Payment Discription here...";

payment.merchantName =@"Y S Rajashekar Reddy];

payment.invoiceData = [[[PayPalInvoiceData alloc] init] autorelease];

payment.invoiceData.invoiceItems = [NSMutableArray array];

PayPalInvoiceItem *item = [[PayPalInvoiceItem alloc] init];

item.totalPrice=[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.2f", 126.34545]]; // If u give xxx.xx , no need to give the %.2f , u can give directly %f

    item.name = @"Any Name";

    item.itemId = @"Item ID";

    [payment.invoiceData.invoiceItems addObject:item];

    [item release];
}

payment.subTotal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.2f",126.34545]]; //Total and Subtotal must be equal

payment.invoiceData.totalTax = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%.2f",3.34]];

NSLog(@"Total Tax is :%@",[payment.invoiceData.totalTax stringValue]);

[payPal checkoutWithPayment:payment];
}
</code>
Here the total and subtotal and Tax allows only two digits after the .(dot) Ex: (234.xx). So by using the %.2f to work perfectly.
Answer: yes, it is possible to integrate PayPal mechanism in iOS. Click here to see code for integrating PayPal in iOS Paypal integration in iOS