Proof that if $f:S^{n} \to \mathbb{R} $ is continuous, then is not injective

Question: I have to prove that if $f:S^{n} \to \mathbb{R} $ (where $S^{n}= \{(x_1, ..., x_{n+1})\in\mathbb{R}^{n+1} |  x_1^2+...+x_{n+1}^2=1\} $ is continuous, then is not injective. If possible, I would like it to be proven by using connectivity arguments.
My attempt: suppose $f$ is injective. Let $p\in f(S^n)$ and, since $f$ is injective, there exists only one $q\in S^n$ such that $f(q)=p$. We consider now $f_{|S^n \setminus\{q\}}:{S^n \setminus\{q\}} \to f(S^n\setminus\{q\})=f(S^n)\setminus\{p\} $, which is continuous and bijective (because $f$ was continuous and injective). Then, since ${S^n \setminus\{q\}}$ is path-connected and $f$ is continuous and exhaustive, we have that $f(S^n)\setminus\{p\}$ is path-connected as well.  Here I would like to use that $\mathbb{R}\setminus \{p\}$ is not path-connected and arrive at a contradiction, but this is wrong.
Comment: Pedantic note: The assertion is false for $n = 0$, it holds only for $n > 0$.
Answer: A different approach. Because $S^n$ is compact and $f$ is continuous, it attains a maximal and a minimal value. Let those be $M$ and $m$. So there exists points $A,B\in S^n$ such that $f(A)=M, f(B)=m$. On $S^n$ there are two disjoint paths, say $\gamma_1$ and $\gamma_2$, from $A$ to $B$ (on $S^1$ you find them by going around the circle in opposite directions, with $n>1$ there is a lot more elbow room).
But, by continuity, $f$ will take all the values in the interval $[m,M]$ on both $\gamma_1$ and $\gamma_2$.
Answer: Since $S^n$ is compact, if $f$ was injective, it would be a homeomorphism onto $f(S^n)$. But $S^n$ is compact and connected and the only subsets of $\mathbb R$ which are compact and connected are the the intervals $[a,b]$. However, if you remove one point from the middle of this interval, it becomes disconnected. No point of $S^n$ has that property.
Comment: What do you mean by "by invariance of domain"? We know it is a homeomorphism if $f$ is injective, since $S^n$ is compact and $\mathbb{R}$ is Hausdorff, but I don't get your first sentence.
Comment: Forget invariance of domain. I've found a simpler argument. I hope that everything is clear now.
Answer: Define $g(x) = f(x)-f(-x).$ It suffices to show $g=0$ somewhere on $S^n.$ To do this, take any $x_0\in S^n.$ If $g(x_0)=0,$ we're done. If not, then either $g(x_0) > 0$ or $g(x_0) < 0.$ Suppose WLOG $g(x_0) > 0.$ Then $g(-x_0) = -g(x_0) <0.$ Thus $g$ takes on both positive and negative values on $S^n.$ Since $g:S^n \to \mathbb R$ is continuous and $S^n$ is connected, $g=0$ somewhere on $S^n$ by the intermediate value property, and we're done.
Comment: Note this shows the even stronger result that injectivity fails at a pair of antipodal points.


Adding something at end of file in Python?

Question: I was just trying to add a string to end of file, but I can't get it to work. I get this error:
IOError: (9, 'Bad file descriptor')

I get it on line 123. It's in the code below, but marked with #hashcomment:
pluginlokacija2 = os.path.realpath("%s/plugins"%os.getcwd())
fo = open("%s/TwistedJobs/config.yml"%pluginlokacija2, "wb")
old = fo.read() #this is line no. 123
fo.seek(0)
fo.write("%s\n- %s\n " % (old, event.getPlayer().getName()))
fo.close

Thanks in advance, Amar!
P.S. If you need any more information, please ask for it in comments!
Comment: You opened the file for writing but then tried to read from it.
Answer: You want open(filename, "ab+") :

The mode can be 'r', 'w' or 'a' for reading (default), writing or
  appending.  The file will be created if it doesn't exist when opened
  for writing or appending; it will be truncated when opened for
  writing.  Add a 'b' to the mode for binary files. Add a '+' to the
  mode to allow simultaneous reading and writing.

Also with "append" mode you don't even have to read the existing content, seek(0) etc, you can just plain write:
bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
bruno@betty ~/Work/playground $ python
Python 2.7.3 (default, Apr 10 2013, 06:20:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("yadda.txt", "a+")
>>> f.write("newline here\n")
>>> f.close()
>>>
bruno@betty ~/Work/playground $ cat yadda.txt
foo
bar
newline here
bruno@betty ~/Work/playground $

Comment: You don't have to read / concatenate / seek(0) with the 'append' mode - just write what you have to.
Answer: You need to open the file for reading in order to use .read()
You have only opened it for writing with "wb".
Use "rb" to read, "wb" to write, and "ab" to append
adding a '+' like "ab+" allows for simulaneous reading and appending/writing
There is a reference for the different modes here
Example:
with open("filepath/file.ext", "ab+") as fo:
    old = fo.read() # this auto closes the file after reading, which is a good practice
    fo.write("something") # to the end of the file


Desktop stuck on software rendering (LIBGL_ALWAYS_SOFTWARE set)

Question: In my 17.04 desktop session,
LIBGL_ALWAYS_SOFTWARE=1

is set in the environment for all processes. That's clearly a bad idea.
I suspect that this happened because I temporarily had a bad OpenGL setup, and something decided to fall back to software rendering. The problem is that there is no indication whatsoever how to get unstuck.
FWIW, OpenGL works just fine with hardware acceleration when removing the environment variable:
unset LIBGL_ALWAYS_SOFTWARE=1; glxinfo

gives the expected output and so on.
Furthermore, LIBGL_ALWAYS_SOFTWARE is not set when logging into the system via ssh.
Comment: So what is your question exactly? Have you checked the usual suspects (i.e. shell configuration files, starting from `~/.bashrc`, `~/.profile` or `~/.bash_profile` if you have one, back through `/etc/profile.d/*`, `/etc/profile`, `/etc/environment`)?
Comment: @steeldriver I should have noted that the variable is **not** set when logging in via SSH, so it has to be related to the desktop login process.
Comment: Hmm... based on this previous answer [What happens under the covers to log me in and start up Unity or another Graphical User Interface?](https://askubuntu.com/a/150488/178692) it's possibly being set via the `/etc/X11/Xsession.d/50_check_unity_support` script. What is the result of executing `/usr/lib/nux/unity_support_test -p -f -d :0` manually?
Comment: Thanks for the hint. That wasn't it, but I got lucky and at least found a way to fix it.
Answer: Running the following command once and then logging in again fixed the issue:
systemctl --user unset-environment LIBGL_ALWAYS_SOFTWARE

Unfortunately, I still don't know what caused the setting in the first place.


Minecraft 1.8.9 won't start on Linux

Question: I use Minecraft: Java Edition on a Linux system. Whenever I try to launch versions 1.8.9 and before, the doesn't start, and as soon as I hit the "Play" button, the Launcher re-opens stating that the game has crashed. The game runs perfectly if I play it in earlier versions.
I was able to generate a crash report by enabling "Open output log when games start" in the Settings menu. It's a bit lengthy, so I made a Pastebin for it... https://pastebin.com/KN2Ac9vb
I would like to know what's going wrong, and how to fix this error so I can play 1.8.9 properly.
Answer: According to this question on stackoverflow, this is due to an issue in your Java install. Grabbing an earlier version of (or even just reinstalling) Java should fix it. Alternate JDKs may also work.

Minecraft 1.8.9 won't start on Linux


Concatenate multiple fields into a single field in marklogic

Question: These are the sample XMLs I'm uploading to my database:

<?xml version="1.0" encoding="UTF-8"?>
<AXFRoot>
  <MAObject type="default" mdclass="NEWS_VIDEO" label="News Video">
    <ID name="">123456</ID>
    <Meta name="MAINTITLE" format="string" label="Title">Clifford Irving hugs his wife Edith after her release from a Nassau jail.</Meta>
    <Meta name="SYSTEM_OBJECTOWNER" format="string" label="Owner">DEFAULT</Meta>
 <Meta name="KEYWORDS" format="string" label="Keywords">clifford-irving edith-irving prisoner-releases 1972-08-18 nassau new-york US nassau-county-jails prisons wifes husbands media, [],</Meta>
  </MAObject>
<AXFRoot>

<?xml version="1.0" encoding="UTF-8"?>
<AXFRoot>
  <MAObject type="default" mdclass="NEWS_VIDEO" label="News Video">
    <ID name="">456123</ID>
    <Meta name="MAINTITLE" format="string" label="Title">CAMEL NEWS CARAVAN- SEGMENT 2: US Military women march in Formosa in 1950.</Meta>
    <Meta name="SYSTEM_OBJECTOWNER" format="string" label="Owner">DEFAULT</Meta>
 <Meta name="KEYWORDS" format="string" label="Keywords">Military women-march Formosa-in-1950 United-States-army US</Meta>
  </MAObject>
<AXFRoot>

<?xml version="1.0" encoding="UTF-8"?>
<AXFRoot>
  <MAObject type="default" mdclass="NEWS_VIDEO" label="News Video">
    <ID name="">78946</ID>
    <Meta name="MAINTITLE" format="string" label="Title">Commercial US Title</Meta>
    <Meta name="SYSTEM_OBJECTOWNER" format="string" label="Owner">DEFAULT</Meta>
 <Meta name="KEYWORDS" format="string" label="Keywords">commercial 2009 english advertisement movie parts</Meta>
  </MAObject>
<AXFRoot>

What I want to do here is that, when I search for the word US by /search?q=US, I want the query result to have a data field in JSON which contains all the places which has the word US.
Eg :
data :{clifford-irving edith-irving prisoner-releases 1972-08-18 nassau new-york US nassau-county-jails prisons wifes husbands media, [],CAMEL NEWS CARAVAN- SEGMENT 2: US Military women march in Formosa in 1950.Military women-march Formosa-in-1950 United-States-army US Commercial US Title}
Is there a way of doing such queries in MarkLogic?
Answer: Using the Search API, you can get back an XML structure with a snippet showing each match in context.

http://docs.marklogic.com/search:search

You might need to specify a large max-snippet-chars value to make sure you get the entire snippet text:

http://docs.marklogic.com/guide/search-dev/appendixa#id_50098

Anyway, you can then transform the XML structure into a JSON object.  For instance, using the REST API, you can specify a post-processing transform for search:

http://docs.marklogic.com/REST/POST/v1/search
http://docs.marklogic.com/guide/rest-dev/transforms

By the way, the XML vocabulary appears to provide markup semantics via attribute values (especially the name attribute).  To be able to index and restrict search matches based on the markup semantics, you should consider changing the model so that the values are the markup, as in a MAINTITLE element and a OBJECTOWNER element.  Generic markup like a meta element is not useful to index.
Hoping that helps,


Partitions lost trying to create bootable iso disk

Question: I tried to create a bootable Ubuntu iso disk on a partition (sdc-2) of a usb stick, which had originally three partitions (sdc-1/2/3, of type ext3/fat32/ntfs). Following this thread, I ran:
sudo umount /dev/sdc2
sudo dd if=input.iso of=/dev/sdc

Now, I am not able to access the 3 partitions anymore. So first question, did I make a mistake? My feeling is that I should have used of=/dev/sdc2 instead, right?
Second question, how do I fix the problems:

The partitions are not shown. Running testdisk, I see one "iso" partition, but then, the "quick search" option shows the three underlying partition. How can I get the three partitions system back?
Previous partition sdc1 seems damaged. Testdisk detects it, but cannot list files. Did the dd operation irremediably damage it? Any change I could recover without using tools like photorecovery?

Thanks so much!!
Comment: If an answer was helpful to you, then please consider marking it as the [accepted answer](http://askubuntu.com/help/accepted-answer) so others may more easily find it in the future. This is also a polite way to thank the person answering your question for helping you out.
Answer: If you cannot access your files, choose "deeper search" which may take some time, but might be able to locate the proper sectors to recover the partition. Ensure the letter to the right of the partition type is not "D", as this means it's set for deletion. It can be changed to other partition types L,E or P (Logical, Extended, or Primary). Only duplicates that don't work should be marked for deletion after you've found all your working partitions.
Once you've located the partitions, and are able to access the files, choose the [Write] option to save the partition tables.
For complete instructions and detailed recovery options, please see this step by step guide : http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step
Comment: thanks a lot!!! The deeper search finds a ton of weird partitions, none of them seem to contain the files I wanted to recover :-( Also, I cannot choose the [write] as "partition table type "None" has been selected". Should I have selected another one?  What is the default one? Thanks!
Answer:
did I make a mistake?

You overwrote the beginning of drive /dev/sdc with a ISO file. From the last part of your question, it seems it is not what you wanted to do. Hence yes, it was a mistake. A pretty bad one.
You should have used /dev/sdc2.

How can I get the three partitions system back?

As you have determined, you can easily restore the 2nd and the 3rd ones by using TestDisk.
TestDisk can create a partition table from the file systems it finds on your drive. The basic idea, however, is that you shoulde use TestDisk to copy the files on a different drive, then recreate your partitions from scratch.
You won't be able to do the same on the first one because it is damaged. You need to analyze /dev/sdc1 with an advanced recovery tool like R-Linux.


Azure App Service Plan 'out of space' yet portal shows 99% free space

Question: When I deploy a project via Devops release pipeline I'm receiving the following error when running App Service Deploy:

There is not enough space on the disk.

I am confused how this can be the case given that the App Service Plan which the relevant app service resides has a 50Gb storage limit, and only just over 1.1Gb of that is being used.
Here's the full debug output from the devops pipeline:
2022-11-16T10:32:16.4226641Z ##[debug]ZIP Deploy response: {"statusCode":500,"statusMessage":"Internal Server Error","headers":{"content-length":"8414","connection":"close","content-type":"application/json; charset=utf-8","date":"Wed, 16 Nov 2022 10:32:16 GMT","server":"Microsoft-IIS/10.0","cache-control":"no-cache","expires":"-1","pragma":"no-cache","x-ms-request-id":"ef65e217-ab18-4421-9edc-7ae664b7fbba","x-aspnet-version":"4.0.30319","x-powered-by":"ASP.NET"},"body":{"Message":"An error has occurred.","ExceptionMessage":"There is not enough space on the disk.\r\n","ExceptionType":"System.IO.IOException"}

I've checked the storage account via SCM and can see that most of the storage is taken up with previously deployed Zip files, however this should not be an issue given that there is still 48+Gb space.
Is this a configuration issue? Can I manually increase/recalculate the available storage for the plan without changing tier? Any advice gratefully received.
Comment: Hi , Have you tried to deploy with Az Command Line? Is the same issue observed?
Is the same issue observed if you restart the App Service?
Answer: Looking at the shared information, I have understood that you are trying to deploy your app through Azure deVops and it is failed with error "There is not enough space on the disk" and also we see that(from shared screenshot) you have multiple app running under the same app service plan.
This might be happened due to the insufficient space in temp files not in the file system storage.
App service file system comes with persisted files and temporary files.

Persisted files: This is what you can view as your web site's files. They follow a structure described here. They are rooted in %HOME% directory. For App Service on Linux and Web app for Containers, persistent storage is rooted in /home.
All the files in persistent storage will remain even after the app restarts as well and these files are shared between all instances of your site (when you scale it up to multiple instances).
Temporary files: Unlike Persisted files, these files are not shared among site instances. Also, you cannot rely on them staying there. For instance, if you restart a web app, you'll find that all of these folders get reset to their original state.

You refer to this documentation for more information about the persistent files and temporary files in app service file system.

If you web app is running on the Windows app service plan i would suggest you install the Azure Web Apps Disk Usage extensions from site extensions through kudu console and using that extension you can understand which app is consuming more space and you can delete the unwanted space accordingly. Refer to this blog post to understand more what is taking my disk space for my azure web apps.
If you webapp are running on the Linux app service plan I would suggest restarting all the apps inside the app service plan to clear that temp file or try to scaleup the app service plan to next tier to increase the temp size.
Comment: Thanks for the answer. I discovered that the issue was due to the Temporary files stored within the App Service which hosted an Azure function. The AzFunc had kept all Zip files which had been deployed to it cached, and once I had cleared those out, using Kudu, the deployment worked as normal.


add machines and devices to MAAS with CLI

Question: I would like to pre-populate MAAS with new machines for future OS deployments.  For example, I have 10 servers, each with a quad port nic.  I know the MAC addresses (40) that belong to the servers (10), but don't know which MAC will get connected when the server is wired up.  How do I add these by script or CLI to MAAS.
Same question but for devices too. (routers, unmanaged hosts, etc.)
Currently, MAAS can discovery them, and I can add them to the database from the dashboard.  But this is time consuming, and has to be re-done everytime we trial out a new MAAS server.
Unless I am missing something, or the --help is incomplete, the CLI commands don't have add/create functions.
Seems odd to me that this command doesn't exist:
maas <user> nodes create
...so I am wondering if this is just not implemented yet, there is another way to handle this, or I am making a conceptual/workflow error.
Answer: maas <user> nodes is a read-only endpoint to read nodes. Nodes are a generic term for all Machines, Devices, and Controllers in MAAS. To be able to add a machine or device you must use the correct endpoint.
Add a machine:
maas <user> machines create [params]...
Add a device:
maas <user> devices create [params]...
Comment: Thank you.  Could you help me with what are the minimum parameters to add a machine using the CLI?  In the UI, we add a machine with a name, mac address, IPMI 2, IPMI ip address, username and password.   I can't seem to sort out the right parameters to automate this for new machines.
Comment: answered own question:

https://askubuntu.com/questions/939698/how-do-you-add-a-machine-to-maas-with-ipmi-power-using-cli


Find circle going through point of horizontal line $g_1$ and tangential to line $g_2$

Question: I have a problem in finding the radius and the center of a circle with the following conditions

Circle tangential to line $g_1$ and going through known point $P_1$
Circle is tangential to $g_2$

The following things I need to find:

radius of circle $(r)$
center of circle $(x_m, y_m)$
coordinates of $P_2 (x_2,y_2)$

So far I know that because of the horizontal line the middle point of the circle need to be $x_m = x_1$. I then tried to continue with the equation of a circle but I have still $2$ unknowns ($y_m$ and $r$) because I do not know how to use the constraint of $g_2$.
Does anybody have a hint how to solve this problem?
Edit #1:
I tried to understand the "Special cases of Apollonius' problem" with two lines and one point. Here is the current progress: But I do not know how to continue since becaues P1 is already a point on the circle/the tangent.
Comment: First: find intersection P of g1 and g2. Second: find point P2 of g2 such that PP1=PP2. There are two such points, there are two circles, satisfying problem statement. Third: find equations of lines g3 and g4 perpendicular to g1 and g2 and passing through P1 and P2. Fourth: find intersection of g3 and g4. This is center O. Fifth: find distance OP1, which is radius.
Answer: Let $P_1 = (x_1, y_1)$.  You can first find the intersection of $g_1$ and $g_2$.
Let the equation of $g_2$ be
$$ A x + B y + C = 0 $$
Set $ y = y_1$ and solve for $x$, this will give you,
$$ x = - \dfrac{B y_1 + C}{A} $$
Note that $A$ cannot be zero, because $g_2$ is not horizontal.  If it is horizontal, then the problem becomes trivial to solve.
So now the intersection point between $g_1$ and $g_2$ is
$P_3 = (x_3, y_3) = (- \dfrac{B y_1 + C}{A} , y_1 ) $
Find the signed distance between $P_1$ and $P_2$:
$ d =  x_1 - x_3  $
Next, find the angle between $g_1$ and $g_2$.  There are two possible angles.  The unit normal to $g_1$ is $u_1 = \langle 0, 1 \rangle$, and the unit normal to $g_2$ is $ u_2 = \langle \dfrac{A}{\sqrt{A^2 + B^2}}, \dfrac{B}{\sqrt{A^2 + B^2}} \rangle $.  To get the angle right, we have to use a combination of dot product and cross product of $u_1$ and $u2$.
$ \cos(\phi_1) = u_1 \cdot u_2 $
$ \sin(\phi_1) = \bigg[ u_1 \times u_2 \bigg]_z $
And $ \phi_1 = \text{Atan2}(\cos(\phi_1), \sin(\phi_1) ) $
Therefore, the two possible angles between $g_1$ and $g_2$ are
$ \phi_1 $ and $ \phi_2 = \pi - \cos^{-1} ( u_1 \cdot u_2 ) $
From this, it follows that the possible signed radii are
$ r_1 = d \tan \bigg( \dfrac{\phi_1}{2} \bigg) $
and
$r_2 = - d \tan \bigg( \dfrac{\phi_2}{2} \bigg) $
And the center will be at
$ C_i = P_1 + (0, r_i) $
As an example, suppose $g_1$ is the line $y = 10$, and $g_2$ is the line $ y = \sqrt{3} (x + 15) $
First find the intersection point between the two lines
$ 10 = \sqrt{3} (x + 15) $ implies $ x_3 = -15 + \dfrac{10}{\sqrt{3}} $
Suppose $P_1 = (10, 0) $ , then $ d = x_1 - x_3 = 25 - \dfrac{10}{\sqrt{3}} $
$ u_1 = \langle 0, 1 \rangle$, $ u_2 = \langle - \dfrac{\sqrt{3}}{2} , \dfrac{1}{2} \rangle $
From this
$ \cos(\phi_1)  = \dfrac{1}{2} $
$ \sin(\phi_1) = \dfrac{\sqrt{3}}{2} $
Therefore, $ \phi_1 = \dfrac{\pi}{3} $
And $ \phi_2 = \pi - \phi_1 = \dfrac{2 \pi}{3} $
From this,
$r_1 = d \tan(\dfrac{\pi}{6} ) = (25 - \dfrac{10}{\sqrt{3}}) (\dfrac{1}{\sqrt{3}} ) = \dfrac{1}{3} ( 25 \sqrt{3} - 10 ) $
And
$r_2 = - d \tan(\dfrac{\pi}{3} ) = - (25 \sqrt{3} - 10 ) $
Here is additional figures obtained from this algorithm.
Comment: Wow I'm really impressed. Thank you for this great solution. One question to that. Why there is a minus sign at r2? In my understanding a radius is always unsigned?
Comment: It is so you can add the signed radius to the point $P_1$ to obtain the center $C$ as follows  $C_i = P_1 + (0, r_i) $
Comment: Thanks for the explanation. Very nice solution
Comment: Just an additional question. Is this method also applicable if I have still two lines and not only P1 on g1 but also P2 on g2 is fixed? Or is this problem then overconstrained? Because now P2 is also a solution but what if it is an additional constraint?
Comment: Yes.  In this case, the problem will be over-constrained.
Comment: Okay thanks for this clarification.
Answer: If a circle is tangent to two lines, its center must be on one of the two angular bisectors of these two lines.
If a circle is touching a line in a given point, the center must be on the orthogonal line through that point, as you already found out.
This is a special case of Apollonius' problem, namely the one with two lines and one point, made even more special by the point lying on one of the lines.
Comment: Thank you for your hint. I tried to understand what I can find there but still do not know how to continue from the line connecting P1 and P2 on. The result of my understanding you can find at Edit #1.


Can't type inside EditText after setting visibility gone

Question: I have an EditText:
<EditText
        android:id="@+id/editWord"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text" />

In my activity I'm able to fire text changed events in this way:
editWord.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {
        //do stuff
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
         //do stuff
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //do stuff
    }
});

I need to hide the EditText and I tried adding this in my XML:
android:visibility="invisible"

After this the edit text disappears but events aren't fired. Why? How can I hide my EditText without "lose" events firing?
Comment: How are you changing the `EditText`'s text once its visibility is set to `invisible`?
Comment: Setting this in my activity manifest `android:windowSoftInputMode="stateVisible"` and `editWord.requestFocus()` in my activity
Answer: Why not just set the alpha to 0 in the xml of your EditText? android:alpha="0"
It should have the same visual effect of android:visibility="invisible" but will still call the addTextChangedListener methods.


Rails: Method returns object instead of attribute

Question: I'm in the process of building my first Rails application and am going crazy knowing this is probably a simple fix. I'm having trouble returning the proper object and attribute from a method. I have three models: User, Feed and Subscription.
User:
class User < ActiveRecord::Base
.
.
  has_many :subscriptions, dependent: :destroy
  has_many :feeds, through: :subscriptions

  def subscribe!(feed_id)
    subscriptions.create!(feed_id: feed.id)
  end
end

Subscription:
class Subscription < ActiveRecord::Base
.
.
  belongs_to :user, class_name: "User"
  belongs_to :feed, class_name: "Feed"

  validates :user_id, presence: true
  validates :feed_id, presence: true
end

Feed:
class Feed < ActiveRecord::Base
.
.
  belongs_to :subscriptions

  def self.create_feed(feed_url)
    feed = Feedzirra::Feed.fetch_and_parse(feed_url)

    unless exists? :feed_url => feed.url
      create!(
        :title => feed.title,
        :feed_url => feed.feed_url,
        :url => feed.url,
        :etag => feed.etag,
        :last_modified=> feed.last_modified
      )
    end
  end
end

Whenever I call user.subscriptions.create!(feed) explicitly from the console it works just fine, but the test using it don't pass. The test in question:
describe "subscribing" do
  let(:feed) { Feed.create_feed("http://www.somevalidfeed.com/feed/") }
  before { @user.subscribe!(feed) }
end

This returns:
NameError: undefined local variable or method `feed' for #<User:0x007f9c951b3b98>

I don't understand why this is returning an object or why it's trying to find the id of the User instead of the Feed object that's being passed to it. After searching for a few hours I just can't seem to get pointed in the right direction, so any help would be very much appreciated!
Answer: probably here's the problem:
  def subscribe!(feed_id)
    subscriptions.create!(feed_id: feed.id)
  end

probably you meant
  def subscribe!(feed_id)
    subscriptions.create!(feed_id: feed_id)
  end

or even
  def subscribe!(feed)
    subscriptions.create!(feed_id: feed.id)
  end

Answer: In your User class, I think your subscribe method is wrong, it should be
def subscribe!(feed)
  subscriptions.create!(feed_id: feed.id)
end

Comment: I knew it would be something simple like this! Thank you so much.


Setting a hotkey in a Java program that exits, without a GUI

Question: I'm writing a program that will run continuously and I was wondering if there was a Java equivalent to the Autoit SetHotKey(Key, Action()).  I saw an answer on here that related to a GUI interface, but my program does not have a GUI.  I just want the program to exit whenever I press a certain key, preferably ESC.
I'd have the program running in an infinite loop using the awt.Robot's keyevents, I'd like to be able to quit the program by pressing a certain key.
Comment: without any ui, how does the OS know to send you key events?
Answer: There are no core Java solutions since Java was built to be as operating system agnostic as possible, and to achieve your goal, you need a program that can integrate closer to the OS. The main solutions that I know of are to integrate your program to the OS via JNA, JNI, or (my favorite), AutoIt. Of done something similar by simply having my Java program and AutoIt communicate through standard IO and sockets.
A simple example:
Java program, TrialAutoIt3a.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Scanner;

public class TrialAutoIt3a {

   // ***** of course your path to program will be different
   private static final String AUTOIT_PATH = "C:/Users/Pete/Documents/Programming/AutoIt/Experiment/";
   private static final String AUTOIT_EXEC = "TestWithJava.exe";
   protected static final CharSequence EXIT = "exit";
   private static Process proc = null;

   public static void main(String[] args) {
      Runtime rt = Runtime.getRuntime();
      System.out.println("Type \"exit\" to exit program");

      try {
         proc = rt.exec(AUTOIT_PATH + AUTOIT_EXEC);
      } catch (IOException e1) {
         e1.printStackTrace();
         System.exit(-1);
      }
      InputStream iStream = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(iStream);
      final BufferedReader bufReader = new BufferedReader(isr);

      OutputStream oStream = proc.getOutputStream();
      final PrintWriter pw = new PrintWriter(oStream, true);

      Runnable bufReaderRunnable = new Runnable() {
         public void run() {
            String output;
            try {
               while ((output = bufReader.readLine()) != null) {
                  System.out.println(output);
                  if (output.toLowerCase().contains(EXIT)) {
                     proc.destroy();
                     System.exit(0);
                  }
               }
            } catch (IOException e) {
               e.printStackTrace();
            } finally {
               if (bufReader != null) {
                  try {
                     bufReader.close();
                  } catch (IOException e) {
                     e.printStackTrace();
                  }
               }
            }
         }
      };
      new Thread(bufReaderRunnable).start();

      Runnable myRun = new Runnable() {
         public void run() {
            Scanner scan = new Scanner(System.in);
            while (scan.hasNextLine()) {
               String line = scan.nextLine();
               pw.println(line);
            }
            scan.close();
         }
      };
      new Thread(myRun).start();

   }
}

AutoIt program, TestWithJava.au3:
Local $line = ""

While (True)

    $line = $line & ConsoleRead()

    If StringInStr($line, @CR) Or StringInStr($line, @LF) Then
        ConsoleWrite($line & "to java" & @CRLF)
        $line = ""
    EndIf

    Sleep(25)

WEnd

The AutoIt program will be compiled to an exe file prior to running this program
Comment: Do you have a post off hand that describes having autoit and java communicate to each other?


When to use async vs threads in python?

Question: Below are 2 examples that run sleep for 1 and 2 seconds each using async / await syntax and using threads. The results are seemingly the same but I think they fundamentally work differently. In which case, when to use async vs a thread?
import asyncio
import threading
import time
from datetime import timedelta

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def async_tasks():
    start_time = time.perf_counter()
    task1 = asyncio.create_task(say_after(1, 'hello'))
    task2 = asyncio.create_task(say_after(2, 'world'))
    await task1
    await task2
    print(f'async time: {timedelta(seconds=time.perf_counter() - start_time)}')

def say_after2(delay, what):
    time.sleep(delay)
    print(what)

def threads():
    start_time = time.perf_counter()
    task1 = threading.Thread(target=say_after2, args=(1, 'hello'))
    task2 = threading.Thread(target=say_after2, args=(2, 'world'))
    task1.start()
    task2.start()
    task1.join()
    task2.join()
    print(f'threads time: {timedelta(seconds=time.perf_counter() - start_time)}')

if __name__ == '__main__':
    asyncio.run(async_tasks())
    threads()

hello
world
async time: 0:00:02.002056
hello
world
threads time: 0:00:02.004553

Answer: Interesting to scale this up a bit. I bumped from 2 to 1000. The results were as below. Threads create bigger memory assignments (expected) so you can expect this to hit a limit faster than with asyncio. Both are limited by GIL and are not multi-processing.
size, peak: (0, 0)
async time: 0:00:00.134895
size, peak: (293112, 2303252)
threads time: 0:00:00.252217
size, peak: (497151, 4764784)

In asyncio gather is a nice way to do this.
async def async_tasks():
    start_time = time.perf_counter()
    tasks = []
    for _i in range(1000):
        tasks.append(asyncio.create_task(say_after(0.1, 'hello')))
    await asyncio.gather(*tasks)
    print(f'async time: {timedelta(seconds=time.perf_counter() - start_time)}')

The may be a nicer way with threading than what I used, however simple!
def threads():
    start_time = time.perf_counter()
    tasks = []
    for _i in range(1000):
        tasks.append(threading.Thread(target=say_after2, args=(0.1, 'hello')))
    for task in tasks:
        task.start()
    for task in tasks:
        task.join()
    print(f'threads time: {timedelta(seconds=time.perf_counter() - start_time)}')

From the docs (edited to use get_traced_memory as opposed to statistics which I had wrong)
if __name__ == '__main__':
    tracemalloc.start()
    print("size, peak:", tracemalloc.get_traced_memory())
    tracemalloc.reset_peak()
    asyncio.run(async_tasks())
    print("size, peak:", tracemalloc.get_traced_memory())
    tracemalloc.reset_peak()
    threads()
    print("size, peak:", tracemalloc.get_traced_memory())
    tracemalloc.reset_peak()

When to use async vs threads in python?


Weighted sum of adjacent values in numpy array

Question: What is the easiest/fastest way to take a weighted sum of values in a numpy array?
Example: Solving the heat equation with the Euler method
length_l=10
time_l=10
u=zeros((length_l,length_l))# (x,y)
u[:, 0]=1
u[:,-1]=1
print(u)
def dStep(ALPHA=0.1):
    for position,value in ndenumerate(u):
        D2u= (u[position+(1,0)]-2*value+u[position+(-1, 0)])/(1**2) \
            +(u[position+(0,1)]-2*value+u[position+( 0,-1)])/(1**2)
        value+=ALPHA*D2u()
while True:
    dStep()
    print(u)

D2u should be the second central difference in two dimensions. This would work if I could add indexes like (1,4)+(1,3)=(2,7). Unfortunately, python adds them as (1,4)+(1,3)=(1,4,1,3).
Note that computing D2u is equivalent to taking a dot product with this kernel centered around the current position:
 0, 1, 0
 1,-4, 1
 0, 1, 0

Can this be vectorised as a dot product?
Answer: I think you want something like:
import numpy as np
from scipy.ndimage import convolve

length_l = 10
time_l = 10
u = np.zeros((length_l, length_l))# (x,y)
u[:,  0] = 1
u[:, -1] = 1

alpha = .1
weights = np.array([[ 0,  1,  0],
                    [ 1, -4,  1],
                    [ 0,  1,  0]])

for i in range(5):
    u += alpha * convolve(u, weights)
    print(u)

You could reduce down a bit by doing:
weights = alpha * weights
weights[1, 1] = weights[1, 1] + 1

for i in range(5):
    u = convolve(u, weights)
    print(u)

Comment: Hmm... I am getting a `ValueError: object too deep for desired array
`
Comment: Are you sure you're importing `convolve` from `scipy.ndimage`? I believe I've seen this error before with the 1d-version of convolve.
Comment: Yeah, switching to the nd version fixed it.


better solution then a timeout for normalization delay

Question: I have to use this timeout, because submit gets fired before the normalization method finishish. This feels really sloppy, is there a better way?
        let submitButton = document.getElementById("hidden-submit");
        cleanFileName = files[0].name.normalize('NFD').replace(/\p{Diacritic}/gu, "");
        setTimeout(() => {
            submitButton.click();
        }, 10)

Comment: Are you sure that's what's happening?
Comment: @DaveNewton Yeah, cause once I remove the timeout it doesn't work anymore, I can't see another reason. I am using Svelte and binding the cleanFileName to an input. My s3 bucket can't handle Spanish characters
Comment: Clean the filename in a change event, or use a click event with a type="button" (rather than type="submit") button
Comment: @user2182349 This for drag and drop upload situation. Also its inside the change events.
Comment: I suspect you have not yet identified the underlying issue. More code might help diagnosis.
Answer: You can either use Promise :
new Promise(submitButton.click)

Or the window.onload method depending on the exact beahaviour you want :
window.onload = () => {
  const submitButton = document.getElementById("hidden-submit");
  cleanFileName = files[0].name.normalize('NFD').replace(/\p{Diacritic}/gu, "");
  submitButton.click();
}


Defining Parametric function for a plane passing through points

Question: Question: Propose how to define parametrically with functions x(u,v), y(u,v), z(u,v) a plane passing through points with coordinates (-4,0,0), (0,4,0), (2,0,4).
My thought process would be to use a bilinear representation to define the middle points, but I have no idea if that is the correct first step using the formula P' = P1 + u(P2 - P1)
May I have guidance on how should I tackle this question, I apologize if it seems trivial, I have no idea beyond trying using a bilinear representation, and even then I am not sure if it is the correct way of dealing with this.
Answer: Let $A=(-4,0,0), B=(0,4,0), C=(2,0,4).$
Taking arbitrarily point $A$ as the origin in the plane, let us express that the generic point $M=(x,y,z)$ is such that :
$$\vec{AM}=u \vec{AB}+v \vec{AC} \ \iff \ M=A+u \vec{AB}+v \vec{AC} \ \iff$$

$$\begin{cases} x&=&-4+4u+6v\\y&=& \ \ \ 0+4u+0v\\z&=& \ \ \ 0+0u+4v\end{cases}.$$

Verification : if $u=1$ and $v=0$, we find back $B$ ; if  $u=0$ and $v=1$, we find back $C$.


Undefined references compiling clang tutorial on 14.04.2

Question: I tried to compile the code from clang's libtooling tutorial (section "Put it together"). Compiling works:
g++ `llvm-config-3.5 --cxxflags` -fno-rtti  -c test.cpp -o test.o

I got undefined references from clang, so I even tried linking against all clang libraries:
CLANG_LIBS="$(ls /usr/lib/llvm-3.5/lib/libclang* | sed -e 's/.*lib/-l/g' -e 's/\.a//g' -e 's/\.so.*//g' | tr '\n' ' ' )"
g++ `llvm-config-3.5 --ldflags --libs` $CLANG_LIBS test.o -o test

I get ~ 15 undefined references:
    test.o: In function `ASTFrontendAction':
/usr/lib/llvm-3.5/include/clang/Frontend/FrontendAction.h:215: undefined reference to `clang::FrontendAction::FrontendAction()'
test.o: In function `SyntaxOnlyAction':
/usr/lib/llvm-3.5/include/clang/Frontend/FrontendActions.h:129: undefined reference to `vtable for clang::SyntaxOnlyAction'
test.o: In function `std::unique_ptr<clang::tooling::FrontendActionFactory, std::default_delete<clang::tooling::FrontendActionFactory> > clang::tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>()::SimpleFrontendActionFactory::~SimpleFrontendActionFactory()':
/usr/lib/llvm-3.5/include/clang/Tooling/Tooling.h:309: undefined reference to `clang::tooling::FrontendActionFactory::~FrontendActionFactory()'
test.o: In function `~SimpleFrontendActionFactory':
/usr/lib/llvm-3.5/include/clang/Tooling/Tooling.h:309: undefined reference to `clang::tooling::FrontendActionFactory::~FrontendActionFactory()'
test.o: In function `clang::tooling::ClangTool::~ClangTool()':
/usr/lib/llvm-3.5/include/clang/Tooling/Tooling.h:252: undefined reference to `clang::tooling::ClangTool::clearArgumentsAdjusters()'
test.o: In function `llvm::RefCountedBase<clang::FileManager>::Release() const':
/usr/lib/llvm-3.5/include/llvm/ADT/IntrusiveRefCntPtr.h:55: undefined reference to `clang::FileManager::~FileManager()'
test.o: In function `~ClangTool':
/usr/lib/llvm-3.5/include/clang/Tooling/Tooling.h:252: undefined reference to `clang::tooling::ClangTool::clearArgumentsAdjusters()'
test.o: In function `llvm::RefCountedBase<clang::FileManager>::Release() const':
/usr/lib/llvm-3.5/include/llvm/ADT/IntrusiveRefCntPtr.h:55: undefined reference to `clang::FileManager::~FileManager()'
test.o: In function `main':
/home/t0161834/cprogs/nccheck/test.cpp:24: undefined reference to `clang::tooling::CommonOptionsParser::CommonOptionsParser(int&, char const**, llvm::cl::OptionCategory&, char const*)'
/home/t0161834/cprogs/nccheck/test.cpp:26: undefined reference to `clang::tooling::ClangTool::ClangTool(clang::tooling::CompilationDatabase const&, llvm::ArrayRef<std::string>)'
/home/t0161834/cprogs/nccheck/test.cpp:27: undefined reference to `clang::tooling::ClangTool::run(clang::tooling::ToolAction*)'
test.o: In function `OptionCategory':
/usr/lib/llvm-3.5/include/llvm/Support/CommandLine.h:150: undefined reference to `llvm::cl::OptionCategory::registerCategory()'
test.o: In function `__static_initialization_and_destruction_0':
/home/t0161834/cprogs/nccheck/test.cpp:18: undefined reference to `clang::tooling::CommonOptionsParser::HelpMessage'
/home/t0161834/cprogs/nccheck/test.cpp:18: undefined reference to `llvm::cl::extrahelp::extrahelp(char const*)'
/home/t0161834/cprogs/nccheck/test.cpp:21: undefined reference to `llvm::cl::extrahelp::extrahelp(char const*)'
test.o:(.data.rel.ro._ZTVZN5clang7tooling24newFrontendActionFactoryINS_16SyntaxOnlyActionEEESt10unique_ptrINS0_21FrontendActionFactoryESt14default_deleteIS4_EEvE27SimpleFrontendActionFactory[_ZTVZN5clang7tooling24newFrontendActionFactoryINS_16SyntaxOnlyActionEEESt10unique_ptrINS0_21FrontendActionFactoryESt14default_deleteIS4_EEvE27SimpleFrontendActionFactory]+0x20): undefined reference to `clang::tooling::FrontendActionFactory::runInvocation(clang::CompilerInvocation*, clang::FileManager*, clang::DiagnosticConsumer*)'
collect2: error: ld returned 1 exit status

Installed packages:
$ dpkg -l "*clang*" | grep ii | awk '{ print $2 }' | tr '\n' ' '
clang-3.5 libclang-3.5-dev libclang-common-3.5-dev libclang1:amd64 libclang1-3.4:amd64 libclang1-3.5:amd64

$ dpkg -l "*llvm*" | grep ii | awk '{ print $2 }' | tr '\n' ' '
libllvm3.4:amd64 libllvm3.5:amd64 llvm-3.5 llvm-3.5-dev llvm-3.5-runtime

Can someone solve or at least reproduce the error?
Comment: Hey, I have the same problem and I'm looking into it as well. Will let you know if something comes up.
Comment: I actually had a different error (had to compile with '-fno-rtti') and after I solved it, I can now compile the example. I'm using llvm-3.7.1, are you sure the tutorial is supposed to work on 3.5?
Comment: @stanm Thanks, but since it's just a linker error, I guess it should work on 3.5. Also, 3.5 is not really old (2014).
Answer: The order of the cpp file and the clang libraries matters, as well as the order of clang libraries. I made it successfully link by using
g++ `llvm-config --cxxflags --ldflags` tool.cpp $CLANG_LIBS `llvm-config --libs --system-libs` -o tool

where CLANG_LIBS was defined as
CLANGLIBS="-lclangTooling -lclangFrontendTool -lclangFrontend -lclangDriver -lclangSerialization -lclangCodeGen -lclangParse -lclangSema -lclangStaticAnalyzerFrontend -lclangStaticAnalyzerCheckers -lclangStaticAnalyzerCore -lclangAnalysis -lclangARCMigrate -lclangRewrite -lclangRewriteFrontend -lclangEdit -lclangAST -lclangLex -lclangBasic -lclang"

Comment: After I've used your solution [and installed libedit](http://stackoverflow.com/questions/27926618/linker-issues-with-ledit-ubuntu-14-10/27928077), it worked. Thanks!


Why was MLP Classifier deprecated in Apache Mahout?

Question: I am wondering why MultiLayerPerceptron http://apache.github.io/mahout/0.10.1/docs/mahout-mr/index.html?org/apache/mahout/classifier/mlp/MultilayerPerceptron.html and all classes within MLP Package of Apache Mahout were deprecated. This was done as part of https://issues.apache.org/jira/browse/MAHOUT-1676. The JIRA issue doesn't mention about any reasons for doing so. I was planning to use this classifier in my project but since it is deprecated I am now hesitant to use it. I don't see any alternative version of classes to be used as mentioned in the Javadoc . Does anyone using Mahout for MLP has any idea?
Answer: I'm not sure how to answer this because it's basically off-topic. The mahout team considers that the MLP isn't used much by the community and it's painful to maintain so far. Thus they've decided to remove it since there exist other good implementations of it in other frameworks.
Comment: Thanks eliasah. I was just looking for that reason why it was discontinued. I thought it must be replaced with new set of classes that I am not aware of and couldn't find it online.


Is there any way to get element attribute names by Xpath?

Question: I can get attribute value of element by Xpath, but how to get all the attribute names?
example:
# there is an element
''
i = <Element img at 0x102622cb0>

In [10]: i.xpath("//img/@src")
Out[10]: ['http://fakesrc']

In [11]: i.xpath("//img/@*")
Out[11]: ['http://fakesrc', 'pic name']

How can I get the the names src/alt of i?
Comment: Using `@*` should get you all the attributes. I think your problem is that when displaying them, you're only seeing the value. You would need to iterate the collection returned and get the `name` property
Comment: Indeed, I can get the names by iterating the result, but it seems have no direct way to finish this job.
Answer: Depending on whether you want to include namespace prefixes or not, you can choose between the following two options in XPath 2.0:
//@*/local-name()
//@*/name()

Choose a different initial context node that fits your needs and see the specifications for more info.
With XPath 1.0, the above is not possible.  The following does work, but will only show the attribute name of one attribute, even if there are multiple ones.
local-name(//@*)
name(//@*)

Comment: In lxml(Python),  i.xpath("name(//img/@*)")   I got the first attribute name only... The result is 'src' instead of ['src', 'alt']
Comment: That's because in Python you're pretty much limited to XPath 1.0.
Comment: so now I iterate the result of //@* to get attribute names, grudgingly accepted.


Play a sound when a element gets animated using jquery

Question: Iam trying to build basic "simon game" that has been given as a challenge in my bootcamp. now iam struck at playing sounds when an button gets animated('here my animation is fadeOut(); and fadeIn();).
Iam getting the animation but sound is not playing while the button element is animating.
My HTML code is:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

Simon-Game

      <button type="button" id="green" class="green box"></button>
      <button type="button" id="red" class="red box"></button>
      <button type="button" id="yellow" class="yellow box"></button>
      <button type="button" id="blue" class="blue box"></button>

My JS code is:

var buttonColors = ["green", "red", "yellow", "blue"];
var gamePattern = [];

function nextSequence() {
  var randomNumber = Math.floor(Math.random() * 4);
  var chosenColor = buttonColors[randomNumber];
  gamePattern.push(chosenColor);
  $("#" + chosenColor)
    .fadeOut(500)
    .fadeIn(500);
  $("#" + chosenColor).playSound(chosenColor);
}

function playSound(chosenColor) {
  switch (chosenColor) {
    case "green":
      var audio = new Audio("sounds/green.mp3");
      audio.play();
      audio.autoplay = true;
      break;

    case "blue":
      var audio = new Audio("sounds/blue.mp3");
      audio.play();
      audio.autoplay = true;
      break;

    case "red":
      var audio = new Audio("sounds/red.mp3");
      audio.play();
      audio.autoplay = true;
      break;

    case "yellow":
      var audio = new Audio("sounds/yellow.mp3");
      audio.play();
      audio.autoplay = true;
      break;

    default:
      var audio = new Audio("sounds/wrong.mp3");
      audio.play();
      audio.autoplay = true;
  }
}

nextSequence();

Answer: you are calling playsound function on element which you cant because its not JS object. either define onclick method in HTML and call it using click. like $("#" + chosenColor).click(); or directly call the playsound function playSound(chosenColor)
Regarding playing sound you may observe that code snippet does not work here due to autoplay policy of editor. you may check working one here since autoplay policy allows us to run the audio without use interaction.
please check link for more details on autoplay-policy

var buttonColors = ["green", "red", "yellow", "blue"];
var gamePattern = [];

function playSound(chosenColor) {

  switch (chosenColor) {
    case "green":
      var audio = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3");

      audio.autoplay = true;
      audio.play();
      break;

    case "blue":
      var audio = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3");
      audio.autoplay = true;
      audio.play();
      break;

    case "red":
      var audio = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3");
      audio.autoplay = true;
      audio.play();

    case "yellow":
      var audio = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3");

      audio.autoplay = true;
      audio.play();

    default:
      var audio = new Audio("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3");

      audio.autoplay = true;
      audio.play();
  }
}
  function nextSequence() {
    var randomNumber = Math.floor(Math.random() * 4);
    var chosenColor = buttonColors[randomNumber];
    gamePattern.push(chosenColor);
    $("#" + chosenColor)
      .fadeOut(500)
      .fadeIn(500);
    // you can't call function on element.
    //*$("#" + chosenColor).playSound();

    //either define onclick method in HTML and call it using click.
    $("#" + chosenColor).click();
    // or directly call the playsound function
    playSound(chosenColor)
  }

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="style.css" />
  <title>Document</title>

Simon-Game

    <button type="button" onclick="playSound('green')" id="green" class="green box">Green</button>
    <button type="button" onclick="playSound('red')" id="red" class="red box">Red</button>
    <button type="button" onclick="playSound('yellow')" id="yellow" class="yellow box">Yellow</button>
    <button type="button" onclick="playSound('blue')" id="blue" class="blue box">Blue</button>

  <button onclick="nextSequence()">Start</button>

Comment: but I want the sound to be played when animating the button chosen, and not on click
Comment: like i said you just cant play sound in browser unless user has interacted with it. i would suggest to add a start button which user can click thus satisfying the chrome security condition and it will play sound. check my code snippet.
Comment: basically browser wants to make sure that user has interacted with screen before autoplaying anything,
Comment: Thank you , I got it
Comment: if this helped you make sure to mark the answer as accepted and upvote! and welcome to SO :)


A specialized interface of Drupal Answers for smart phones

Question: Is there any policy of Stack Exchange to design and develop smart phone application specially for iPhone/Android to give interface to Stack sites or is there any application around?
If there is no such app then do people look for such thing? As I do for my android smart phone.
The application should help the complete interaction interface for active users and moderators. Definitely this type of application would not help a lot for seekers.
Comment: You know about http://stackapps.com/questions/1843/android-app-for-stackoverflow?
Answer: The whole of SE has recently been tweaked to have a mobile optimized interface. It works quite well.
Comment: I am not looking to view it on mobile browsers. There should be an app to target an SE site and then filter questions of my interests with respect to tag, answer them, view and manage other basic tasks. App should be bandwidth saver on slow or costly internet services.
Answer: As reported by Berdir in his comment, applications that allows to browse the content of SE sites in Android exists, and there are native applications for smart phones running over Operating Systems too.
I am not aware of any limitation about the usage of the Stack Exchange API made from those applications, or any specific policy in act. You should check on stackapps about that.


Third party SDK returns incorrect value after notarizing my App

Question: I'm facing a pretty weird issue. I have a function GetInfoA() which returns the value processed from the SDK API. Everything is normal until the app is notarized from Xcode. The value returned from GetInfoA() will be incorrect. I have NO idea why this happened because all the other functions from the API return the correct value, which means the SDK is working properly... right?
Could anyone give me a hint on how to debug it? I'm clueless. Thanks in advance.
Comment: Update:
I found this issue may not be related to notarization. The same issue is found if the App is "archived" from Xcode.
Answer: Update:
I found this is not notarization-related. The "archived" app has this issue and could be solved by turning off the optimization. Thanx to Why is XCode archive acting different than XCode build/run on iPhone


Hapi Joi - validate concatenated keys

Question: I have a request body like this one:
bod = {
file: '123654',
extension: 'bbb',
...
}

I'm using hapi joi to validate it's fields:
let valSchema = {};
valSchema.play = Joi.object().keys({
    file: Joi.string().required().message("Invalid name. Please check documentation."),
    extension: Joi.string().empty().required().message("No extension sent. check the docs..."),
});

module.exports.valSchema = valSchema;

The problem is that one of the validations needs to check if the "$file:$extension" is in an array such as:
validConcatenations = [
    "1111:aaa","111123:bbb", "12312:aab",
    "21323:zzzs" ... ];

I would need to do this:
if (data.file && settings.fileWithExtensions.indexOf(`${data.file}:${data.extension}`) < 0) {
        return errors.invalidSampleRate;
    }

using joi...Is this possible using it?
using with?
Comment: in an array _where_? Because that sounds like a completely independent check in code that has nothing to do with validating your incoming data. It might immediately follow the initial data accepting step, but don't conflate the two: first validate the incoming data to make sure _it_ is correct as per your application requirements. Validation failure there is a signal _about the data_. If there then turns out to not be an array entry for it, that's not validation failure, that's a signal _about your system_, not the data itself. It isn't responsible for maintaining that array.
Answer: It is possible, all you need to do is a custom validation as the example below.
VERSION 16.1.8 or greater
'use strict';

const Joi = require('@hapi/joi');

const customValidation = function (value, helpers) {
    const validConcatenations = [
        "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
    if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
        throw Error(`Wrong concatenation ${value.file}:${value.extension}`)
    }
    return value;
};

const schema = Joi.object().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).custom(customValidation);

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));

Outputs:
{ value: { file: '123654', extension: 'bbb' },
  error:
   { ValidationError: "value" failed custom validation because Wrong concatenation 123654:bbb
     _original: { file: '123654', extension: 'bbb' },
     details: [ [Object] ] } }
{ value: { file: '1111', extension: 'aaa' } }

Looking at the docs it is possible to do the below solution since version 12.1.0
VERSION 12.1.0 or greater
'use strict';

const _Joi = require('@hapi/joi');

const custom = {
    base: _Joi.object(),
    name: 'custom',
    language: {
        concatenation: 'is a invalid concatenation',
    },
    rules: [
        {
            name: 'concatenation',
            validate(params, value, state, options) {
                const validConcatenations = [
                    "1111:aaa", "111123:bbb", "12312:aab", "21323:zzzs"];
                if (!validConcatenations.includes(`${value.file}:${value.extension}`)) {
                    return this.createError('custom.concatenation', {v: value}, state, options);
                }
                return value;
            }
        }
    ]
};

const Joi = _Joi.extend(custom);

const schema = Joi.custom().keys({
    file: Joi.string().required(),
    extension: Joi.string().empty().required(),
}).concatenation();

const wrongData = { file: '123654', extension: 'bbb' };
const niceData = { file: '1111', extension: 'aaa' };

console.log(schema.validate(wrongData));
console.log(schema.validate(niceData));

Outputs:
{ error:
   { ValidationError: "value" is a invalid concatenation
    at Object.exports.process (/tmp/test/node_modules/@hapi/joi/lib/errors.js:202:19)
    at type._validateWithOptions (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:762:31)
    at type.validate (/tmp/test/node_modules/@hapi/joi/lib/types/any/index.js:796:21)
    at Object.<anonymous> (/tmp/test/index.js:36:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
     isJoi: true,
     name: 'ValidationError',
     details: [ [Object] ],
     _object: { file: '123654', extension: 'bbb' },
     annotate: [Function] },
  value: { file: '123654', extension: 'bbb' },
  then: [Function: then],
  catch: [Function: catch] }
{ error: null,
  value: { file: '1111', extension: 'aaa' },
  then: [Function: then],
  catch: [Function: catch] }

Comment: "@hapi/joi": "^15.0.2" returns "TypeError: Joi.object(...).keys(...).custom is not a function" :(
Comment: @Eunito Can't you upgrade Joi to version [16.1.8](https://hapi.dev/family/joi/api/?v=16.1.8#anycustommethod-description) or greater?
Comment: unfortunatly no... Would cause retrocompatabilty issues! I'll need to perform extravalidation on the concatenated keys after joi does it's job on each Key...

Hapi Joi - validate concatenated keys


Proof $13 \mid (k\cdot 2^n+1)$ if $n\equiv2 \pmod{12}$ and $k\equiv3 \pmod{13}$?

Question:
Proof $13 \mid (k \cdot 2^n + 1)$ if $n\equiv2 \pmod{12}$ and $k\equiv3 \pmod{13}$
Hint: for $k$ odd: $2^n \equiv-k' \pmod p$ and $kk' \equiv1 \pmod p$

My thoughts:
$13\mid(k-3) \Rightarrow k=13a+3$
and
$12|(n-2)  \Rightarrow n=12b+2$
so
$\begin{align}k\cdot 2^n+1 &=(13a+3)2^{12b+2}+1 \\
&=4(13a+3)(2^{b})^{12}+1\\
\textrm{ or }
&=(k-3+3)\cdot 2^{n-2+2}+1\\
&=4\cdot 2^{n-2}(k-3+3)+1\\
&=4\cdot 2^{n-2}(k-3)+3\cdot2^n+1\end{align}$
I don't kow how to use the hint :(
Answer: If $n=12N+2$ and $k=13K+3$ then
$$
k2^n+1=13K2^n+3\cdot 4\cdot \left(\underbrace{2^{12}}_{\equiv 1\bmod{13}}\right)^{N}+1.
$$
Answer: By Fermat we have $2^{12} \equiv 1 \pmod{13}$ so $2^{12b}=1+13c$.
So
\begin{eqnarray*}
k2^n+1=(3+13a)(4+4 \times 13 c)+1=13(1+4a+12c+52ac)
\end{eqnarray*}
Answer: ${\rm mod}\ 13\!:\!\! \overbrace{\color{#c00}{ 2^{\large n}}\!\equiv 2^{\large 2+12j}}^{\large\quad\ \ \color{#c00}n\ \equiv\ 2\pmod{\!12}}\!\!\!\!\!\!\!\equiv 2^{\large 2}\color{#0a0}{(2^{\large 12})}^{\large j}\!\equiv 4\color{#0a0}{(1)}^{\large j}\!\equiv \color{#c00}4\,\ $ by $\ \rm\color{#0a0}{ Fermat}$
therefore $\ k\equiv 3\,\Rightarrow\, k\,\color{#c00}{2^{\large n}}\!+1\equiv 3\cdot \color{#c00}4+1\equiv 0\pmod{13}$


Which version of the Windows SDK uses xinput1_3.dll?

Question: I currently have Windows SDK 7.0A installed. This version of the SDK contains Xinput.h which references xinput9_1_0.dll:
#define XINPUT_DLL_A  "xinput9_1_0.dll"

I need my program to use xinput1_3.dll instead. I figured that in order to do this, I must link with the xinput.lib file from an earlier version of Windows SDK.
But, which version of the SDK contains the Xinput.h file that references xinput1_3.dll?
Answer: I think the solution is actually to use the Microsoft DirectX SDK (June 2010) by modifying the include and library dirs for your project. The XInput.h file from the DirectX SDK...
// XInput.h from the DirectX SDK

#ifndef XINPUT_USE_9_1_0
#define XINPUT_DLL_A  "xinput1_3.dll"
#define XINPUT_DLL_W L"xinput1_3.dll"
#else
#define XINPUT_DLL_A  "xinput9_1_0.dll"
#define XINPUT_DLL_W L"xinput9_1_0.dll"
#endif
#ifdef UNICODE
    #define XINPUT_DLL XINPUT_DLL_W
#else
    #define XINPUT_DLL XINPUT_DLL_A
#endif

... is actually a little different to the one from the Windows SDK...
// XInput.h from the Windows SDK

#define XINPUT_DLL_A  "xinput9_1_0.dll"
#define XINPUT_DLL_W L"xinput9_1_0.dll"
#ifdef UNICODE
    #define XINPUT_DLL XINPUT_DLL_W
#else
    #define XINPUT_DLL XINPUT_DLL_A
#endif

So, by default, the DirectX SDK will actually use xinput1_3.dll.
Comment: Hmm, that's strange... I wonder why this was down voted. Seemed like the best solution to me. Can any one shed some light on this?
Comment: Seems like a good answer. Loosely related: what are the differences between 1.3 and older versions of XInput? I have found a MSDN document, but it is very brief and does not really say much: http://msdn.microsoft.com/en-us/library/windows/desktop/hh405051(v=vs.85).aspx
Answer: The modified date on XInput9_1_0.dll reads 2009-07-14, so I will try to use the latest version before this release, which is: v6.1 (Windows Server 2008 & .NET 3.5 SDK) from 2008-02-05


Connect to remote JSON/XML REST service using WCF in .NET 4.5 or above+

Question: I want to consume a remote REST service using WCF in .NET 4.5 or above.  It is for some desktop application software I am writing.  I am electing to use WCF as I currently believe it to be the most appropriate technology in .NET unless anyone says otherwise.
The service is accessed by either GET or POST (the same response) and can return either JSON or XML which is specified as a URL parameter.  However, even though it can return XML, there is no WSDL file.
I want to access this service without the use of any third party libraries.
My questions:

Is WCF the best technology to do this in .NET 4.5 or above?
Which are the appropriate classes/methods to connect, send the GET or POST request and await the response?
Is there a way to tell WCF to automagically fill my model classes with the de-serialized json or xml and if not which is the latest/recommended de-serialization class within .NET?

Here is an example URL of the service:
XML: http://www.expasy.org/cgi-bin/prosite/PSScan.cgi?seq=ENTK_HUMAN&output=xml
JSON: http://www.expasy.org/cgi-bin/prosite/PSScan.cgi?seq=ENTK_HUMAN&output=json
Here is an example of what is returned by the service in XML:
<?xml version="1.0" encoding="UTF-8"?>
<matchset xmlns="urn:expasy:scanprosite" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:expasy:scanprosite http://expasy.org/tools/scanprosite/scanprosite.xsd" n_match="13" n_seq="1">
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>54</start>
    <stop>169</stop>
    <signature_ac>PS50024</signature_ac>
    <signature_id>SEA</signature_id>
    <score>32.979</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>183</start>
    <stop>222</stop>
    <signature_ac>PS50068</signature_ac>
    <signature_id>LDLRA_2</signature_id>
    <score>10.75</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>197</start>
    <stop>221</stop>
    <signature_ac>PS01209</signature_ac>
    <signature_id>LDLRA_1</signature_id>
    <level_tag>(0)</level_tag>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>225</start>
    <stop>334</stop>
    <signature_ac>PS01180</signature_ac>
    <signature_id>CUB</signature_id>
    <score>13.293</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>345</start>
    <stop>504</stop>
    <signature_ac>PS50060</signature_ac>
    <signature_id>MAM_2</signature_id>
    <score>42.203</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>391</start>
    <stop>431</stop>
    <signature_ac>PS00740</signature_ac>
    <signature_id>MAM_1</signature_id>
    <level_tag>(0)</level_tag>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>524</start>
    <stop>634</stop>
    <signature_ac>PS01180</signature_ac>
    <signature_id>CUB</signature_id>
    <score>17.206</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>642</start>
    <stop>678</stop>
    <signature_ac>PS50068</signature_ac>
    <signature_id>LDLRA_2</signature_id>
    <score>13.3</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>655</start>
    <stop>677</stop>
    <signature_ac>PS01209</signature_ac>
    <signature_id>LDLRA_1</signature_id>
    <level_tag>(0)</level_tag>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>678</start>
    <stop>788</stop>
    <signature_ac>PS50287</signature_ac>
    <signature_id>SRCR_2</signature_id>
    <score>16.02</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>785</start>
    <stop>1019</stop>
    <signature_ac>PS50240</signature_ac>
    <signature_id>TRYPSIN_DOM</signature_id>
    <score>39.104</score>
    <level>0</level>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>821</start>
    <stop>826</stop>
    <signature_ac>PS00134</signature_ac>
    <signature_id>TRYPSIN_HIS</signature_id>
    <level_tag>(0)</level_tag>
</match>
<match>
    <sequence_ac>P98073</sequence_ac>
    <sequence_id>ENTK_HUMAN</sequence_id>
    <sequence_db>sp</sequence_db>
    <start>965</start>
    <stop>976</stop>
    <signature_ac>PS00135</signature_ac>
    <signature_id>TRYPSIN_SER</signature_id>
    <level_tag>(0)</level_tag>
</match>
</matchset>

Here is an example of what is returned by the service in JSON:
{
"n_match" : 13, "n_seq" : 1,
"matchset" : [
{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 54, "stop" : 169, "signature_ac" : "PS50024", "signature_id" : "SEA", "score" : 32.979, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 183, "stop" : 222, "signature_ac" : "PS50068", "signature_id" : "LDLRA_2", "score" : 10.75, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 197, "stop" : 221, "signature_ac" : "PS01209", "signature_id" : "LDLRA_1", "level_tag" : "(0)"},{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 225, "stop" : 334, "signature_ac" : "PS01180", "signature_id" : "CUB", "score" : 13.293, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 345, "stop" : 504, "signature_ac" : "PS50060", "signature_id" : "MAM_2", "score" : 42.203, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 391, "stop" : 431, "signature_ac" : "PS00740", "signature_id" : "MAM_1", "level_tag" : "(0)"},{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 524, "stop" : 634, "signature_ac" : "PS01180", "signature_id" : "CUB", "score" : 17.206, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 642, "stop" : 678, "signature_ac" : "PS50068", "signature_id" : "LDLRA_2", "score" : 13.3, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 655, "stop" : 677, "signature_ac" : "PS01209", "signature_id" : "LDLRA_1", "level_tag" : "(0)"},{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 678, "stop" : 788, "signature_ac" : "PS50287", "signature_id" : "SRCR_2", "score" : 16.02, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 785, "stop" : 1019, "signature_ac" : "PS50240", "signature_id" : "TRYPSIN_DOM", "score" : 39.104, "level" : 0 },{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 821, "stop" : 826, "signature_ac" : "PS00134", "signature_id" : "TRYPSIN_HIS", "level_tag" : "(0)"},{"sequence_ac" : "P98073", "sequence_id" : "ENTK_HUMAN", "sequence_db" : "sp", "start" : 965, "stop" : 976, "signature_ac" : "PS00135", "signature_id" : "TRYPSIN_SER", "level_tag" : "(0)"}
] }

Here are the model classes I already made, although I'm not sure if I needed to make them or if WCF can automagic one for me:
    public class PrositeScanMatchSet
    {
        public int n_match { get; set; }
        public int n_seq { get; set; }
        public PrositeScanMatch[] matchset { get; set; }
    }

    public class PrositeScanMatch
    {
        public string sequence_ac { get; set; }
        public string sequence_id { get; set; }
        public string sequence_db { get; set; }
        public int start { get; set; }
        public int stop { get; set; }
        public string signature_ac { get; set; }
        public string signature_id { get; set; }
        public float score { get; set; }
        public int level { get; set; }
        public string level_tag { get; set; }
    }

Also, here is a class I made to make the service query string:
public class ScanPrositeParameters
{
    ///
    /// Sequence(s) to be scanned: UniProtKB accessions e.g. P98073 or identifiers e.g. ENTK_HUMAN or PDB identifiers e.g. 4DGJ or sequences in FASTA format or UniProtKB/Swiss-Prot format.
    /// Do not repeat parameter; multiple sequences can be specified by separating them with new lines(%0A in url).
    ///
    public string seq        ;

    ///
    /// Motif(s) to scan against: PROSITE accession e.g. PS50240 or identifier e.g. TRYPSIN_DOM or your own pattern e.g. P-x(2)-G-E-S-G(2)-[AS].
    /// If not specified, all PROSITE motifs are used.
    /// Do not repeat parameter; multiple motifs can be specified by separating them with new lines(%0A in url).
    ///
    public string sig        ;

    ///
    /// Target protein database for scans of motifs against whole protein databases: 'sp' (UniProtKB/Swiss-Prot) or 'tr' (UniProtKB/TrEMBL) or 'pdb' (PDB).
    /// Only work if 'seq' is not defined.Parameter can be repeated; 1 target db by 'db' parameter.
    ///
    public string db         ;

    ///
    /// If true (defined, non empty, non zero): includes UniProtKB/Swiss-Prot splice variants.
    /// Only works on scans against UniProtKB/Swiss-Prot.
    ///
    public string varsplic   ;

    ///
    /// Any taxonomical term e.g. 'Homo sapiens', e.g. 'Fungi; Arthropoda' or corresponding NCBI TaxID e.g. 9606, e.g. '4751; 6656'
    /// Separate multiple terms with a semicolon.
    /// Only works on scans against UniProtKB/Swiss-Prot and UniProtKB/TrEMBL.
    ///
    public string lineage    ;

    ///
    /// Description (DE) filter: e.g. protease.
    /// Only works on scans against UniProtKB/Swiss-Prot and UniProtKB/TrEMBL.
    ///
    public string description;

    ///
    /// Number of X characters in a scanned sequence that can be matched by a conserved position in a pattern.
    /// Only works if 'sig' is defined, i.e.on scans of specific sequences/protein database(s) against specific motif(s).
    /// Only works on scans against patterns.
    ///
    public string max_x      ;

    ///
    /// Output format: 'xml' or 'json' (or 'txt')
    ///
    public string output     ;

    ///
    /// If true (defined, non empty, non zero): excludes motifs with a high probability of occurrence.
    /// Default: on.
    /// Only works if 'seq' is defined and 'sig' is not defined, i.e.on scans of specific sequence(s) against all PROSITE motifs.
    ///
    public string skip       ;

    ///
    /// If true (defined, non empty, non zero): shows matches with low level scores.
    /// Default: off.
    /// Only works with PROSITE profiles.
    ///
    public string lowscore   ;

    ///
    /// If true (defined, non empty, non zero): does not scan against profiles.
    /// Only works if 'seq' is defined and 'sig' is not defined, i.e.on scans of specific sequence(s) against all PROSITE motifs.
    ///
    public string noprofile  ;

    ///
    /// Mimimal number of hits per matched sequences.
    /// Only works if 'sig' and 'db' are defined, i.e.on scans of protein database(s) against specific motif(s).
    ///
    public string minhits    ;

    public string QueryString()
    {
        var result = new Dictionary<string, string>()
        {
            {"seq", seq},
            {"sig", sig},
            {"db", db},
            {"varsplic", varsplic},
            {"lineage", lineage},
            {"description", description},
            {"max_x", max_x},
            {"output", output},
            {"skip", skip},
            {"lowscore", lowscore},
            {"noprofile", noprofile},
            {"minhits", minhits}
        };

        return String.Join("&", result.Where(a => a.Key != null && a.Value != null).Select(kvp => WebUtility.UrlEncode(kvp.Key) + "=" + WebUtility.UrlEncode(kvp.Value)).ToList());
    }

}

Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Answer: Using WCF seems like overkill when the server supports a REST Get interface.
The XDocument class can read a XML uri.
var doc = XDocument.Load("http://www.expasy.org/cgi-bin/prosite/PSScan.cgi?seq=ENTK_HUMAN&output=xml");

You can then use LINQ to locate data.  See Basic Queries http://msdn.microsoft.com/en-us/library/bb943906.aspx for more details.
Answer: I would recommend looking at HttpClient to retrieve JSon from the Remote Service.
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
Answer: You have 3 questions here so I'm going to answer them all and build upon other people's answers: -
Is WCF the best technology to do this in .NET 4.5 or above?
WCF is a very powerful communication framework but as one of the answers above states; you could very easily just communicate with the REST server using a much simpler HttpClient. You mention you want to either use JSON/XML, which implies that, potentially, in the future, this may be expanded upon to support another format, so I believe that it would be more appropriate not to use WCF at this time and follow the concept of KISS. You should easily be able to swap out your connectivity code if you use an interface. (http://en.wikipedia.org/wiki/KISS_principle)
I'm sure you have already done a lot of research on WCF but if not, take a looks at http://msdn.microsoft.com/en-us/library/ms731082%28v=vs.110%29.aspx. The MSDN documentation is surprisingly good for getting started.
Which are the appropriate classes/methods to connect, send the GET or POST request and await the response?
This has already been answered; your client will know already whether it is requesting xml/json so you will just pass the data to the appropriate reader that will parse JSON/XML/other formats.
Luckily .NET has numerous APIs available to help you parse these languages and this will help answer your final question.
Is there a way to tell WCF to automagically fill my model classes with the de-serialized json or xml and if not which is the latest/recommended de-serialization class within .NET?
Most definitely..
JSON
See http://msdn.microsoft.com/en-us/library/bb412179%28v=vs.110%29.aspx

How to: Serialize and Deserialize JSON Data

That will show you how to de-serialise the JSON data into your model classes; which also elaborates on doing it with WCF aswell, so this might be very useful to you. This includes the recommended class to use for deserialising JSON using DataContractJsonSerializer. It's recommended to use this because these classes don't rely upon the C# compiler, whereas one of the more commonly used previous methods before .NET 3.5/4 did.
XML
Quite a high upvoted question/answer here for doing it with XML which includes example working code: -
How to Deserialize XML document

How to Deserialize XML document

Make sure you have a look at the non accepted answer that uses XSD as well as the accepted answer. Both viable solutions; use what you feel is right for you! :)
Good luck!


Bolt/Fire Damage stat on weapons

Question: I've been really confused about this since I started getting my first attribute adding gems.
I am getting gems that add fire/bolt damage to a weapons. Still, adding that gem to a weapon doesn't activate flame/bolt visual effect.
I am wonder if those elemental damages actually work if the appropriate paper is not activated. For instance does a sword with +20 fire damage gem add the fire damage to each hit or does the +20 only increase effect of fire paper?
Also, assuming I use a weapon with fire damage gem, but no fire paper, do oil urns make the fire damage more effective?
Answer: When you get a gem that 'adds fire damage', it usually converts all damage done to fire.  Same with bolt.  It does two things: converts all damage from the weapon into elemental damage and converts the scaling of the weapon to Arcane.  This usually significantly reduces the amount of damage you do with the weapon, in favor of scaling off of Arcane and doing elemental damage.  While the effect does not show on your weapon, it does show when you hit someone with it (a fire weapon will show a fire effect when you hit an enemy).
You do not need bolt or fire paper for this.  Paper only adds the effect to the weapon if it wasn't already there.  So, for a normal weapon that you add fire paper for, you simply add a fire damage number to the weapon that, again, scales off of arcane.
And oil does increase the effect of fire damage done to a target, no matter what that damage source is.
To test out your numbers, I suggest getting two weapons, leveling them up evenly, then leveling up your damage stat (either Dex or Str) evenly, then having one of them slot your fire gem.  Watch the numbers change with the new scaling.
Comment: That is a lot of new information, thanks! Also, does that mean a combination of: weapon scaled to 250 damage, a fire gem, an oil urn and beast enemy would result in insane damage?
Comment: I have not found a gem that 'adds' fire scaling or lighting scaling to a weapon.  I have only seen ones that change the scaling.  The most damage I can see getting out of something like this would be using a high normal damage weapon, using oil on the target, and then using fire paper.  I could be wrong, but I don't think any gems 'add' fire scaling.
Comment: Oh, I just meant that if weapon with physical damage maxed out would deal the insane damage under those circumstances. I will test the weapons as soon as I get a chance to play, although, i never noticed that huge jump in damage when using fire paper on beasts Thank you for your help. Some of the game's mechanics really are too hard to figure out on my own!

Bolt/Fire Damage stat on weapons


Are PHP Variable Variable Variables possible. $$$a

Question: Php uses variable variables.
So
<code>$a="hello";
$$a="oops";
echo($hello)
</code>
this gives us output:oops
My question is can Variable variables be used for more levels
like is $$$a defined?
will
<code>$a="hello";
$$a="oops";
$$$a="she";
echo($oops);
</code>
give us output?? If yes to what level are variable variables possible?
If no why not????
Comment: If only there was a way to test this yourself...
Comment: @i-lo - The [so] Q&A format is not really geared towards discussions. Here questions must be specific enough to provide concrete answers to a real problem. You could maybe head on over to the [php chat room](http://chat.stackoverflow.com/rooms/11/php) and have a discussion there.
Comment: What did your preliminary tests show?
Answer: Yes, this is fine, and AFAIK they can be nested infinitely.
Please don't use these though, it's very rare that variable variables are a good idea, let alone variable variable variable variable variable variable variable variable variable variable variable variable variable variable variable variable variable variables.
Answer: It appears that the limit is quite high.
<code><?php

$depth = 1;
while (true) {
    echo "// At depth {$depth}\n";

    $prefix    = str_pad('', $depth, '$');
    $statement = "{$prefix}varvar = 'var{$depth}';\n";

    echo $statement;

    eval($statement);
    $depth++;
}
</code>
Only lightly tested.
Answer: You can scope variables to the height of your stack. It is semi-infinite. You can declare variables inside variables until you run out of memory space. Then crazy crazy things will start to happen, and your program might crash (read really likely). Either way this type of scoping is not recommended.