Kendo ui NumericTextBoxFor - Setar valores de inicialização

Question: Como posso definir um valor de inicialização padrão para o campo NumericTextBoxFor do Kendo.
Ex: Meu campo é inicializado em branco. Quero que ele venha com um default definido por mim:
<code>@(Html.Kendo().NumericTextBoxFor(model => model.MinVoltage).Name("MinVoltage").HtmlAttributes(new { style = "width: 6em;font-size:12px;font-weight:normal" }))
@Html.ValidationMessageFor(model => model.MinVoltage)
</code>
O meu model está desta forma:
<code>    [Column("MIN_VOLTAGE")]
    [Required(ErrorMessage = "Campo obrigatório")]
    [Display(ResourceType = typeof(Messages), Name = "MinimuVoltage")]
    [Range(0.1, 99.99, ErrorMessage = "Valores válidos: 0.1 a 99.99 ")]
    public double MinVoltage { get; set; }
</code>

Eu defini um valor de Range, e quero que ele inicie por default com o valor 0.1,
Porém o campo é inicializado sem valor default conforme a imagem acima.
Como posso setar um valor de inicialização default para o campo NumericTextBoxFor?
Answer: Use .Value(0.1) para definir valor padrão.
Para o range use .Min(0.1) e .Max(99.99)
Para configurar o incremento use .Step(0.1)
talvez você tenha que configurar o formato .Format() e caso não consiga com o NumericTextBoxForModel use .NumericTextBox()


How can I solve this recurrence relation: $a_n = 3a_{n-1} + \frac{4^n}{4}$?

Question: How can I solve the following recurrence relation?
$$a_n = 3a_{n-1} + \frac{4^n}{4}$$
I know that $a_n^{(h)} = 3a_{n-1}$ and that the characteristic equation is:
$$r-3 = 0$$ and thus:
$$a_n^{(h)} = \alpha_1(3)^n$$
I am struggling with the particular solution $a_n^{(p)}$.
Comment: What does the superscript in parentheses denote?
Comment: @GFauxPas: h - homogeneous, p - particular
Answer: HINT :
Dividing the both sides by $3^n$ gives
$$\frac{a_n}{3^n}=\frac{a_{n-1}}{3^{n-1}}+\frac{1}{4}\cdot\left(\frac 43\right)^n\iff b_n-b_{n-1}=\frac{1}{4}\cdot\left(\frac 43\right)^n$$
where $b_n=\frac{a_n}{3^n}$.
Answer: You have
$$a_{n} = 3~a_{n-1} + 4^{n-1} \tag{X}$$
and
$$a_{n+1} = 3~a_{n} + 4\cdot 4^{n-1} \tag{Y}$$
Compute $Y - 4X$ and you'll have a basic linear recurrence.
Answer: Consider the generating function for $a_{n}$. The process is the following.
\begin{align}
\sum_{n=0}^{\infty} a_{n+1} \, t^{n} &= 3 \, \sum_{n=0}^{\infty} a_{n} \, t^{n} +  \sum_{n=0}^{\infty} (4t)^{n} \\
\frac{1}{t} \, \sum_{n=1}^{\infty} a_{n} \, t^{n} &= 3 \, A(t) + \frac{1}{1-4t} \\
\frac{1}{t} \left( A(t) - a_{0} \right) &= 3 \, A(t) + \frac{1}{1-4t}
\end{align}
where $A(t) = \sum_{n=0}^{\infty} a_{n} \, t^{n}$, which leads to
\begin{align}
A(t) &= \frac{a_{0}}{1-3t} + \frac{t}{(1-3t)(1-4t)} \\
&= \frac{a_{0}}{1-3t} + \left( \frac{1}{1-4t} - \frac{1}{1-3t}\right) \\
&= \frac{a_{0} - 1}{1-3t} + \frac{1}{1-4t} \\
&= \sum_{n=0}^{\infty} \left((a_{0} - 1) \, 3^{n} + 4^{n}\right) \, t^{n}
\end{align}
and finally
\begin{align}
a_{n} = 3^{n} \, (a_{0} - 1) + 4^{n}.
\end{align}
Answer: Hint. A particular solution is $a_n^{(p)}=4^n$.
Comment: @Julia It works too. Thanks.
Comment: Why not $\alpha 4^n$?
Answer: Use generating functions. Define $A(z) = \sum_{n \ge 0} a_n z^n$, write your recurrence as:
$$
a_{n + 1} = 3 a_n + 4^n
$$
Multiply by $z^n$, add over $n \ge 0$ to get:
$$
\sum_{n \ge 0} a_{n + 1} z^n
  = 3 \sum_{n \ge 0} a_n z^n + \sum_{n \ge 0} 4^n z^n
$$
Recognize some sums:
$$
\frac{A(z) - a_0}{z}
  = 3 A(z) + \frac{1}{1 - 4 z}
$$
Solve for $A(z)$, write as partial fractions:
$\begin{align}
A(z) &= \frac{a_0 - (4 a_0 - 1) z}{1 - 7 z + 12 z^2} \\
     &= \frac{a_0 - 1}{1 - 3 z} + \frac{1}{1 - 4 z}
\end{align}$
This is just two geometric series:
$$a_n = (a_0 - 1) \cdot 3^n + 4^n$$


Prove that the inequality is true

Question: Prove  that  forl  all   positive  real  numbers $x, y, z$ we  have  that $ (x^3 + y^3 + z^3)^2 \geq 3(x^2y^4 + y^2z^4 + z^2x^4)$.  I tried  to  apply  Cebasev, Muirhead but  doesn't work.
Answer: \begin{eqnarray*}
y^3(2x+y)(x-y)^2+z^3(2y+z)(y-z)^2+x^3(2z+x)(z-x)^2 \geq 0
\end{eqnarray*}
Now rearrange.
Answer: Because
$$(x^3+y^3+z^3)^2-3(x^4z^2+y^4x^2+z^4y^2)=$$
$$=\sum_{cyc}(x^6+2x^3y^3-3x^2y^4)=\sum_{cyc}x^2(x^4+2xy^3-3y^4)=$$
$$=\sum_{cyc}x^2(x^4-x^3y+x^3y-x^2y^2+x^2y^2-xy^3+3xy^3-3y^4)=$$
$$=\sum_{cyc}x^2(x-y)(x^3+x^2y+xy^2+3y^3)=$$
$$=\sum_{cyc}\left((x-y)(x^5+x^4y+x^3y^2+3x^2y^3-(x^6-y^6)\right)=$$
$$=\sum_{cyc}(x-y)(2x^2y^3-xy^4-y^5)=\sum_{cyc}y^3(x-y)^2(2x+y)\geq0.$$
Also, there is a proof by Rearrangement and AM-GM, but it's much more complicated.

Prove that the inequality is true


What is the general term for instruments without fixed pitches? Like fretless

Question: There are fretless versions of electric guitars and basses. Instruments in the violin family are (almost) always fretless. But what is the general term for this when expanded for other instruments, like trombones, slide saxophones, theremins and other instruments that do not have fixed pitches?
Comment: @leftaroundabout I think the OP had fretted violin in mind. It is not *almost fretless violin*, but *violins are (almost always) fretless*…
Comment: What's an _almost fretless_ violin? Or, do you mean they're _almost always_ fretless? — A problem with this question is that it's hard to draw a clear line. Sure, piano and organ are 100% fixed-pitch and theremin is 100% continuous-pitch, but most other instruments have some sort of discrete choice built in yet can also perform more or less pronounced pitch bends and require fine-intonation by the player on each note. Striking example: [recorder](https://en.wikipedia.org/wiki/Recorder_(musical_instrument)), which with its holes one might think should be discrete, but really isn't.
Comment: @CarlWitthoft I did not know this instrument before, but this one seems to be capable: https://www.youtube.com/watch?v=POzJoi463UI
Comment: @Kaz You proved that musicians are as nerdy as programmers :D
Comment: The examples instruments given are all of the real contiguous pitch type. Others are imaginable (piano with bend wheel?) which have the normal scale structure, but are capable of bridging the gaps. Shall they be included in the searched term?
Comment: @leftaroundabout  I interpreted that as referring to various antique or oddball families which are bowed and fretted as well --  nyckelharpa ,  Arpeggione , ...
Comment: BTW,  the slide saxophones I'm aware of use the slide to access open holes.  They aren't primarily capable of  continuous portamento
Comment: Violins have one fret: the zeroth fret (nut) which frets the open string for you. So, almost fretless.
Comment: @Kaz I think you're stretching a point (pun intended) to claim that requiring a node at both ends of the string constitutes a fret :-) .   One of the main differences, speaking from a physics point of view, between stringed instruments and wind instruments is that the wind instruments do not have a node at both ends (just essentially one at or near the mouthpiece), whereas  the thought of trying to generate a standing wave with a string that was open-ended.....
Comment: Interesting, I wonder how a violin where the nut was attached using a spring instead would sound. I guess each note would be bent in curious ways...
Answer: I would suggest: continuous pitch instruments.
Comment: @CarlWitthoft would there not be value in grouping such instruments for a composer working on microtonal music?
Comment: @kojiro  Not really, as any wind or string instrument can be "bent" to produce microtones.
Comment: Interesting that it got a Wiki page!   Personally I don't see any value to grouping said instruments, but if it is helpful here and there, why not use it.
Comment: @CarlWitthoft Well, it's a Category page, those are auto-generated on wikis anyhow.
Comment: I'd suggest hyphenating it for clarity: **continuous-pitch instruments**.
Answer: The expression technique of producing a continuous tone while smoothly varying the pitch from one note to another is called portamento.
If we use the term portamento instrument, it's clear we are referring to a variable-pitch instrument that fundamentally supports portamento playing.
Comment: @CarlWitthoft There are tons of counterexamples. Anyone can hit a key on a piano and get a tone. Or blow into a harmonica.  A toddler could blow into a slide whistle while moving the piston to produce a portamento from one pitch to another. That's what makes a slide whistle an example of an instrument which fundamentally supports portamento. You don't have to produce portamento *in spite* of the instrument's limitations; it is designed to produce it.
Comment: But a skilled player can, in fact, perform a portamento on a fretted/keyed instrument like a guitar or trumpet or clarinet. Being able to portamento on a certain instrument doesn't indicate that it doesn't have fixed pitches.
Comment: @NuclearWang I would say that these instruments do not *fundamentally support* portamento. If an instrument fundamentally supports portamento it means that a complete neophyte picking it up for the first time can obtain the effect easily, and that it can be easily applied to all or almost all of the notes of any melody, including large intervals as much as an octave or more.
Comment: @Kaz  a complete neophyte can't produce the correct note or effect on pretty much any instrument.  period.


Windows XP image sysprepped in VirtualBox fails to boot on bare metal

Question: (1) I created a VirtualBox virtual machine and installed then customized a Windows XP SP3 reference system in it.
(2) I ran sysprep to reseal the system for deployment. By restarting the virtual machine directly I saw that sysprep ran as configured and the system was correctly deployed.
(3) However, after using Symantec Ghost 11.5 to make an image of the system and deploying it to a real physical machine, the Windows XP sysprepped system fails to boot. Specifically, the system keep restarting even before the Windows logo shows up.
Is there some difference between a VirtualBox virtual machine and a real bare metal system that I need to account for? And is there a way to salvage my current virtual reference system without having to remake it from scratch on bare metal?
Thanks!!
Comment: Obligatory: [*Why are you still running Windows XP*](http://windows.microsoft.com/en-us/windows/end-support-help)? [Professionals](http://meta.serverfault.com/questions/4111/what-is-a-professional-capacity) generally don't deploy out-of-support software...
Comment: Agreed, windows xp should be being scrubbed from your environment and your hours should be spent on migration considerations, not on deploying an aging and soon to be extremely vulnerable OS.
Comment: I couldn't agree with you more. Unfortunately my organisation's management is mired in red tape and bureaucracy (who don't know anything about IT) that is forcing us to continue to make and deploy new Windows XP images despite our objections..... I wish I know how to change this!! Thanks for your help, though!
Answer: This is likely down to ATA / AHCI support. On the baremetal computer you're attempting to install, open the bios settings dialog and check to see if you can reconfigure SATA to be ATA instead of AHCI.
XP did not ship with AHCI support, nearly every modern computer comes with this feature and the option is generally enabled.


Saving generated Image with Carrierwave - no form, all inside the model

Question: this is a tricky one, I hope someone can help me.
I have a article_set, which has many set_items, each set item has an image.
I want to create an collage of the images, so one image out of many, and save it with carrierwave.
that's whats going on in my model:
require 'RMagick'

class ArticleSet < ActiveRecord::Base

    # ...

    after_create :create_collage
    mount_uploader :blog_image, BlogImageUploader

    def create_collage
      # load the template
      template = Magick::Image.read("#{RAILS_ROOT}/public/images/set_template.png").first

      # go through all set items by z_index and add lay it over the template
      for item in self.set_items
        photo = Magick::Image.read(item.product.assets.first.image.url(:thumb).to_s).first
        photo.scale(item.width, item.height)
        # composite item over template offsetting pos_x and pos_y for the template border
        template.composite!(photo, item.pos_x, item.pos_y, Magick::OverCompositeOp)
      end

      # save composite image to JPG
      template.write("set_#{self.id}_#{Time.now.to_i}.jpg")

      #save and upload to s3

      self.blog_image.store!(template)
      self.blog_image = self.blog_image.store_path
      self.write_carrierwave_identifier
      self.save

    end

end

So far, so good. I can save the set and it runs though this method, but I guess the last part
       #save and upload to s3

      self.blog_image.store!(template)
      self.blog_image = self.blog_image.store_path
      self.write_carrierwave_identifier
      self.save

is probably incorrect, in my database I get only NULL values for blog_image.
It should, of course, contain the file name of the generated file...
any help highly appreciated.
thanks
Answer: That 3rd last line looks a bit dodgy:
self.blog_image = self.blog_image.store_path

If you remove that i'm fairly sure it should work.
Comment: Hi Mario, thanks for your answer. The problem was actually in the carrierwave uploader configuration, where it was still set to :s3 instead of :fog, but you are right, that this line is unnecessary and ahs to be deleted. so i am gonna accept your answer! cheers


How to factor intricate polynomial $ ab^3 - a^3b + a^3c -ac^3 +bc^3 - b^3c $

Question: I would like to know how to factor the following polynomial.
$$ ab^3 - a^3b + a^3c -ac^3 +bc^3 - b^3c $$
What is the method I should use to factor it? If anyone could help.. Thanks in advance.
Comment: Try $b=a$ and...
Comment: Why do you call this a polynomial?  Is it a polynomial in the three variables $a,b,c$?  To see mathlove's point, think of it as a polynomial in the single variable $a$, with $b,c$ constants.  Notice that polynomial has a root $b$.
Answer: $ab^3 - a^3b + a^3c -ac^3 +bc^3 - b^3c =$
$ab^3 - a^3b + a^3c -b^3c -ac^3 + bc^3=$
$ab(b^2-a^2)+c(a^3-b^3)-c^3(a-b)=$
$ab(a+b)(b-a)+c(a-b)(a^2+ab+b^2)-c^3(a-b)=$
$(a-b)[-ab(a+b)+c(a^2+ab+b^2)-c^3]=$
$(a-b)(-a^2b-ab^2+ca^2+cab+cb^2-c^3)=$
$(a-b)(ca^2-a^2b+cab-ab^2+cb^2-c^3)=$
$(a-b)[a^2(c-b)+ab(c-b)+c(b^2-c^2)]= $
$(a-b)(c-b)[a^2+ab-c(b+c)]=$
$(a-b)(c-b)(a^2+ab-bc-c^2)=$
$(a-b)(c-b)(a^2-c^2+ab-bc)=$
$(a-b)(c-b)[(a-c)(a+c)+b(a-c)]=$
$(a-b)(c-b)(a-c)(a+b+c)$
The suggestion of replacing $b$ with $a$ was the following: if in such an expression when you replace $b$ with $a$ you get a $0$ then one of the factors may be $(a-b)$.
In the future if you want an idea of the factors that appear you could write on wolframalpha factor$(ab^3 - a^3b + a^3c -ac^3 +bc^3 - b^3c)$
Answer: \begin{align*}
ab^3 - a^3b + a^3c -ac^3 +bc^3 - b^3c&=-a^3(b-c)+b^3(a-c)+c^3(b-a)\\
&=-a^3(b-c)+b^3(a-c)+c^3[(b-c)+(c-a)]\\
&=(c^3-a^3)(b-c)+(b^3-c^3)(a-c)\\
&=(c-a)(c^2+ac+a^2)(b-c)+(b-c)(b^2+bc+c^2)(a-c)\\
&=(a-c)(b-c)(-c^2-ac-a^2+b^2+bc+c^2)\\
&=(a-c)(b-c)(b^2+bc-ac-a^2)\\
&=(a-c)(b-c)[(b+a)(b-a)+c(b-a)]\\
&=(a-c)(b-c)(b-a)(a+b+c)\\
&=(a-b)(b-c)(c-a)(a+b+c)\\
\end{align*}
Comment: You can continue - $b^2-a^2+bc-ac=(b-a)[a+b+c]$.
Answer: Let
$$
f(a)=ab^3-a^3b+a^3c-ac^3+bc^3-b^3c.
$$
If $a=b$, then $f(a)=0$. Therefore $(a-b)\mid f(a)$. Analogously $(a-c)\mid f(a)$; so, $(a-b)(a-c)\mid f(a)$. But we can take it directly:
$$
ab^3-a^3b+a^3c-ac^3+bc^3-b^3c = ab(b^2-a^2) + c^3(b-a) - c(b^3-a^3) =\\=
ab(b-a)(b+a)+c^3(b-a)-c(b-a)(b^2+ba+a^2) =\\= (b-a)[ab(b+a)+c^3-cb^2-cab-ca^2]
$$
$$
ab(b+a)+c^3-cb^2-cab-ca^2=ab(a+b) + c(c^2-a^2) - cb(a+b) =\\= (a-c)b(a+b) - c(a-c)(a+c)=(a-c)[b(a+b)-c(a+c)]
$$
And then
$$
b(a+b)-c(a+c) = ba+b^2 - ca - c^2 = a(b-c) + (b^2-c^2) =\\= a(b-c)+(b+c)(b-c)=(b-c)(a+b+c).
$$
So,
$$
ab^3-a^3b+a^3c-ac^3+bc^3-b^3c=(b-a)(a-c)(b-c)(a+b+c)
$$


Setting up Eclipse with JRE Path

Question: I have downloaded and extracted Eclipse. I have Eclipse in the following directory: C:\Applications\eclipse. When I try and run the executable , I get the following message :

I currently have the following folder:
C:\Program Files (x86)\Java\jre7

Do I need to set up some environment variables for my Windows 7 OS to get Eclipse to run ? If so , may I please have some help to do this ? If not , can I please have some help to get Eclipse to run .
EDIT
I have changed the shortcut to include the path to the Virtual Machine , and am now getting this error :
http://www.canning.co.nz/Eclipse/Eclipse_Message2.png
Comment: possible duplicate of [Eclipse - no Java (JRE) / (JDK) ... no virtual machine](http://stackoverflow.com/questions/2030434/eclipse-no-java-jre-jdk-no-virtual-machine)
Answer: You can add this line to eclipse.ini :
-vm
D:/work/Java/jdk1.6.0_13/bin/javaw.exe  <-- change to your JDK actual path
-vmargs <-- needs to be after -vm <path>

But it's worth setting JAVA_HOME and JRE_HOME anyway because it may not work as if the path environment points to a different java version.
Because the next one to complain will be Maven, etc.
Comment: One point to add - ensure that the java Path is put in a separate line. Don't  put "-vm" and the path in same line.
Comment: Note that you can't wrap the path in quotes when it contains spaces. If it contains spaces, put the whole path into one line as in the example!
Comment: If you change it in the .ini file, and it still doesn't work, check the shortcut or menu item properties, where it might need to be updated, like:  C:\birt_232\eclipse\eclipse.exe -vm "C:\Program Files (x86)\Java\jre1.8.0_60\bin" -vmargs -Xmx512m (or whatever your path is).
Answer: Add this to eclipse.ini:
-vm
your_java_path\bin\javaw.exe

...but be aware that you must add these lines before -vmargs
Answer: I have several version of JDK (not JRE) instaled and I launch Eclipse with:
C:\eclipse\eclipse.exe -vm "%JAVA_HOME%\bin\javaw.exe" -data f:\dev\java\2013

As you can see, I set JAVA_HOME to point to the version of JDK I want to use.
I NEVER add javaw.exe in the PATH.
-data is used to choose a workspace for a particular job/client/context.
Answer: Add the following   -vm D:/Java/jdk1.6.0_30/bin/javaw.exe in the begin of eclipse.ini like this :
-vm
  D:/Java/jdk1.6.0_30/bin/javaw.exe
  -startup
  plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
  --launcher.library
  plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
  -product
   org.eclipse.epp.package.jee.product
   --launcher.defaultAction
   openFile
   --launcher.XXMaxPermSize
   1024M
   -showsplash
   org.eclipse.platform
    --launcher.XXMaxPermSize
   1024m
    --launcher.defaultAction
   openFile
   --launcher.appendVmargs
   -vmargs
   -Dosgi.requiredJavaVersion=1.6
   -Xms1024m
   -Xmx2048m

Comment: This answer is what worked for me. Need the `-vm` args at the top of `eclipse.ini`.
Answer: This may sound dumb, but it may be a fresh, or damaged install, so is the JDK installed? If not, go to the download site and download the latest version of Java JRE. Like I said, this may sound dumb, but it solved my problem.
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Answer: You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):
-vm
C:\Java\JDK\1.8\bin\javaw.exe

or wherever your javaw.exe happens to be.
Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right
Answer: Add the following to the eclipse.ini :
-vm

Java_Home_Variable\bin\javaw.exe

In my Case its

-vm

H:\usr\java\jdk1.6.0_16\bin\javaw.exe

Comment: Yes! My eclipse.ini had the -vm option set to a path that had the old JRE. It looks like the Java installer provides a `C:\ProgramData\Oracle\Java\javapath` directory with links to the current JRE programs.
Answer: I had the same issue caused by two things:

I had downloaded a 32bit Java version instead of 64bit.
The eclipse.ini did not have path to javaw.exe, so as per prior posts added the statement which points to the location java.

So after I uninstalled the 32 bit Java 1.7, installed the correct one and added the javaw.exe path, eclipse fired up with no more errors
Answer: You are most probably missing PATH entries in your windows. Follow this instruction : How do I set or change the PATH system variable?
Answer: I just copied the jre folder to whatever path the message tells me it was missing at, and solved it.
(after editing the JAVA_HOME and editing the eclipse.ini didn't worked (as i probably did something wrong)) (i have no other java applications running so it's not affecting me)
Answer: If you are using windows 8 or later:

download and install the jdk or jre with all the default settings and options.
Then download and install eclipse.

Everything should work fine. I don't know if it works exactly the same for other OS, but you don't have to set the PATH manually in Windows 8 or later.
Answer: Java version used : 1.8
IDE : Eclipse Neon
Adding like the below didn't work for me

-vm
    [relative java home]/jdk1.8.0_21/bin/javaw.exe

and then when i removed

javaw.exe

it worked, so it will be like

-vm
    [relative java home]/jdk1.8.0_21/bin/

Setting up Eclipse with JRE Path


Google Cloud Endpoints + GoogleApiClient in Android without GET_ACCOUNTS permission

Question: Is there any way to have authenticated Google Endpoints in an android app using GoogleApiClient without being forced to have GET_ACCOUNTS permission?
Android 23+ with new runtime permissions will then ask the user for the undesirable READ_CONTACTS permission. It seems strange that all android apps with Google Endpoints would now require READ_CONTACTS permission.
The closest StackOverflow question I can find is this, but it claims that it may only work for a very limited time.  This Google post provides some guidance using tokens, but not for Endpoints.
Comment: If you check the Google Document, the only way is by using the ACCOUNTS permission. In supporting request to an Endpoint that requires authentication, your Android client needs to get user credentials and pass them to the service object.

Check this [page](https://cloud.google.com/appengine/docs/java/endpoints/consume_android) for more info.

Also before your game can make any calls to the Google Play games services, it must first establish an asynchronous connection with the Google Play servers by using an GoogleApiClient object and authenticating the user with the Google Play games services.
Comment: When you say "Google Endpoints" what do you mean?  For example you can call Game Services APIs without this permission (no additional permissions are required).
Comment: @aez - Can you reference where it says you need GET_ACCOUNTS?  READ_CONTACTS is only needed if you are reading the contacts or getting the contact information for the current user.
Comment: @KENdi - Yes, requiring GET_ACCOUNTS permission is the problem. Android Marshmallow and above (23+) which groups GET_ACCOUNTS with the READ_CONTACTS (@Clayton see [this](http://developer.android.com/guide/topics/security/permissions.html#normal-dangerous)) permission will then require, at runtime, permission from the user for READ_CONTACTS.  This means to me that any Marshmallow or above android app using Google Endpoints will require READ_CONTACTS permission at runtime.
Comment: I think the proper name is "Google Cloud Endpoints", described [here](https://cloud.google.com/appengine/docs/java/endpoints/).  And if you use authenticated Google Cloud Endpoints, you must use GET_ACCOUNTS.  So, yes, I can use Game Services APIs, but if I use an authenticated Google Cloud Endpoints backend, I have the permission problem.
Answer: I finnaly found the solution. I updated the answer on the question you mentioned.

To avoid the 1 hour token limitation, use
  GoogleSignInApi.silentSignIn() to get a new token before every
  call you make to your endpoint. For example if you are not in the UI
  thread:

<code>GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail()
                .requestIdToken(CLIENT_ID)
                .build();
GoogleSignInClient client = GoogleSignIn.getClient(context, options);
GoogleSignInAccount user = Tasks.await(getGoogleSignInClient(context).silentSignIn());

// Use the new user token as before
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
        .setJsonFactory(JacksonFactory.getDefaultInstance())
        .build();
credential.setAccessToken(user.getIdToken());
</code>


"Lower score than you actually shot will disqualify you" in Golf? What does this mean?

Question: This answer here mentions this rule:

"Lower score than you actually shot will disqualify you".

I have friends who boost by their 20, 30 and 40 handicaps but their performance with me is far poorer such as in the range of 50 -- so 10-30 shots poorer than they are supposed to be. I cannot understand this: it is not motivational particularly when they become angry to unrelated things such as other golfers.

When a golfer gets a far worse result than their handicap, what should happen to their handicap?

Does it get lower and what does the disqualification mean?
Answer:
When a golfer gets a far worse result than their handicap, what should
  happen to their handicap?

His handicap should increase.
The handicap is calculated by taking a golfer's score for the past ten rounds, calculate an average score, and depending on what par is, subtract the average score by par and there's your handicap. The term "scratch golfer" is given to those who average par or better over ten rounds.
For example, here are the last ten example rounds for an example golfer:
92-92-92-92-92-92-92-92-92-92 = 920. 920/10 = 92.
If par is 72, then 92-72 = 20. This golfer would have a 20 handicap.
Now, assume this golfer's next round was a 112 (ie, "When a golfer gets a far worse result than their handicap"), then:
92-92-92-92-92-92-92-92-92-112 = 940. 940/10 = 94.
If par is 72, then 94-72 = 22. This golfer would now have a 22 handicap.

Does it get lower?

As shown above, no.

What does the disqualification mean?

I believe your interpretation of the statement in context is misconstrued.
For example, if you shot a 90 but write down that you shot an 89, then you would be disqualified (given you're playing in a sanctioned tournament) for submitting a scorecard with a lower score than actually shot. If you write down that you shot a 91, the 91 would stand as signed.
Rule 6.6d of the USGA Rules of Golf and the R&A Rules of Golf addresses this (verbiage from the USGA Rules of Golf):

d. Wrong Score for Hole
The competitor is responsible for the correctness of the score
  recorded for each hole on his score card. If he returns a score for
  any hole lower than actually taken, he is disqualified. If he returns
  a score for any hole higher than actually taken, the score as returned
  stands.
Answer: The phrase means that if you record a "lower" (better) score than you actually shot, that will disqualify you from the tournament, because it is really a form of cheating.
Maybe there are some tournaments that will disqualify people for recording "higher" (worse) scores, because of "inaccuracy," and its implication for future handicapping, but in general, a wrong record one way is viewed much more dimly than a wrong record the other way.


change the alert error position

Question: Build a form Contact us by EMAIL me form I uploaded it to my server, and I want to change the CSS file the error location (when you click on the submit button, then all fields not filled properly marked an error - red) My question is simple: How do I can change the CSS file so that the error diaphragm on the left and not on the right? Thank you!
The form is in this link: http://lawb.co.il/HTMLPage.html
the CSS file is in this link: http://lawb.co.il/contact_us.css
You can see example for what I want here:
insted of this

Is is possible?
Answer: Add promptPosition:"topLeft" in contact.js:
EMF_jQuery("#emf-form").validationEngine({
                validationEventTriggers:"blur",
                scroll:true,
                promptPosition: "topLeft"
        });

And these lines in CSS:
   .formError {
   ...
   left: 360px !important;
   ...
   }

   .formError .formErrorContent {
   ...
   width: 310px !important;
   ...
   }

   formError .formErrorArrow {
   ...
   left: 70%;
   ...
   }

It should work.
Comment: thank you! It is work..But only partially

If you clik on the again link you can see I changed the script code, from what you said, but still ... The text itself does not move to the left, how can I move the text only, to the left?
Comment: Which text do you refer to?
If you mean the label text, then use this:
`#emf-container li label.emf-label-desc {
font-weight: bold;
padding-right: 2px;
padding-bottom: 5px;
display: block;
text-align: left;
}`
Comment: I mean to the text in the red alrt, I want that the alert will be in the Left side..
Comment: Try to add `text-align: left;` to the CSS rule **.formError .formErrorContent**
Comment: thank you! I upload an example, I mean to what that there is in the example, can you tell me how can I fix it?
Comment: I uploaded an example, can you Fix it so waht that there is in the image will be in the CSS or JS code?
Comment: thank you a lot!! you realy helps me! just one more quastion: I uploaded the fixed form (you can see it) thare is an option that all the error messages will be streight to the right side (insted to the left)? that all the messeges will be in Vertically Solid and straight line to the right(now it is to the left)? hope you understand me..
Comment: Sorry, i can't test it so i just guess every time... Edited my answer again, please try it and let me know
Comment: here is live example, with editable code, you can try hrer http://jsfiddle.net/TCpkb/ thanks
Comment: Edited again, going back to CSS. Please switch back to the original version of your form and make the changes above :)
Comment: much more betrer! thank you!
Is there an option that the red or the orange alert box will be thight to the text?
Comment: I'm not sure it's what you mean, but try to replace `padding: 4px 10px 4px 10px;` to `padding:2px;` in the _.formError .formErrorContent_ css rule
Comment: here is a picture for what I mean. pleas you are almost thhre! keep help me pleas! https://www.dropbox.com/s/hpqb863dvc6nn6w/%D7%9C%D7%9B%D7%99%D7%93%D7%94%20%282%29.PNG
Comment: I can see what you mean... Sorry but if you remove these parts, everything will lose it's position, and go back as it was before my last edit :(
Comment: so there is no way to fix it?
Comment: Sure there can be a way: calculate the width of each error message, any time it's displayed, and then adjust the left position. I don't really think it's worth the effort ;)
Comment: Try with [jQuery validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
Answer: try this
            align:left;

or
            float:left;

change the alert error position


How can I verify the percentage?

Question: cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
x = cars.count("coupe")
y = len(cars)

Q: If the number of times the coupe element appears in the tuple cars is more than 45%, print "Too many." to the terminal. If not, print "You are set."
that means
if x/y > 45%;     I will have to print "Too many" else "You are set".
But I can't run it in the python program.
Can anybody please help?
Answer: You already close to find out, just use if statement to check percentage.
You can do that as follows:
cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
x = cars.count("coupe")
y = len(cars)

stat = 0.45 # %45
if x/y > stat:
 print("Too many")
else:
 print("You are set")

Comment: This seems to be the best answer
Answer: 45% is the same as 45/100, that is, 0.45. So you could write:
>>> cars = ('coupe', 'coupe', 'coupe', 'carbiolet', 'sedan')
>>> x = cars.count("coupe")
>>> y = len(cars)
>>> x
3
>>> y
5
>>> threshold = 0.45 # 45% or you could also write 'threshold = 45/100'
>>> if x/y > threshold:
...     print("Too many")
... else:
...     print("You are set")
...
Too many

How can I verify the percentage?


Intelligent Merge of two Arrays (3-way-kindof)

Question: I have two Arrays, each represents a list of Stories. Two users can concurrently modify the order, add or remove Stories, and I want those changes merged.
An example should make this clearer
Original       1,2,3,4,5
UserA (mine)   3,1,2,4,5 (moved story 3 to start)
UserB (theirs) 1,2,3,5,4 (moved story 5 forward)

The result of the above should be
Merge (result) 3,1,2,5,4

In case of conflicts, UserA should always win.
I came pretty far with this simple approach. First i deleted whatever mine says i should deleted (that part of the code is not shown, it's trivial), then I iterate over mine, inserting and moving from theirs what is needed (mstories = mine, tstories = theirs):
     for (var idx=0;idx<mstories.length;idx++) {
        var storyId = mstories[idx];

        // new story by theirs
        if (tstories[idx] !== undefined && mstories.indexOf(tstories[idx]) == -1) {
           mstories.splice(idx+1, 0, tstories[idx]);
           idx--;
           continue;
        }
        // new story by mine
        if (tstories.indexOf(storyId) == -1 && ostories.indexOf(storyId) == -1) {
           tstories.splice(idx+offset, 0, storyId);
           offset += 1;
        // story moved by me
        } else if ((tstories.indexOf(storyId) != idx + offset) && ostories.indexOf(storyId) != idx) {
           tstories.splice(tstories.indexOf(storyId), 1);
           tstories.splice(idx+offset, 0, storyId);
        // story moved by them
        } else if (tstories.indexOf(storyId) != idx + offset) {
           mstories.splice(mstories.indexOf(storyId), 1);
           mstories.splice(idx+offset, 0, storyId);
           mdebug(storyId, 'S moved by them, moffset--');
        }
     }
     result = tstories

It's close, but it gets confused when too many Stories are moved to the front / back with Stories in between, which the other User touched.
I have an extended version which does checks on the original and is smarter - holding 2 offsets, etc - , but I feel like this is a problem that must have a) a name b) a perfect solution and i don't want to re-invent it.
Comment: Checkout Operational Transformation that is commonly used for for concurrency control in collaborative systems. Google Wave heavily uses it for keeping documents synchronized. http://www.waveprotocol.org/whitepapers/operational-transform, Wikipedia - http://en.wikipedia.org/wiki/Operational_transformation
Comment: indeed OT helped me. the solution was to extract the set of operations (move, insert, delete) for both changes, then transform one of the changes (basically the offsets) to be applicable after the other .. then apply both.

i now doubt that this can be written understandably in one loop as i tried.
Comment: Interesting problem! I would very much like to see the solution for it. I tried at it for a bit with no luck, maybe I'll try again when I don't have a headache.
Answer: Here's a function that iterates over the supplied arrays and lets another function decide how to merge at a given index.  (see Strategy Pattern)
// params:
//   original, a, b: equally dimensioned arrays
//   mergeStrategy : function with params _original, _a, _b that
//                   accept the values inhabiting the arrays
//                   original, a, and b resp.
//
//                  - Is called for each array index.
//                  - Should return one of the arguments passed.
//                  - May throw "conflict" exception.
// returns merged array

function merge(original, a, b, mergeStrategy){
    var result=[];

    for ( var i =0; i< a.length; i++ )  {
        try {
            result.push( mergeStrategy( original[i], a[i], b[i] ));
        } catch (e if e=="conflict") {
            throw ("conflict at index "+i);
        }
    }
    return result;
}

And here are some usage examples ... yours:
// example:  always choose a over b
function aWins( original, a, b ) {
    return ( original == a ) ? b : a;
}

// returns [3,1,2,5,4]
merge(
    [1,2,3,4,5],
    [3,1,2,4,5],
    [1,2,3,5,4], aWins);

... and one that throws an exception upon conflict:
function complain( original, a, b ) {
    if (original == a )
        return b;

    if (original == b )
        return a;

    if ( a == b )
        return a;

    throw ("conflict");
}

// throws "conflict at index 3"
merge(
    [1,2,3,4,5],
    [3,1,2,1,5],
    [1,2,3,5,4], complain);


Find the volume of the solid in the first octant bounded by the three surfaces $z = 1-y^2$, $y=2x$, and $x=3$

Question: I want to find the volume of the solid in the first octant bounded by the three surfaces $z = 1-y^2$, $y=2x$, and $x=3$. It seems that would simply be to calculate the following triple integral:
$\int_0^3 \int_0^{2x} \int_0^{1-y^2} z\,dz\,dy\,dx$
This is pretty straight-forward to do without any variable substitutions etc. which makes me think it's almost too simple (for a home assignment).
Am I missing something or is the above correct?
Comment: *Hint*: What is $1-y^2-\varepsilon$ when $y=2x-\varepsilon$ when $x=1$ ($\varepsilon>0$ a small number)?  Is it positive?
Comment: For the first surface $z = 1-y^2$ changes sign at $y = 1$ which is when $x=\frac{1}{2}$ but I'm not sure how that information factors in when doing iterated integration…?
Comment: The easiest "fix" is to change the upper limit of $y$-integral to $\min(2x,1)$, or stick an indicator function into the integrand to kill off these unnecessary parts.
Comment: After integrating over z and y I then end up with the integral $\int_0^3 \left(\frac{1}{2}(\min(2x, 1)) - \frac{1}{3}(\min(2x, 1))^3 + \frac{1}{10}(\min(2x, 1))^5\right) dx$. With these limits, will $\min(2x, 1)$ not always be 1?
Comment: Hmm... why is there a $z$ in the (original) integrand?
Comment: My thinking was that $z$ is the function I need to integrate since no function is given, is that incorrect? Is using the function 1 the correct way to do it? Another idea was to integrate $1-y^2$ as a double integral.
Comment: You should be integrating the function 1 over the region to get the volume.
Answer: It's always a good idea to try and figure out how your shape looks, this helps with setting up the right integral bounds.

Note that calculating the volume using an integral can be written as:
$$ \int_{V}dV = \iiint 1\,dx\,dy\,dz$$
or
$$ \int_{A}f(A)\,dA = \iint f(x,y)\,dx\,dy$$
So using $\iiint z\,dz\,dy\,dx$ is not how you calculated the volume.
The volume bounded by these surfaces could be calculated as:
$$\int_{0}^{1}\int_{y/2}^{3}\int_{0}^{1-y^2} 1\,dz\,dx\,dy = \int_{0}^{1}\int_{y/2}^{3}{1-y^2 \,dx\,dy}   $$
Note that if you want to integrate $x$ at the end, you should split up the integrals as such:
$$\int_{0}^{0.5}{\int_{0}^{2x} 1-y^2}\,dy\,dx + \int_{0.5}^{3}{\int_{0}^{1} 1-y^2}\,dy\,dx$$
Answer: I ended up doing the following (omitting some algebra steps):
$1 - y^2 \geq 0$ when $y \leq 1$ which gives an integration interval $0 \leq y \leq 1$. By dividing the integral into two parts with the intervals $0 \leq x \leq \frac{1}{2}$ and $\frac{1}{2} \leq x \leq 3$ we get the two simpler integrals:
$V =
V_1 + V_2 =
\int_0^{1/2} \int_0^{2x} \int_0^{1-y^2} dz\,dy\,dx +
\int_{1/2}^3 \int_0^1 \int_0^{1-y^2} dz\,dy\,dx$
$V_1 = \int_0^{1/2} \int_0^{2x} \int_0^{1-y^2} dz\,dy\,dx =
\int_0^{1/2} \int_0^{2x} (1-y^2)\,dy\,dx =
\int_0^{1/2} \left(2x - \frac{8}{3}x^3\right) dx =
\frac{5}{24}$
$V_2 = \int_{1/2}^3 \int_0^1 \int_0^{1-y^2} dz\,dy\,dx =
\int_{1/2}^3 \int_0^1 (1-y^2) dy\,dx =
\int_{1/2}^3 \frac{2}{3} dx =
\frac{5}{3}$
$V = V_1 + V_2 = \frac{5}{24} + \frac{5}{3} = \frac{15}{8}$
Makes sense? Thank you for the comments.


How do you put a Func in a C# attribute (annotation)?

Question: I have a C# annotation which is :
[AttributeUsage(AttributeTargets.Method)]
public class OperationInfo : System.Attribute {
    public enum VisibilityType {
        GLOBAL,
        LOCAL,
        PRIVATE
    }
    public VisibilityType Visibility { get; set; }
    public string Title { get; set; }
    public Func<List<string>, List<string>> Func;

    public OperationInfo(VisibilityType visibility, string title, Func<List<string>, List<string>> function) {
        Visibility = visibility;
        Title = title;
        Func = function;
    }
}

As you can see, there is a property which is a Func and I want to call it dynamically. Basically, I'd like to parse all the methods which have this annotation and then call the Func binded to the annotation.
I'd like to use it like this (this is a simple example of an echo function, which gets a string and return the same string):
[OperationInfo(OperationInfo.VisibilityType.GLOBAL, "echo", IDoEcho)]
    public static string DoEcho(string a)
    {
        return a;
    }

    [OperationInfo(OperationInfo.VisibilityType.PRIVATE, null, null)]
    public static List<string> IDoEcho(List<string> param) {
        return new List<string>() { DoEcho(param[0]) };
    }

I've got no error in my Annotation class but when it comes to regenerate the entire solution, each time I declare a method with the annotation I've got an error which tells me that I must use literals in an annotation.
I understand there is limitations, but is there any way I can avoid this problem? I know I can use a string instead of a Func, and look dynamically for the function whose name is the same as the string, but I would like not to do so.
Thanks for helping :)
Comment: It might not look pretty, but you will often find strings as arguments to attributes because the values must be known at compile time.
Answer: I don't think it is possible, c# only allows you to use Attributes with constant values only.
One way of doing this would be to create a class instead of a func, and then you pass the type of that class into the attribute.
You'd then need to instantiate it with reflection and execute a method in it.
So an example would be:
public interface IDoStuff
{
    IList<string> Execute();
}

then your attribute would take a type instead of a Func
public OperationInfo(VisibilityType v, string title, Type type)
{
   ///...
}

you then would create a class that implements your interface and pass it into the attribute. Although this would mean that (at least initially, and without knowing your problem) you will need to create a new class every time you want to return different results.
Answer: From the C# spec:

17.1.3 Attribute parameter types
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
·         One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
·         The type object.
·         The type System.Type.
·         An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (§17.2).
·         Single-dimensional arrays of the above types.
Answer: So, I was working on some custom authentication today and came across this issue myself, so I figured it might help to add my solution in case this helps anyone. What I was specifically aiming to do was to have three Func<,> structured as:
Func<HttpContext, T?> First;
Func<T?, T?> Second;
Func<T?, bool> Third;

Where the first function extracts (for example) various request headers from the context, the second processes those headers through a security mechanism and then the third tests the output of the second function for validity.
My solution to the problem was to pass two type parameters to the attribute class:
AuthorizationAttribute<T, Tobj> : Attribute, IAuthorizationFilter where T : class, IAuthorisationTransformers<Tobj>, new()
{
    Func<HttpContext, T?> First;
    Func<T?, T?> Second;
    Func<T?, bool> Third;

    public AuthorizationAttribute()
    {
        T Transformers = new T();
        First = Transformers.First;
        Second = Transformers.Second;
        Third = Transformers.Third;
    }

}

Create an interface which contains the methods that the Attribute requires:
public interface IAuthorisationTransformers<T>
{
    public T? First(HttpContext context);

    public T? Second(T? WorkingValue);

    public bool Third(T? WorkingValue);
}

And then create a new concrete implementation of the interface from within my production code:
internal sealed class ControllerTransformers : IAuthorisationTransformers<string>
{
    public string? First(HttpContext context)
    {
        throw new NotImplementedException();
    }

    public string? Second(string? WorkingValue)
    {
        throw new NotImplementedException();
    }

    public bool Third(string? WorkingValue)
    {
        throw new NotImplementedException();
    }
}

This effectively allows me to have different authorisation procedures for each controller, using the same attribute but passing a different class type.


Why the query doesn't match the DOM?

Question: Here is my code:
$res = file_get_contents("http://www.lenzor.com/photo/search/index/type/user/%D8%B9%D9%84%DB%8C//text/%D9%81%D8%A7%D8%B7%D9%85%D9%87");

$doc = new \DOMDocument();
@$doc->loadHTMLFile($res);
$xpath = new \DOMXpath($doc);
$links = $xpath->query("//ul[@class='user_box']/li");
$result = array();
if (!is_null($links)) {
    foreach ($links as $link) {
        $href = $link->getAttribute('class');
        $result[] = [$href];
    }
}

print_r($result);

Here is the content I'm working on. I mean it's the result of echo $res.

Ok well, the result of my code is an empty array. So $links is empty and that foreach won't be executed. Why? Why //ul[@class='user_box']/li query doesn't match the DOM ?
Expected result is an array contains the class attribute of lis.
Comment: array of `li`'s means `followers_content` ?
Comment: @SahilGulati Yes .. however it's just an example. I want to see a working version of the code.
Comment: `loadHTMLFile` loads __FILE__
Comment: @u_mulder what function should I use to load a HTML content?
Comment: You know, there's a manual. You can read it.
Comment: Second, `@class='user_box'` finds items where class is `user_box`. It __will__ skip items with several classes.
Comment: @u_mulder Ok, I found [`loadHTML`](http://php.net/manual/de/domdocument.loadhtml.php). Thank you. And for your second note, can I use `@id='users_search'` ?
Comment: https://stackoverflow.com/questions/10551717/xpath-get-html-element-if-its-class-contains-some-text https://stackoverflow.com/questions/1390568/how-can-i-match-on-an-attribute-that-contains-a-certain-string
Answer: Try this, Hope this will be helpful. There are few mistakes in your code.

1. You should search like this '//ul[@class="user_box clearfix"]/li' because class="user_box clearfix" class attribute of that HTML source contains two classes.
2. You should use loadHTMLinstead of loadHTMLFile.

<?php
ini_set('display_errors', 1);

libxml_use_internal_errors(true);
$res = file_get_contents("http://www.lenzor.com/photo/search/index/type/user/%D8%B9%D9%84%DB%8C//text/%D9%81%D8%A7%D8%B7%D9%85%D9%87");

$doc = new \DOMDocument();
$doc->loadHTML($res);
$xpath = new \DOMXpath($doc);
$links = $xpath->query('//ul[@class="user_box clearfix"]/li');
$result = array();
if (!is_null($links)) {
    foreach ($links as $link) {
        $href = $link->getAttribute('class');
        $result[] = [$href];
    }
}

print_r($result);

Why the query doesn't match the DOM?


Cannot access server shares via VPN

Question: I have set up a my server to accept VPN connections. My users primarily use VPN to access the server shares files.  Everything was working fine until one day I was doing some work on the file system and all of a sudden all of my users cannot access the server shares.
I know the VPN connection is OK because I can ping several devices on the remote network through the VPN connection. Local users are not having any problems accessing the server shares locally.
Whenever I try to access the server shares through the VPN I get an error message:

The folder you entered does not appear to be valid.  Please choose another.

The path I am using is:
\\pbpmwinserver01\server shares

Obviously I have messed up something but I am not sure what I did.  I am thinking it is some sort of group permissions problem but I have checked and all seems OK as well as I understand the correct profiles.
How can I go about debugging the problem further?
Comment: You neglect to mention what you're using as a VPN termination point.
Comment: Do you have webdav sharE ?
Comment: How many subnets do you have on your network? We had a similar problem when we added a new subnet to our network.
Comment: Can you ping the hostname? Is your vpn client seeing the domain?
Comment: Do you really have a blank in the share name?
Comment: Try to browse the share of the server by going to `\\server`
Comment: Is the VPN server the same as the file server? Are they on the same network? Do you have any firewalls in place? Do you have any routing rules in place that would prevent remote devices from communicating with this server? Are remote devices able to access any other local resources on the network?  Can you access the server pbpmwinserver01 in any way (if so, what service/protocol)?  Assuming the file server is a Windows Server, can you access the root share (C$, D$, E$, etc..), using local/domain admin credentials?
Answer: There could be a firewall rule on the file server that restricts access based on IP. I'm assuming that your VPN clients are assigned a different IP than your internal clients. You should check the scope definition for the File & Print Services (SMB-IN) rule if you're using Windows 2008 or 2008 R2 on the file server.
Comment: I am using Windows Server 2008 R2 as my VPN termination point.  When I remotely desktop connection into the server I can see that the VPN client connection is successful.  I am using statically assigned ip addresses for VPN clients.  I checked my server share properties and everything looks ok.  I checked the firewall properties and they are ok too.  I turned off the firewall but still could not accessedmthe shared files.  The error I get is "Windows cannot access "\\pbpmwinserver01\server shares" In the details I get "Error code 0x80070035, The networkd path was not found".
Answer: Verify that the local firewall or antivirus software is not blocking the connection. Disable Norton or McAfee to see if you can connect to the share.
Answer: Here are some suggestions that may help debugging the problem:

Check if it works if you enclose the path in quotes "\\pbpmwinserver01\server shares"
Check that the share it is accessing is "\\pbpmwinserver01\server" (without quotes).
If the share paths are fine my next thought would be to validate the VPN (can you ping the server, can you resolve the IP of the hostname, etc.).
Answer: First you need to make sure there is nothing wrong with the shares. Try to access them within your network and make sure they are working the way you want to. Use one of your users account having the problem connecting with VPN to make sure is not a user account relates issue neither.
You need to be systematic when troubleshooting problems.
If everything works within your network then VPN is the issue. VPNs connections are complicated and hard to troubleshoot.
Having multiple subnets and using the remote routing component in Windows creates a routing problem.. Computers connecting to the VPN  using the same subnet won't be able to get to the network...because of the routing problem.

Cannot access server shares via VPN


Need help web scraping table with beautifulsoup and selenium webdriver

Question: So I am working on trying to webscrape https://data.bls.gov/cgi-bin/surveymost?bls and was able to figure out how to webcrawl through clicks to get to a table.
The selection that I am practicing on is after you select the checkbox associated with " Employment Cost Index (ECI) Civilian (Unadjusted) - CIU1010000000000A" under Compensation and then select "Retrieve data".
Once those two are processed a table shows. This is the table I am trying to scrape.
Below is the code that I have as of right now.
Note that you have to put your own path for your browser driver where I have put < browser driver >.
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
import numpy as np
import requests
import lxml.html as lh

from selenium import webdriver
url = "https://data.bls.gov/cgi-bin/surveymost?bls"
ChromeSource = r"<browser driver>"

# Open up a Chrome browser and navigate to web page.
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless') # will run without opening browser.
driver = webdriver.Chrome(ChromeSource, chrome_options=options)
driver.get(url)

driver.find_element_by_xpath("//input[@type='checkbox' and @value = 'CIU1010000000000A']").click()
driver.find_element_by_xpath("//input[@type='Submit' and @value = 'Retrieve data']").click()

i = 2

def myTEST(i):
    xpath = '//*[@id="col' + str(i) + '"]'
    TEST = driver.find_elements_by_xpath(xpath)

    num_page_items = len(TEST)
    for i in range(num_page_items):
        print(TEST[i].text)
myTEST(i)

# Clean up (close browser once completed task).
driver.close()

Right now this only is looking at the headers. I would like to also get the table content as well.
If I make i = 0, it produces "Year". i = 1, it produces "Period". But if I select i = 2 I get two  variables which have the same col2 id for "Estimated Value" and "Standard Error".
I tried to think of a way to work around this and can't seem to get anything that I have researched to work.
In essence, it would be better to start at the point where I am done clicking and am at the table of interest and then look at the xpath of the header  and pull in the text for all of the sub 's.

 == $0
   Year
   Period
  Estimated Value
  Standard Error

I am not sure how to do that. I also tried to loop through the {i} but obviously sharing  with two header text causes an issue.
Once I am able to get the header, I want to get the contents. I could you some insight on if I am on the right path, overthinking it or if there is a simpler way to do all of this. I am learning and this is my first attempt using the selenium library for clicks. I just want to get it to work so I can try it again on a different table and make it as automate or reusable (with tweaking) as possible.
Comment: Scrapping or scraping?
Comment: [Edited] Scraping*

Thanks for catching that, through a spelling mistake is not really the point of what I am asking for help. :)
Answer: Actually you don't need selenium, You can just track the POST Form data, and apply the same within your POST request.
Then you can load the table using Pandas easily.
import requests
import pandas as pd

data = {
    "series_id": "CIU1010000000000A",
    "survey": "bls"
}

def main(url):
    r = requests.post(url, data=data)
    df = pd.read_html(r.content)[1]
    print(df)

main("https://data.bls.gov/cgi-bin/surveymost")

Explanation:

open the site.
Select Employment Cost Index (ECI) Civilian (Unadjusted) - CIU1010000000000A
Now you have to open your browser Developer Tools and navigate to Network Monitor section. etc Press  Ctrl + Shift + E ( Command + Option + E on a Mac).
Now you will found a POST request done.

Navigate to Params tab.

Now you can make the POST request. and since the Table is presented within the HTML source and it's not loaded via JavaScript, so you can parse it within bs4 or read it in nice format using pandas.read_html()

Note: You can read the table as long as it's not loaded via JavaScript. otherwise you can try to track the XHR request (Check previous answer) or you can use selenium or requests_html to render JS since requests is an HTTP library which can't render it for you.
Comment: @AndrewHicks you welcome, let me know in case if you found anything unclear so i can explain
Comment: Wow!!! Not only did that work, but it is so dynamic that it works with the other tables as well! I was definitely overthinking it but then again, I don't fully understand how this works. I will need to digest it some more to figure that part out but thank you so much!
Comment: Yeah...do you know of any "literature" that might cover the concept of what you did here? My background is in analytics (python, r and sql) and not html. Is the information in the data = {} different for every website? Can I use this on let's say yahoo finance or any other page that has a table? I would assume that some tweaks would be needed (aside from the url and the data variables like you put in series_id and survey. Thanks again. I definitely want to learn this.
Comment: @AndrewHicks well let me explain that within the answer. hold on
Comment: So a follow-up. First off, it looks like this method is not appropriate for all websites which is alright for now. Second, I want to tweak the code that that it doesn't just go from 2010-2020, but rather 1939-2020. On the website this requires selecting 1939 from the dropping on the top and then selecting "go".

I tried going about it your way, but it only errors out. Any ideas?

data = "from_year" : "1939", & "to_year" : "2020".

Also, so I take it that the params field exist in FireFox. Do you know if there is something similar in Chrome?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/212887/discussion-between--c-and-andrew-hicks).


Pyajam in debian 7

Question: I'm trying to make the installation package python Pyajam
I tried to install a pip, I received an error 4Suite-XML package
Installing collected packages: pyajam, 4Suite-XML
Running setup.py install for pyajam

Running setup.py install for 4Suite-XML
Usage:
-c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
-c --help [cmd1 cmd2 ...]
-c cmd --help
-c --help-commands
-c --help-packages

error: option --single-version-externally-managed not recognized
Complete output from command /usr/bin/python -c "import
XML/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file_'exec'))"            install --single-version-externally-managed --record /tmp/pip-YlpamB-   record/install-       record.txt:
Usage:

-c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
-c --help [cmd1 cmd2 ...]
-c cmd --help
-c --help-commands
-c --help-packages

error: option --single-version-externally-managed not recognized
The error appears with the installation of 4Suite-XML package, the dependence pyajam

I tried to install only 4Suite-XML
pip install 4Suite-XML

Return the same error
Finally I tried to install by apt
apt-get install python-pyajam
apt-get install python-4Suite-XML

Unable to find package python-pyajam or python-4Suite-XML
Answer: I solved the problem. Compile the package
$ wget http://pypi.python.org/packages/source/4/4Suite-XML/4Suite-XML-1.0.2.tar.bz2

$ tar -xvvf 4Suite-XML-1.0.2.tar.bz2

$ cd 4Suite-XML-1.0.2

$ ./setup.py install

------------------------------------------------------------------------
4Suite-XML version 1.0.2 has been successfully installed!

Python modules (including C extensions)
/usr/local/lib/python2.7/dist-packages

Executable scripts (for PATH environment variable)
/usr/local/bin

Examples, demos and other miscellaneous data files
/usr/local/share/4Suite

Developer files (regression tests)
/usr/local/lib/4Suite

Text documentation
/usr/local/share/doc/4Suite

HTML documentation
/usr/local/share/doc/4Suite/html

Pyajam in debian 7


Expected value until a success?

Question: Suppose we have the a game with a 5-sided unfair die (just to make the probabilities easier to sum to 1), each side having a different payout.
For each side $ x \in \{1,2,3,4\}$ we have the corresponding payouts $ \$1,...,\$4$. However, if the die lands in $5$ there's no payout and the game is over.
Each side, respectively, has probability $P(X=x) = \{0.15, 0.2, 0.25, 0.3, 0.1\}$
What's the expected payout for the game?
If we directly apply the expected value, we would get something like
$$\sum_x x_ip(x_i)= \$2.5 $$
However, the meaning behind calculating the expected value this way seems to only capture the expected value for the game for 1 trial.
How would one approach such a problem?
Comment: (a) Yes, probably expected something more formal. perhaps as in answer by @polettix. (b) Been looking at your phrase 'something like'.
Given that you're going to win, seems the cond'l probabilities of various amounts are $(.15,.2,.25,.3)/.9$, which sum to 1 and so expected winnings are almost \$2.78. Then, multiplying by 9 payouts on avg it is $25. I did a simulation and that's what I got.
Comment: So in this game, we keep rolling the die (and paying in each roll) until we roll the first 5, correct?
Comment: @StephanKolassa Correct.
Comment: So on average, do you have 9 opportunities to win \$2.50?
Comment: @BruceET It would seem so, due to the 0.1 probability of the game ending. However, I was wondering if people would suggest solving this through something more "formal", such as discussing a negative multinomial distribution, or formulating it as a conditional expectation.
Answer: I would have liked to comment but I still can't... so I'll give a complete answer hoping that I'm not spoiling any homework.
I'd start saying that the "winning" sides of this five-sided unfair die are a distraction. We can re-arrange the calculations and obtain the expected value for a single roll:
$$ E_s = 0.9 \cdot \sum_{i=1}^{4}{x_i \cdot \frac{p(x_i)}{\sum_{i=1}^{4}{p(x_i)}}} + 0.1 \cdot 0 = 0.9 \cdot E_w$$
where $E_w$ is the expected value for the win under the assumption that we win (which happens with probability $0.9 = \sum_{i=1}^{4}{p(x_i)} = 1 - 0.1$).
It's like having a loaded coin, where you win $E_w$ with probability $0.9$ and get nothing otherwise.
In the "extended game" case (i.e. winning allows us to continue), if we win the first roll we are getting an expected value of $E_w$ (for the first successful roll) plus our expected value for... an undefined number of rolls, i.e. what we are after. In other terms, the expected value $E_m$ for multiple rolls will be:
$$ E_m = 0.9\cdot(E_w + E_m)$$
$$ E_m = \frac{0.9 \cdot E_w}{0.1} = \frac{E_s}{0.1} = \frac{E_s}{p(x_5)}$$
From another angle, we might observe that the number of trials to get one "success" (in this case, losing!) when repeatedly tossing our loaded coin can be modeled by a geometric distribution. Hence we might just multiply the expected value for a single toss $E_s$ by the average number of tosses needed to get this "successful failure", which is $\frac{1}{p(x_5)}$, and obtain the same result.
Comment: No worries, this is not a homework problem. I was reading about negative binomial distributions and I was wondering how that would extend to a multinomial setting (since reading material for negative multinomial distributions seems to be significantly reduced, from what I found). So it seems like the intuition you provide is to --roughly-- convert this problem into a binomial, summarizing the other outcomes by their expected value, and computing the expected value of this binomial distribution?
Comment: I'm not sure that the binomial really fits here (but I'm no expert), unless of course we consider the Bernoulli as a very simple binomial. I tend to think to the binomial when you know beforehand how many rounds you will have, and you want to model how many times you are likely to "win" in those rounds. The specific case is more in line with the geometric distribution IMHO. The first half of the answer is derived from trying to draw the tree of possibilities with associated weights, and recognizing that the infinite sub-tree is the same as the whole tree, hence the CS-ish recursive relation.
Comment: (+1) esp for correcting avg winnings.
Answer: Recursion
We can define the expected value of the game in a recursive manner. Let's assume that the expected benefit from the game (all rolls until the game ends) is x.
Using the probabilities you give for rolling {0.15,0.2,0.25,0.3,0.1} and the winnings of {\$1, \$2, \$3, \$4, [game ends]}, the expected value of the roll is $2.5 plus the value of that 90% chance of continuing the game - and given the rules of this game, it's clear "the right to continue the game" is exactly as valuable as "the right to play the game" - if the game hasn't ended, at the start of the second (or any other future) roll my potential future winnings (excluding the winnings of previous rolls) are exactly the same as in the beginning of the game.
So we can define the value of the game before the first roll is made as x=$2.5+0.9x, recursively referring to the value itself - and the resulting equation is trivially solvable to x=$25.
In essence this is equivalent to Polettix's answer, but IMHO this approach is much simpler to understand.
Answer: Simulation, per Comment: At each iteration, the die is rolled 400 times,
but only the rolls up to the first observed 5 are counted. Then
the payout w is computed, ignoring the trial on which the 5 occurred.
I chose 400 rolls because (with very high probability) that is enough
to get a 5. [Sloppy programming, wasteful of random numbers, but runs quickly.]
set.seed(1237)  # for reproducibility
pr = c(.15, 0.2, 0.25, 0.3, 0.1)
m = 10^6;  w = h = numeric(m)
for(i in 1:m) {
 x = sample(1:5, 400, rep=T, p=pr)
 h[i] = match(5,x); s = h[i]       # stopping point
 w[i] = sum(x[1:s])-5
 }
mean(w); mean(h)
[1] 25.00693     # aprx 9*2.777778 = 25; avg total payout
[1] 10.00337     # aprx 1/.1 = 10; avg trial number at stop

Note: Can look at summary(h) to see it's consistent with a geometric
distribution (and contains no NAs from almost-impossible runs of
400 without at 5).
summary(h)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
      1       3       7      10      14     143

Answer: There's a .9 chance that you'll win 2.5 EV. You could also win a second 2.5. The probability of that, contingent on winning the first 2.5, is .9, for a total probability of .9^2. You can continue winning 2.5, with the probability of the nth win being .9^n. So you have
$\sum (2.5*.9^n) = 2.5\sum .9^n$, which is a geometric series. Using the formula $\sum r^n = \frac 1 {1-r}$, you get that the total EV is 2.5*10 = 25.
You can also use the algebra mentioned in other answers: EV = 2.5+.9Ev -> EV = 25. This is of course simpler to do, but I decided to post both methods as there's a nonzero chance that someone will read this answer and it will make the geometric series formula slightly less mysterious.
PS You could have a six-sided die where 5 and 6 have probability .05 each, and either results in a loss.

Expected value until a success?


Issue with RegExp matching a phone number format in query

Question: I am trying to write a RegExp for MySQL that will only return the following 3 phone formats:
+1 000-000-0000 x0000
+1 000-000-0000
000-000-0000 x0000
000-000-0000
So basically:
+[any number of digits][space][any three digits]-[any three digits]-[any four digits][space][x][any number of digits]
The country code and the extension are optional. I am new to these but I would think this should return at least a number including both country code and extension options, but I get 0 results when I execute it.
\x2B[0-9]*\x20[0-9]{3}\-[0-9]{3}\-[0-9]{4}\x20x[0-9]+|
\x2B[0-9]*\x20[0-9]{3}\-[0-9]{3}\-[0-9]{4}|
[0-9]{3}\-[0-9]{3}\-[0-9]{4}

Can someone tell me why I am getting 0 results even though I have records like +1 555-555-5555 x5555 in my db. Also what is the syntax to make the country code and the extension are optional
Please note I am using [0-9] because I am querying a text field and \d didn't seem to return anything even when my criteria was something simple like \d*
Comment: Why are you using `\x2B` instead of just escaping the `+`: `\+`? Is there a particular reason? And why are you escaping the spaces (i.e. `\x20` instead of ` `)
Comment: Basically because I did not know you could do it that way :)
Answer: So, as a joint effort, turns out the answer is here:
SELECT * FROM table
WHERE field
REGEXP '(^[+][0-9]+\ )?([0-9]{3}\-[0-9]{3}\-[0-9]{4})(\ x[0-9]+$)?'

First was the fact that character codes in mysql (x20, x2B  and the like) are not allowed. Next important step was the use of parenthesis and the "?" token to make the different sections optional.
============
I think the issue is the lack of parenthesis to define the subexpressions.
This seems to work out for me, though it doesn't look real pretty:
SELECT '+1 000-000-0000 x0000' REGEXP '^(([+][0-9]*\[ ][0-9]{3}\-[0-9]{3}\-[0-9]{4}[ ]x[0-9]+)|())$'

as does
SELECT '' REGEXP '^(([+][0-9]*\[ ][0-9]{3}\-[0-9]{3}\-[0-9]{4}[ ]x[0-9]+)|())$'

as does (plain phone number):
SELECT '555-555-5555' REGEXP '^(([+][0-9]*\[ ])*[0-9]{3}\-[0-9]{3}\-[0-9]{4}([ ]x[0-9]+)*)|())$'

EDIT: (same regexp as above, but testing against version w/ country code and extension):
SELECT '+1 555-555-5555 x55' REGEXP '^(([+][0-9]*\[ ])*[0-9]{3}\-[0-9]{3}\-[0-9]{4}([ ]x[0-9]+)*)|())$'

When I try yours:
SELECT '+1 000-000-0000 x0000' REGEXP '\x2B[0-9]*\x20[0-9]{3}\-[0-9]{3}\-[0-9]{4}\x20x[0-9]+|'

I get:
1139 - Got error 'empty (sub)expression' from regexp

Comment: @dgig it turns out I was looking for (expression)? For anyone reading grouping with () and adding a trailing? makes it optional. I was able to finally solve it with the following expression: SELECT * FROM `table` WHERE field REGEXP '(^[+][0-9]+\ )?([0-9]{3}\-[0-9]{3}\-[0-9]{4})(\ x[0-9]+$)?' I would not have been able to get there without walking through your examples so if you would like to update your answer I will select it as the answer.
Comment: I found out you can not use chr codes in mysql. I needed to escape. This is what I finally ended up with that seems to work: ^\\+[0-9]+\ |^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$|\ x[0-9]+$
Comment: If that's the problem you had, please post an answer detailing it and accept it.
Comment: I still have not figured out the complete answer. I need to know how to make the country code and extension optional. What I have right now is basically any of the three.
Comment: My third SELECT shows that, does it not? Indeed it does.
Comment: You can put parenthesis around sections of characters to group them, and then apply any  kind of count token (*, +, {3}) to that.


Python Como clickar em divs usando selenium

Question: Estou tentando pegar empregos no google empregos e extrair dados para guadar em banco de dados ou em json.
Sites: GOOGLE EMPREGOS TELA
Notem como tenho no lado esquerdo uma lista com varios empregos e quando clico em algum ele exibe na tela ao lado informações mais detalhas, como faço pra cada emprego na lista da esquerda ser clickado e depois extrair o texto do titulo do emprego, como ali na imagem onde está escrito Estágio TI no lado de exibição
Meu codigo:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url1 = 'https://www.google.com/search?client=firefox-b-d&ei=Ja39X_nUIKif5OUPp6eUkAE&q=vagas+estagio+ti&oq=vagas+estagio+ti&gs_lcp=CgZwc3ktYWIQAzIICAAQsQMQgwEyAggAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADICCAA6BAgAEEc6CggAELEDEIMBEEM6BAgAEEM6DggAELEDEIMBEMcBEK8BOgsIABCxAxDHARCjAjoFCAAQsQM6BQguELEDOggIABDHARCvAVDeMFipTmClUGgCcAN4AIABnQKIAbUckgEGMC4xLjE1mAEAoAEBqgEHZ3dzLXdpesgBCMABAQ&sclient=psy-ab&uact=5&ibp=htl;jobs&sa=X&ved=2ahUKEwjZlb7fyJbuAhXWGbkGHdiZAEUQutcGKAB6BAgDEAQ#htivrt=jobs&fpstate=tldetail&htilrad=-1.0&htidocid=jN52cIGLUm9ZT0BQAAAAAA%3D%3D'

# Definindo Drive
driver = webdriver.Chrome(executable_path=r'./chromedriver')
driver.get(url1) # Entrando no url1

# Click

time.sleep(10)
driver.quit() # Fechando o driver

Como posso fazer?
Answer: Um elemento pode ser clicado no Selenium através da função click():
elemento = driver.find_element_by_class_name('foo')
elemento.click()

Comment: Mas tem varios elementos com a mesma classe, como clico neles°
Comment: Nesse caso você pode usar `find_elements_by_class_name`, que irar retornar uma lista. Veja mais sobre aqui: https://selenium-python.readthedocs.io/locating-elements.html
Comment: Então o meu problema era que retorna uma lista kkkk, obrigado


lighttpd: How to disable auth on second site

Question: My setup has the current auth config.  it forces authentication by any remote host.  That's good.  But I need to make an exception.
<code>auth_file="/etc/lighttpd.users"
#if auth_file is not empty enable lighttpd local authentification

if grep -q ".*:.*" "$auth_file" 2>/dev/null;then
    sed -ir '/^$/d' $auth_file
    cat <<EOF
\$HTTP["remoteip"] != "127.0.0.1" {

    auth.backend = "htdigest"
    auth.backend.htdigest.userfile = "$auth_file"

    auth.require = (
        "/" => (
        "method"  => "digest",
        "realm"   => "MyRealm",
        "require" => "valid-user"
        )
    )
}
EOF
fi
</code>
I setup a second server on a different port (as seen below).  I'd like to make an exception to my auth script such that users to this 2nd site do not require authentication.
<code>$SERVER["socket"] == ":8080" {
        server.document-root = "/www2"
                }
</code>
Answer: Seems like you've already got it, just not put together. If you have config options for the other server above, you might need to put that in the else block first.
<code>\$SERVER["socket"] == ":8080" {
    server.document-root = "/www2"
}
else \$HTTP["remoteip"] != "127.0.0.1" {

    auth.backend = "htdigest"
    auth.backend.htdigest.userfile = "$auth_file"

    auth.require = (
        "/" => (
        "method"  => "digest",
        "realm"   => "MyRealm",
        "require" => "valid-user"
        )
    )
}
</code>


Time Signature Issue

Question: I've been having an issue with this composition. Is it supposed to be 4/4 or would it become a different time signature? I know that 4/4 is 4/4 often because each note contains 4 beats- but often I heard composers could take time signatures such as 6/8 or 3/4 because of how the notes look better displayed or in terms of rhythm. This measure contains a bunch of 32and and 16th notes... Would the time signature end with ?/16 or ?/32?
Answer: Different time signatures can be used to simplify the notation, but I would argue that that's not the case in this example, which strikes me as a pretty clear 4/4 assuming an average tempo. Rather, I think it's just that the notation of this example isn't ideal. While it may be exact in terms of note lengths, a more standard notation would be something like:

This way the reader doesn't have to crawl through a forest of eighth and sixteenth-note rests to determine the meter.
Historically, other "equivalent" time signatures like 2/4 versus 8/16 could be used to suggest some tempo or other performance implications. For more on this, see especially this fantastic answer to Is there any practical difference between 3/4 and 3/8 time?
Comment: Excellent job using articulations and simplifying this to make it readable, Richard. The music in the question looks like what happens when computer notation programs interpret something too literally.
Comment: You could improve this even further by writing the last beat of measures 9 & 10 as staccato eighths. Also the fouth eighth of M.8
Comment: @PiedPiper Absolutely. I considered this, but for some reason decided against it; perhaps just to still include some sixteenth notes? I'm not exactly sure, but there *are* multiple ways of notating this.
Comment: If you have to sight-read this kind of stuff, simpler is always better.
Answer: Were I attempting to play this, the problem would not be the time signature, but rather the manner of notation, which is hard to read. It's best to bar together notes that combine to form one or two beats -- as has been done with the first fourth eighth-notes -- and this can be done even when there are rests in between.
X:0
T:Re-stemming of OP Example
M:4/4
K:C major
L:1/16
A2^F2A2d2 B4 z4| B/2z/2Bz2 A/2z/2Az2 ^F2z2 =FzEz | DzB,z DEEz D6z2 [|: _G,z_A,z B,zA,z F,A,zB,- B,zA,z | _F,zA,z B,zA,z D,A,zB,- B,zA,z :|]

However, even this is hard to read. Unless the rests are essential to the interpretation, you could get the same sound by removing the rests and notating with staccato:
X:0
T:Staccato Rewrite of OP Example
M:4/4
K:C major
L:1/8
A^FAd B2 z2 | .B/2.B/2z .A/2.A/2z ^Fz.=F.E | .D.B, D/2E/2.E D3z [|: ._G,._A,.B,.A, F,/2A,/2z/2B,/2- B,.A, | ._F,.A,.B,.A, D,/2A,/2z/2B,/2- B,.A, :|]

You could change the time signature to 16/16 or 32/32, but that wouldn't solve the fundamental readability issue, because the notation itself wouldn't change. However, you could change to something like 8/16, which would have the effect of bar-lines breaking up the notation into easier to digest chunks. This is not recommended, though, as it creates unnecessary clutter and is potentially confusing both for being non-standard and for making it ambiguous how to handle the underlying pulse -- an additional "sixteenth note = sixteenth note" marking would have to be included, adding to the clutter.
X:0
T:8/16 Rewrite of OP Example
M:4/4
K:C major
L:1/16
A2^F2A2d2 B4 z4| [M:8/16]B/2z/2Bz2 A/2z/2Az2 | ^F2z2 =FzEz | DzB,z DEEz | D6z2 [|: _G,z_A,z B,zA,z | F,A,zB,- B,zA,z | _F,zA,z B,zA,z | D,A,zB,- B,zA,z :|]

Please forgive the ugly too-tall stems. That's just how ABCjs does things.
Comment: If something can be written clearly in 4/4 then there's no need to look at other time signatures. The answer to the question is "leave it in 4/4 and simplify the notation".
Comment: @PiedPiper What's wrong with the 8/16 version?
Comment: @PiedPiper True, however OP specifically asked about changing the time signature.... Okay, I have an idea....
Comment: @PiedPiper Do you think the edit improves matters (a few sentences just above the 8/16 example)?

Time Signature Issue


glmer logit - interaction effects on probability scale (replicating `effects` with `predict`)

Question: I am running glmer logit models using the lme4 package. I am interested in various two and three way interaction effects and their interpretations. To simplify, I am only concerned with the fixed effects coefficients.
I managed to come up with a code to calculate and plot these effects on the logit scale, but I am having trouble transforming them to the predicted probabilities scale. Eventually I would like to replicate the output of the effects package.
The example relies on the UCLA's data on cancer patients.
library(lme4)
library(ggplot2)
library(plyr)

getmode <- function(v) {
  uniqv <- unique(v)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}

facmin <- function(n) {
  min(as.numeric(levels(n)))
}

facmax <- function(x) {
  max(as.numeric(levels(x)))
}

hdp <- read.csv("http://www.ats.ucla.edu/stat/data/hdp.csv")

head(hdp)
hdp <- hdp[complete.cases(hdp),]

hdp <- within(hdp, {
  Married <- factor(Married, levels = 0:1, labels = c("no", "yes"))
  DID <- factor(DID)
  HID <- factor(HID)
  CancerStage <- revalue(hdp$CancerStage, c("I"="1", "II"="2", "III"="3", "IV"="4"))
})

Until here it is all data management, functions and the packages I need.
m <- glmer(remission ~ CancerStage*LengthofStay + Experience +
             (1 | DID), data = hdp, family = binomial(link="logit"))
summary(m)

This is the model. It takes a minute and it converges with the following warning:
Warning message:
In checkConv(attr(opt, "derivs"), opt$par, ctrl = control$checkConv,  :
  Model failed to converge with max|grad| = 0.0417259 (tol = 0.001, component 1)

Even though I am not quite sure if I should worry about the warning, I use the estimates to plot the average marginal effects for the interaction of interest. First I prepare the dataset to be feed into the predict function, and then I calculate the marginal effects as well as the confidence intervals using the fixed effects parameters.
newdat <- expand.grid(
  remission = getmode(hdp$remission),
  CancerStage = as.factor(seq(facmin(hdp$CancerStage), facmax(hdp$CancerStage),1)),
  LengthofStay  = seq(min(hdp$LengthofStay, na.rm=T),max(hdp$LengthofStay, na.rm=T),1),
  Experience  = mean(hdp$Experience, na.rm=T))

mm <- model.matrix(terms(m), newdat)
newdat$remission <- predict(m, newdat, re.form = NA)
pvar1 <- diag(mm %*% tcrossprod(vcov(m), mm))
cmult <- 1.96

## lower and upper CI
newdat <- data.frame(
  newdat, plo = newdat$remission - cmult*sqrt(pvar1),
  phi = newdat$remission + cmult*sqrt(pvar1))

I am fairly confident these are correct estimates on the logit scale, but maybe I am wrong. Anyhow, this is the plot:
plot_remission <- ggplot(newdat, aes(LengthofStay,
  fill=factor(CancerStage), color=factor(CancerStage))) +
  geom_ribbon(aes(ymin = plo, ymax = phi), colour=NA, alpha=0.2) +
  geom_line(aes(y = remission), size=1.2) +
  xlab("Length of Stay") + xlim(c(2, 10)) +
  ylab("Probability of Remission") + ylim(c(0.0, 0.5)) +
  labs(colour="Cancer Stage", fill="Cancer Stage") +
  theme_minimal()

plot_remission

I think now the OY scale is measured on the logit scale but to make sense of it I would like to transform it to predicted probabilities. Based on wikipedia, something like exp(value)/(exp(value)+1) should do the trick to get to predicted probabilities. While I could do newdat$remission <- exp(newdat$remission)/(exp(newdat$remission)+1) I am not sure how should I do this for the confidence intervals?.
Eventually I would like to get to the same plot what the effects package generates. That is:
eff.m <- effect("CancerStage*LengthofStay", m, KR=T)

eff.m <- as.data.frame(eff.m)

plot_remission2 <- ggplot(eff.m, aes(LengthofStay,
  fill=factor(CancerStage), color=factor(CancerStage))) +
  geom_ribbon(aes(ymin = lower, ymax = upper), colour=NA, alpha=0.2) +
  geom_line(aes(y = fit), size=1.2) +
  xlab("Length of Stay") + xlim(c(2, 10)) +
  ylab("Probability of Remission") + ylim(c(0.0, 0.5)) +
  labs(colour="Cancer Stage", fill="Cancer Stage") +
  theme_minimal()

plot_remission2

Even though I could just use the effects package, it unfortunately does not compile with a lot of the models I had to run for my own work:
Error in model.matrix(mod2) %*% mod2$coefficients :
  non-conformable arguments
In addition: Warning message:
In vcov.merMod(mod) :
  variance-covariance matrix computed from finite-difference Hessian is
not positive definite or contains NA values: falling back to var-cov estimated from RX

Fixing that would require adjusting the estimation procedure, which at the moment I would like to avoid. plus, I am also curious what effects actually does here.
I would be grateful for any advice on how to tweak my initial syntax to get to predicted probabilities!
Comment: I think your plot will be easier to read if you do something like this: `ggplot(newdat, aes(LengthofStay, fill=factor(CancerStage), color=factor(CancerStage))) +
  geom_ribbon(aes(ymin=plo, ymax=phi), colour=NA, alpha=0.2) +
  geom_line(aes(y = remission), size=1.2) +
  xlab("Length of Stay") +
  ylab("Probability of Remission") +
  labs(colour="Cancer Stage", fill="Cancer Stage") + theme_minimal()`
Comment: You should definitely worry about the convergence warning.
Comment: I don't really get why this is such an impossible question to answer... Is something unclear in what I am asking for?
Comment: I agree with @JacobSocolar . I think that the fact that your model doesn't converge, will result in spurious model estimates. So be careful there.
Comment: sure, thanks! but that's a rather side point. How can I get the plot to reflect predicted probabilities with my initial syntax based on `predict`?
Comment: the code that is run by the effects package may be obtained by running `getAnywhere(Effect.default)`
Comment: By the way, this line in your code is nt replicable because  `revalue` function is not in base R nor in the loaded packages : `CancerStage <- revalue(hdp$CancerStage, c("I"="1", "II"="2", "III"="3", "IV"="4"))`. I used `levels(hdp$CancerStage) <- c(1:4)` instead
Answer: To obtain a similar result as the effect function provided in your question, you just have to back transform both the predicted values and the boundaries of your confidence interval from the logit scale to the original scale with the transformation you provide : exp(x)/(1+exp(x)).
This transformation can be done in base R with the plogis function :
> a <- 1:5
> plogis(a)
[1] 0.7310586 0.8807971 0.9525741 0.9820138 0.9933071
> exp(a)/(1+exp(a))
[1] 0.7310586 0.8807971 0.9525741 0.9820138 0.9933071

So using proposal from @eipi10 using ribbons for the confidence bands instead of the dotted lines (I also find this presentation more readable) :
   ggplot(newdat, aes(LengthofStay, fill=factor(CancerStage), color=factor(CancerStage))) +
        geom_ribbon(aes(ymin = plogis(plo), ymax = plogis(phi)), colour=NA, alpha=0.2) +
        geom_line(aes(y = plogis(remission)), size=1.2) +
        xlab("Length of Stay") + xlim(c(2, 10)) +
        ylab("Probability of Remission") + ylim(c(0.0, 0.5)) +
        labs(colour="Cancer Stage", fill="Cancer Stage") +
        theme_minimal()

The results are the same (with effects_3.1-2 and lme4_1.1-13):
> compare <- merge(newdat, eff.m)
> compare[, c("remission", "plo", "phi")] <-
+     sapply(compare[, c("remission", "plo", "phi")], plogis)
> head(compare)
  CancerStage LengthofStay  remission Experience        plo       phi        fit        se      lower     upper
1           1           10 0.20657613   17.64129 0.12473504 0.3223392 0.20657613 0.3074726 0.12473625 0.3223368
2           1            2 0.35920425   17.64129 0.27570456 0.4522040 0.35920425 0.1974744 0.27570598 0.4522022
3           1            4 0.31636299   17.64129 0.26572506 0.3717650 0.31636299 0.1254513 0.26572595 0.3717639
4           1            6 0.27642711   17.64129 0.22800277 0.3307300 0.27642711 0.1313108 0.22800360 0.3307290
5           1            8 0.23976445   17.64129 0.17324422 0.3218821 0.23976445 0.2085896 0.17324530 0.3218805
6           2           10 0.09957493   17.64129 0.06218598 0.1557113 0.09957493 0.2609519 0.06218653 0.1557101
> compare$remission-compare$fit
 [1] 8.604228e-16 1.221245e-15 1.165734e-15 1.054712e-15 9.714451e-16 4.718448e-16 1.221245e-15 1.054712e-15 8.326673e-16
[10] 6.383782e-16 4.163336e-16 7.494005e-16 6.383782e-16 5.689893e-16 4.857226e-16 2.567391e-16 1.075529e-16 1.318390e-16
[19] 1.665335e-16 2.081668e-16

The differences between the confidence boundaries is higher but still very small :
> compare$plo-compare$lower
 [1] -1.208997e-06 -1.420235e-06 -8.815678e-07 -8.324261e-07 -1.076016e-06 -5.481007e-07 -1.429258e-06 -8.133438e-07 -5.648821e-07
[10] -5.806940e-07 -5.364281e-07 -1.004792e-06 -6.314904e-07 -4.007381e-07 -4.847205e-07 -3.474783e-07 -1.398476e-07 -1.679746e-07
[19] -1.476577e-07 -2.332091e-07

But if I use the real quantile of the normal distribution cmult <- qnorm(0.975) instead of cmult <- 1.96 I obtain very small differences also for these boundaries :
> compare$plo-compare$lower
 [1] 5.828671e-16 9.992007e-16 9.992007e-16 9.436896e-16 7.771561e-16 3.053113e-16 9.992007e-16 8.604228e-16 6.938894e-16
[10] 5.134781e-16 2.289835e-16 4.718448e-16 4.857226e-16 4.440892e-16 3.469447e-16 1.006140e-16 3.382711e-17 6.765422e-17
[19] 1.214306e-16 1.283695e-16

Comment: Thank you! This helps a lot! Unfortunately though there is still a small difference between the two plots, I brought them to the same scale so it's visible in the curves (I added `xlim` and `ylim`). You can also see the difference with e.g. `compare <- merge(newdat, eff.m)
head(compare)
compare$remission-compare$fit` Indeed, in this example the difference is extremely small, but I would like to understand where the bias comes from, so I can eliminate it in my research. PS: I edited the plots and added the `plyr` package. Thanks for your answer!
Comment: See the edited reply. I cannot replicate any significant difference. Maybe a difference in packages versions ? NB you should also add `library(effects)` in your code and delete  `ylim` of your first plot (this plot is on the logit scale so the 0,0.5 limits are outside the range of the plot)


Casio fx-82MS: n-th logarithm

Question: I have got a Casio fx-82MS calculator, and I want to calcuate various logarithms with it, especially $\log₂(x)$-style logarithms. Unfortunately, its user interface contains buttons for just $\ln$ and $\log₁₀$.
How to do it with the existing set of buttons/commands?
Comment: $\log_a x={\ln x\over\ln a}$.
Comment: Use change of base property of a logarithm?
Comment: @Nunoxic, wow, is it possible? I'll search this function. David Mitra, your solution is great for me.
Answer: According to David Mitra, $\log_a x={\ln x\over\ln a}$, what is absolutely usable for me.
Comment: You could also use $\log_a x=\dfrac{\log_{10} x }{\log_{10} a }$ if you prefer (or accidentally press the wrong log button)

Casio fx-82MS: n-th logarithm


Meaning of a novel "division" notation

Question: In Oliver Salazar Celis' "Adaptive Thiele interpolation," ACM Communications of Computer Algebra 56(3), Issue 221, September 2022, page 125 (Eq. 1) we find:

What does this horizontal plus vertical division-like notation mean?
Comment: It's a continued fraction. Wikipedia and other sources attribute the notation to Pringsheim.
Comment: Oh... OK.... thanks.  I'll look it up more thoroughly.   ($+1$)
Answer: It's mentioned in the sentence leading up to the formula:
"...this routine produces a continued fraction of the form..." [source]

On the notation of continued fractions, WolframAlpha has
Comment: Got it... thanks!  ($+1, \checkmark$)

Meaning of a novel "division" notation


Construindo um web crawler em python. Preciso de ajuda para adicionar threads

Question: Estou tentando desenvolver um web crawler para estudos. Ele está bem simples e gostaria de melhorá-lo. Como usar threads para acelerar/melhorar o processo? O programa poderia fazer vários links em paralelo. Como aplicar o conceito de threads ao crawler?
import requests
import re

to_crawl =['http://www.g1.globo.com'] #url para fazer o crawler (a semente: ponto de partida)
crawled = set()# o conjunto do que "ja fiz"/ja percorrido, foi feito o crawer
#se a url já estiver em crawled, vou para a próxima!

#é bom usar header pra finger ser um navegador
header = {"user-agent":"Mozilla/5.0 (X11; Linux i686; rv:45.0) Gecko/20100101 Firefox/45.0",
          "accept": "*/*",
          "accept-language": "en-US,en;q=0.5",
          "accept-encoding": "gzip, deflate",
          "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
          }
while True: #executar pra sempre...

    url = to_crawl[0]
    try: #tratar pox ex URL invalidas..
        req = requests.get(url,headers=header)
    except: #remove a url
        to_crawl.remove(url)
        crawled.add(url)
        continue #passa pro prox link

    #print (req.text) #é a página!
    html = req.text

    links = re.findall(r'(?<=href=["\'])https?://.+?(?=["\'])' ,html)
    print ("Crawling", url)

    #apos a requisicao, removo do to_crawl e insiro em no conjunto crawled:
    to_crawl.remove(url)
    crawled.add(url)

    #agora joga links in to_crawl se nao estiverem em crawled:
    for link in links:
        if link not in crawled and link not in to_crawl:  #se nao estiver nas 2 listas
            to_crawl.append(link)

    #print(padrao.group())
    #print(padrao,)

    for link in links:
        print(link)

Answer: Montei um exemplo bem básico de como poderia ficar usando Thread (já da maneira mais moderna de como trabalhar com threads em python, através do módulo concurrent.futures).
ATENÇÃO O EXEMPLO FOI ESCRITO UTILIZANDO PYTHON 3
import re
from concurrent.futures import ThreadPoolExecutor, as_completed

import requests

HEADERS = {
    'user-agent':
        'Mozilla/5.0 (X11; Linux i686; rv:45.0) Gecko/20100101 Firefox/45.0',
    'accept': '*/*',
    'accept-language': 'en-US,en;q=0.5',
    'accept-encoding': 'gzip, deflate',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
}

MAX_WORKERS = 4

def featch_url(url):
    try:
        res = requests.get(url, headers=HEADERS)
    except:
        return url, ''
    return url, res.text

def process_urls(urls):
    result = {}
    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        futures = [executor.submit(featch_url, url) for url in urls]
    for future in as_completed(futures):
        url, html = future.result()
        result[url] = html
    return result

if __name__ == '__main__':
    urls = ['http://www.pudim.com.br/']
    crawled = set()
    while urls:
        to_process = {url for url in urls if url not in crawled}
        print('start process urls: ', to_process)
        process_result = process_urls(to_process)
        urls = []
        for url, page in process_result.items():
            crawled.add(url)
            urls += re.findall(r'(?<=href=["\'])https?://.+?(?=["\'])', page)

    print('Crawled pages: ', crawled)

O destaque do exemplo fica por conta da função process_urls que fica responsável por criar o ThreadPoolExecutor e "disparar" as threads.
Obviamente o exemplo deverá ser adaptado para a sua necessidade, pois da forma como está ele só irá percorrer todos os links que for encontrado pela frente e por fim vai adicionando no set crawled as páginas que já foram processadas.
Algumas observações

No MAX_WORKERS(que consiste no número máximo de threads que serão abertas por vez) usei um número completamente arbitrário, porém a boa prática é usar o numero de CPUs da máquina * 2 (pode ser obtido via os.cpu_count() * 2)
Caso você pense em fazer algum processamento em cada url (e não só pegar os links) você pode fazer dentro do for do as_completed, pois você consegue já ir processando as páginas conforme elas forem lidas e não somente quando todas forem lidas (isso lhe trara mais performance).
Antes de trabalhar com Threads, tente entender os efeitos colaterais disso, ou seja, pesquise sobre race conditions, locks, etcs.

Apesar de ter feito o exemplo com thread (a nível de estudo/aprendizado) recomendo que caso seja necessário uma solução mais robusta de crawler, você de uma olhada no Scrapy e evite de reinventar a roda (a não ser que seja para apreender como as rodas funcionam).
Comment: a legal, então acho que vai ajudar :)
se tiver alguma dúvida ou problema é só falar
Comment: Vou estudar o código, testar e te retorno depois. Obrigado.
Comment: Obrigado @drgarcia1986. O programa é apenas para estudos!
Comment: Obrigado. Em breve, te retorno.
Comment: criei um outro tópico com assunto semelhante num outro projeto, pois tenho dificuldade com o uso de Threads.
Answer: Aqui está um exemplo (python 3.x) simples, a abordagem é um pouco diferente da sua:
import re
from threading import Thread
import requests

def get_links(url):
    req = get_req(url)
    if(req is not None):
        html = req.text
        urls = re.findall('(?<=href=["\'])https?://.+?(?=["\'])', html)
        return urls
    return None

def get_req(url):
    try:
        req = s.get(url)
        return req
    except Exception:
        print('[-] Erro ao ir buscar página: ', url)
        return None

def inject_links(data, url):
    urls = get_links(url)
    if(urls is not None):
        for url in urls:
            if(url not in data and len(data) < urls_max):
                data.add(url) # adicionamos aos urls crawled
                print('[+] Total: {} [+] putting: {} '.format(len(data), url))
                return inject_links(data, url)
    return

def producer(url, threadNum):
    while len(data) < urls_max:
        inject_links(data, url)
    #print('\n', data) # comentar isto depois de ter percebido, este print e muito pesado
    print('[+] Terminated - killing thread {} -> Total urls stored: {}'.format(threadNum, len(data)))
    # aqui pode escrever para um ficheiro por exemplo

data = set()
urls_max = 100
threads = 10
start_urls = ['http://pt.stackoverflow.com/', 'http://www.w3schools.com/default.asp', 'http://spectrum.ieee.org/']

s = requests.Session()
for i in range(len(start_urls)):
    for j in range(threads):
        t = Thread(target=producer, args=(start_urls[i], '{}.{}'.format(i+1, j+1)))
        t.start()

O uso de set() é para aumentar a performance quando adicionamos/procuramos alguma coisa armazenada lá, e para evitar urls duplicados. Retire o comentário do print dentro do método producer() para ver os urls armazenados
Neste caso vamos começar em três links com 10 threads em cada um, e cada tread é 'morta' quando tivermos 100 links. Esta condição vai ser o core do termino do programa if(url not in data and len(data) < urls_max), se o url não existir já dentro do nosso set() então adicionamos, e se numero total de urls no set for inferior ao urls_max
Comment: obrigado. Vou estudar o código!
Comment: criei um outro tópico com assunto semelhante num outro projeto, pois tenho dificuldade com o uso de Threads


Ideal technology stack for Drupal 6 in Windows Server 2008R2

Question: My background is predominantly Linux-based servers, with which I can configure anything however I want. However, I'm building a Drupal6 site for a client, who (despite my warnings) wishes to self-host from a server in his offices -- and is running Windows Server 2008R2 (likely upgrading to Small Business Server 2011 at some point).
While I have a good idea of the technology stack I'd use in Linux, I'm much less sure how I'd go about this in a Windows-based server environment.
What is the ideal technology stack for serving web-based PHP applications (specifically Drupal) in Windows?
And no, I can't reformat the thing as a Linux box. :) Thanks!
EDIT: One thing worth noting is that I've used MAMP (Apache2, MySQL) in Mac OS 10.6 as my testing environment. It'd be great if the tech stack could use MySQL as I'd ideally like to just dump then import the tables I've been using.
Comment: Not really an answer cuz I don't know what's ideal on Windows... But have you seen this? http://drupal.org/node/1130898 The stack includes IIS and SQL Server Express.
Comment: @Jason -- That's helpful, but seems more directed towards Drupal7. Microsoft Web PI also supports Acquia Drupal 6, but I don't know how the Acquia install profile differs from standard Drupal and am thus a little hesitant to use that.
Comment: The post at http://lab.usgin.org/groups/drupal-development/running-drupal-windows-server-2008-machine worries about running PHP on IIS. This is kind of the concern I'm having. Windows Server admins -- what's the deal with PHP and IIS? Is it at all stable?
Answer: The ideal tech stack on Windows for Drupal is 100% without a doubt Apache + PHP + MySQL. This software now sees more downloads for Windows then it does for Linux (since about 2009).
You should try any number of WAMP (Windows, Apache, MySQL, PHP) packages.
I think you will find WampDeveloper Pro ideal for your situation. It has a full user-interface that adds and manages websites, it installs web applications such as Drupal 6.2 for you automatically, manages local DNS, keeps Apache + MySQL + PHP updated at all times, and makes things very easy. But you pay for it (well worth it).
Though if you're client (or you) are looking for a free WAMP stack, there is XAMPP and WampServer. But they don't have any of the features that WampDeveloper does, and have no official support.
Comment: That's helpful; I may go with WampDeveloper Pro.