问:
Extracting lines from another file and saving unique fields in separate files in python
I am working with a very large zipped text file "values.gz", containing multiple values per gene with geneID in the 2nd column, and another small text file containing a list of unique genes in the fourth column ("bed.txt"). I am trying to extract information from the values.gz file (without reading it all but using the dictionary from bed.txt) for a subset of genes listed in the bed.txt file, and save it in a separate file per gene. I cannot do this in bash as the file is too large to unzip, so I am trying in python but I am a newbie, and I am stuck: I have got as far as extracting the matched genes and saving them in a file, but how do I save to a different file per gene?

For example, the bed.txt file looks like this:

```<code>chr    start   end     gene_id
1       11868   11869   ENSG00000223972
1       29552   29553   ENSG00000227232
1       29806   29807   ENSG00000243485
</code>```

The values.gz file looks like this:

```<code>SNP     gene    v1    v2  v3
rs1       ENSG00000223972       0.09      0.8       0.5
rs1       ENSG00000227232       -0.06     -0.5      0.6
rs1       ENSG00000237683       -0.05     -0.5      0.5
rs2       ENSG00000223972       0.09      0.8       0.3
rs3       ENSG00000227232       0.09      0.8      0.3
</code>```

The output I am looking for is:
ENSG00000223972.gz

```<code>rs1       ENSG00000223972       0.09      0.8       0.5
rs2       ENSG00000223972       0.09      0.8      0.3
</code>```

ENSG00000227232.gz

```<code>rs1       ENSG00000227232       -0.06     -0.5      0.6
rs3       ENSG00000227232       0.09      0.8       0.3
</code>```

(All genes in values.gz should have a matching value in bed (but not 100% sure!), but the bed file will have more genes listed that do not match the values.gz file)

```<code>#! /usr/bin/env python
import gzip

lookup = dict()
my_file = open("bed.txt","r")
for line in my_file.readlines():
    row = line.split()
    lookup[row[3]] = row[1:]
    # print lookup
my_file.close()

with open('MyOutFile', 'w') as outfile:
    with gzip.open("values.gz", "r") as eqtl:
        for line in eqtl.readlines():
            for key in lookup:
                if line.find(key) > -1:
                    outfile.write(line)
</code>```

After Paisanco's suggestions:

```<code>with gzip.open("values.gz", "r") as eqtl:
    for line in eqtl.readlines():
        row = line.split()
        gene = row[1]
        filename = gene+'.txt'
        if gene in lookup:
           # assign unique file name here, then
           if os.path.exists(filename):
               append_write = 'a'
           else:
               append_write = 'w'
           with open(filename,append_write) as outfile:
              outfile.write(line)
</code>```

答:
There are two things you can do here.

One, it looks like you are storing the quantity representing the geneID in your lookup table from the first file. If that quantity is the same type and value in the second file as in the first, you can search your lookup table more efficiently like this:

Code snippet:

```<code>for line in eqtl.readlines():
   row = line.split()
   if row[1] in lookup:
       # do something...
</code>```

Two, if you wanted a unique name for each gene, your file open and write should be the inner loop, instead of the outer. Something like this:

```<code>with gzip.open("values.gz", "r") as eqtl:
    for line in eqtl.readlines():
        row = line.split()
        if row[1] in lookup:
           # assign unique file name here, then
           with open ("UniqueFileNameForThisGene","w") as outfile:
              outfile.write(line)
</code>```

It would be up to you how you wanted to assign a unique file name for each gene - perhaps using other data in the line?

Body:
I am working with a very large zipped text file "values.gz", containing multiple values per gene with geneID in the 2nd column, and another small text file containing a list of unique genes in the fourth column ("bed.txt"). I am trying to extract information from the values.gz file (without reading it all but using the dictionary from bed.txt) for a subset of genes listed in the bed.txt file, and save it in a separate file per gene. I cannot do this in bash as the file is too large to unzip, so I am trying in python but I am a newbie, and I am stuck: I have got as far as extracting the matched genes and saving them in a file, but how do I save to a different file per gene?

For example, the bed.txt file looks like this:

chr    start   end     gene_id
1       11868   11869   ENSG00000223972
1       29552   29553   ENSG00000227232
1       29806   29807   ENSG00000243485

The values.gz file looks like this:

SNP     gene    v1    v2  v3
rs1       ENSG00000223972       0.09      0.8       0.5
rs1       ENSG00000227232       -0.06     -0.5      0.6
rs1       ENSG00000237683       -0.05     -0.5      0.5
rs2       ENSG00000223972       0.09      0.8       0.3
rs3       ENSG00000227232       0.09      0.8      0.3

The output I am looking for is:
ENSG00000223972.gz

rs1       ENSG00000223972       0.09      0.8       0.5
rs2       ENSG00000223972       0.09      0.8      0.3

ENSG00000227232.gz

rs1       ENSG00000227232       -0.06     -0.5      0.6
rs3       ENSG00000227232       0.09      0.8       0.3

(All genes in values.gz should have a matching value in bed (but not 100% sure!), but the bed file will have more genes listed that do not match the values.gz file)

#! /usr/bin/env python
import gzip

lookup = dict()
my_file = open("bed.txt","r")
for line in my_file.readlines():
    row = line.split()
    lookup[row[3]] = row[1:]
    # print lookup
my_file.close()

with open('MyOutFile', 'w') as outfile:
    with gzip.open("values.gz", "r") as eqtl:
        for line in eqtl.readlines():
            for key in lookup:
                if line.find(key) > -1:
                    outfile.write(line)

After Paisanco's suggestions:

with gzip.open("values.gz", "r") as eqtl:
    for line in eqtl.readlines():
        row = line.split()
        gene = row[1]
        filename = gene+'.txt'
        if gene in lookup:
           # assign unique file name here, then
           if os.path.exists(filename):
               append_write = 'a'
           else:
               append_write = 'w'
           with open(filename,append_write) as outfile:
              outfile.write(line)

Body:
There are two things you can do here.

One, it looks like you are storing the quantity representing the geneID in your lookup table from the first file. If that quantity is the same type and value in the second file as in the first, you can search your lookup table more efficiently like this:

Code snippet:

for line in eqtl.readlines():
   row = line.split()
   if row[1] in lookup:
       # do something...

Two, if you wanted a unique name for each gene, your file open and write should be the inner loop, instead of the outer. Something like this:

with gzip.open("values.gz", "r") as eqtl:
    for line in eqtl.readlines():
        row = line.split()
        if row[1] in lookup:
           # assign unique file name here, then
           with open ("UniqueFileNameForThisGene","w") as outfile:
              outfile.write(line)

It would be up to you how you wanted to assign a unique file name for each gene - perhaps using other data in the line?


来源: stackexchange

问:
Bootstrap Input fields aren't centering

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div class="col-xs-12 text-center btn-group" data-toggle="buttons">
        <label class="btn btn-primary active">
            <input type="radio" name="measurement" value="far" checked="checked" /> F
        </label>
        <label class="btn btn-primary">
            <input type="radio" name="measurement" value="cel" /> C
        </label>
    </div>
</div></code>```

I'm not sure why it's left-aligned. I thought the text-center class center aligned anything? And since it's within a div that is col-xs-12, doesn't that make it center-aligned? Or what am I missing?

答:
The culprit is the btn-group. You need to move it to a div under the text-center. The code will look like;</p>

```<code>    <div class="row">
        <div class="col-xs-12 text-center" data-toggle="buttons">
             <div class="btn-group">
                 <label class="btn btn-primary active">
                     <input type="radio" name="measurement" value="far"
                     checked="checked" /> F
                 </label>
                 <label class="btn btn-primary">
                    <input type="radio" name="measurement" value="cel" /> C
                 </label>
            </div>
        </div>
    </div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bootstrap Input fields aren't centering

Body:
@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );

            <input type="radio" name="measurement" value="far" checked="checked" /> F

            <input type="radio" name="measurement" value="cel" /> C

I'm not sure why it's left-aligned. I thought the text-center class center aligned anything? And since it's within a div that is col-xs-12, doesn't that make it center-aligned? Or what am I missing?

Body:
The culprit is the btn-group. You need to move it to a div under the text-center. The code will look like;

    <div class="row">
        <div class="col-xs-12 text-center" data-toggle="buttons">
             <div class="btn-group">
                 <label class="btn btn-primary active">
                     <input type="radio" name="measurement" value="far"
                     checked="checked" /> F
                 </label>
                 <label class="btn btn-primary">
                    <input type="radio" name="measurement" value="cel" /> C
                 </label>
            </div>
        </div>
    </div>


问:
You must add a reference to assembly mscorlib, version=4.0.0
I'm having some trouble migrating a web project from RC1 to RC2. When I switched, I'm getting a bunch of these errors throughout the project.

The type 'Func<,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Looks like all of the linq functions and lambda expressions are not working.

This is what my project.json file looks like:

```<code>  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "System.Linq": "4.1.0-rc2-24027"
      },
      "imports": [ "net451", "portable-net45+win8" ]
    }
  },
  "dependencies": {
    "NETStandard.Library": "1.5.0-rc2-24027",
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "System.ComponentModel.Annotations": "4.1.0-*"
  }
</code>```

Any ideas what this means? I've tried running dotnet restore, did not help.

答:
In fact, the problem is an old lib that requires an asp.net 4.0 or 4.5 vesion (less than Core).

Microsoft provides a solution for it by installing the fallowing NuGet package.

Microsoft.NETCore.Portable.Compatibility

this way you will be able to run your code with old libs.

Body:
I'm having some trouble migrating a web project from RC1 to RC2. When I switched, I'm getting a bunch of these errors throughout the project.

The type 'Func<,>' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

Looks like all of the linq functions and lambda expressions are not working.

This is what my project.json file looks like:

  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "System.Linq": "4.1.0-rc2-24027"
      },
      "imports": [ "net451", "portable-net45+win8" ]
    }
  },
  "dependencies": {
    "NETStandard.Library": "1.5.0-rc2-24027",
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "System.ComponentModel.Annotations": "4.1.0-*"
  }

Any ideas what this means? I've tried running dotnet restore, did not help.


问:
A-Frame WASD controls substitute on mobile devices
I have an A-Frame multiplayer project, which relies on each user moving around the map, and it works well in desktop browsers. The stumbling block is the lack of motion controls in mobile, like the WASD-controls for the camera.

What workaround would you suggest? Perhaps, adding on-screen buttons and triggering keypress events with jQuery?

Or is there a more straightforward method of adding a function that would change the camera position for each on-screen button press? In this case, is there a way to find the exact functions attributed to the W, A, S, D keys?

Among several things I've tried was:

```<code>$(".up-button").click(function(){
  window.dispatchEvent(new KeyboardEvent('keypress',{keyCode: 38}));
</code>```

And another one:

```<code>var e = jQuery.Event("keydown");
e.which = 38;
$(window).trigger(e);
</code>```

Neither is producing any change.

答:
Have you tried something like:

```<code>window.dispatchEvent(new KeyboardEvent('keypress',{keyCode: 38} )  );
</code>```

to simulate pressing the up arrow key?

You could simulate pressing wasd or up down left right.
The rotation might be a little more tricky though,
you would have to simulate the onMouseDown and onMouseMove events.

Body:
I have an A-Frame multiplayer project, which relies on each user moving around the map, and it works well in desktop browsers. The stumbling block is the lack of motion controls in mobile, like the WASD-controls for the camera.

What workaround would you suggest? Perhaps, adding on-screen buttons and triggering keypress events with jQuery?

Or is there a more straightforward method of adding a function that would change the camera position for each on-screen button press? In this case, is there a way to find the exact functions attributed to the W, A, S, D keys?

Among several things I've tried was:

$(".up-button").click(function(){
  window.dispatchEvent(new KeyboardEvent('keypress',{keyCode: 38}));

And another one:

var e = jQuery.Event("keydown");
e.which = 38;
$(window).trigger(e);

Neither is producing any change.

Body:
Have you tried something like:

window.dispatchEvent(new KeyboardEvent('keypress',{keyCode: 38} )  );

to simulate pressing the up arrow key?

You could simulate pressing wasd or up down left right.
The rotation might be a little more tricky though,
you would have to simulate the onMouseDown and onMouseMove events.


问:
How to convert "commands module" into "subprocess module"?
I would like to know how to use "subprocess module" to rewrite the following code:

```<code>import commands
print commands.getoutput('convert -quality 100 ___t*.png images/transient_heat.gif')
print commands.getoutput('rm ___t*.png')
</code>```

Because "commands module" does not support Python 3, I would like to use "subprocess module". I tried the following code but it does not work.

```<code>import subprocess
print ( subprocess.Popen('convert -quality 100 ___t*.png images/transient_heat.gif') )
print ( subprocess.Popen('rm ___t*.png') )
</code>```

Thank you very much! The code was originally taken from Kitchin's blog: http://kitchingroup.cheme.cmu.edu/blog/2013/03/07/Transient-heat-conduction-partial-differential-equations/

答:
subprocess expects a list of strings that form the command. You could split your commands up by hand like so:

```<code>import subprocess
print(subprocess.Popen(['convert', '-quality', '100', '___t*.png', 'images/transient_heat.gif']))
print (subprocess.Popen(['rm', '___t*.png']))
</code>```

or, you could let shlex.split() do the work for you:

```<code>import shlex
import subprocess
print (subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif')))
print (subprocess.Popen(shlex.split('rm ___t*.png')))
</code>```

EDIT:

The following code will show you the output of stdout and stderr when it executes, which may help you fix any mistakes in your command line.

```<code>import shlex
import subprocess

convert_proc = subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outs, errs = convert_proc.communicate()
print('STDOUT: {}'.format(outs))
print('STDERR: {}'.format(errs))

subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif'))
print (subprocess.Popen(shlex.split('rm ___t*.png')))
</code>```

Body:
I would like to know how to use "subprocess module" to rewrite the following code:

import commands
print commands.getoutput('convert -quality 100 ___t*.png images/transient_heat.gif')
print commands.getoutput('rm ___t*.png')

Because "commands module" does not support Python 3, I would like to use "subprocess module". I tried the following code but it does not work.

import subprocess
print ( subprocess.Popen('convert -quality 100 ___t*.png images/transient_heat.gif') )
print ( subprocess.Popen('rm ___t*.png') )

Thank you very much! The code was originally taken from Kitchin's blog: http://kitchingroup.cheme.cmu.edu/blog/2013/03/07/Transient-heat-conduction-partial-differential-equations/

Body:
subprocess expects a list of strings that form the command. You could split your commands up by hand like so:

import subprocess
print(subprocess.Popen(['convert', '-quality', '100', '___t*.png', 'images/transient_heat.gif']))
print (subprocess.Popen(['rm', '___t*.png']))

or, you could let shlex.split() do the work for you:

import shlex
import subprocess
print (subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif')))
print (subprocess.Popen(shlex.split('rm ___t*.png')))

EDIT:

The following code will show you the output of stdout and stderr when it executes, which may help you fix any mistakes in your command line.

import shlex
import subprocess

convert_proc = subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif'), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outs, errs = convert_proc.communicate()
print('STDOUT: {}'.format(outs))
print('STDERR: {}'.format(errs))

subprocess.Popen(shlex.split('convert -quality 100 ___t*.png images/transient_heat.gif'))
print (subprocess.Popen(shlex.split('rm ___t*.png')))


问:
R/ RStudio - system path issue
I think I did some damage to my system path and now I am unable to knit in RStudio. I have the most current version of R and RStudio.

Here is what i'm working with

```<code>Sys.getenv()
</code>```

OUTPUT:

```<code>__CF_USER_TEXT_ENCODING        0x20C97408:0x0:0x0
Apple_PubSub_Socket_Render     /private/tmp/com.apple.launchd.g6i2lhsTBr/Render
DISPLAY                        :0
DYLD_FALLBACK_LIBRARY_PATH     /Library/Frameworks/R.framework/Resources/lib:/Users/lewa8222/lib:/usr/local/lib:/usr/lib::
EDITOR                         vi
GIT_ASKPASS                    rpostback-askpass
HOME                           /Users/lewa8222
LANG                           en_US.UTF-8
LC_CTYPE                       en_US.UTF-8
LN_S                           ln -s
LOGNAME                        lewa8222
MAKE                           make
PAGER                          /usr/bin/less
PATH                           :/Users/lewa8222/anaconda/bin/python/:/Users/lewa8222/anaconda/bin/python/:/Users/lewa8222/anaconda/bin/python:/Users/lewa8222/anaconda/bin/python:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Library/TeX/texbin
R_BROWSER                      /usr/bin/open
R_BZIPCMD                      /usr/bin/bzip2
R_DOC_DIR                      /Library/Frameworks/R.framework/Resources/doc
R_GZIPCMD                      /usr/bin/gzip
R_HOME                         /Library/Frameworks/R.framework/Resources
R_INCLUDE_DIR                  /Library/Frameworks/R.framework/Resources/include
R_LIBS_SITE
R_LIBS_USER                    ~/Library/R/3.3/library
R_PAPERSIZE                    a4
R_PDFVIEWER                    /usr/bin/open
R_PLATFORM                     x86_64-apple-darwin13.4.0
R_PRINTCMD                     lpr
R_QPDF                         /Library/Frameworks/R.framework/Resources/bin/qpdf
R_RD4PDF                       times,inconsolata,hyper
R_SESSION_TMPDIR               /var/folders/43/4q82487d5xsfpxdx6nl_c1wmhckx08/T//RtmpXOclp9
R_SHARE_DIR                    /Library/Frameworks/R.framework/Resources/share
R_SYSTEM_ABI                   osx,gcc,gxx,gfortran,?
R_TEXI2DVICMD                  /usr/local/bin/texi2dvi
R_UNZIPCMD                     /usr/bin/unzip
R_ZIPCMD                       /usr/bin/zip
RMARKDOWN_MATHJAX_PATH         /Applications/RStudio.app/Contents/Resources/resources/mathjax-26
RS_RPOSTBACK_PATH              /Applications/RStudio.app/Contents/MacOS/rpostback
RS_SHARED_SECRET               0255dad0-e77a-4d8c-bba9-0dc9e68fa0ff
RSTUDIO                        1
RSTUDIO_PANDOC                 /Applications/RStudio.app/Contents/MacOS/pandoc
RSTUDIO_SESSION_PORT           23768
RSTUDIO_USER_IDENTITY          lewa8222
RSTUDIO_WINUTILS               bin/winutils
SED                            /usr/bin/sed
SHELL                          /bin/bash
SSH_AUTH_SOCK                  /private/tmp/com.apple.launchd.X0TdgERzV2/Listeners
TAR                            /usr/bin/tar
TMPDIR                         /var/folders/43/4q82487d5xsfpxdx6nl_c1wmhckx08/T/
USER                           lewa8222
XPC_FLAGS                      0x0
XPC_SERVICE_NAME               0
</code>```

Notice the path

```<code>Sys.getenv("PATH")
</code>```

I was trying to link my anaconda version of python as the main python kernel in RStudio / RMarkdown.

To do this i used

```<code>Sys.setenv(PATH = paste("/Users/lewa8222/anaconda/bin/python/", Sys.getenv("PATH"), sep=":"))
</code>```

Not knowing that each time I think it was appending to my Path.

Now, when i try to knit a file using the knit button in rstudio it fails as follows:

```<code>Error: 1:11: unexpected '/'
1: .libPaths(/
              ^
Execution halted
</code>```

Any idea how I can fix this knitr error?

I have spent a lot of time on stack overflow and Rstudio help and can't seem to find a solution that works.
Thank you
Leah

UPDATE! Thanks to the answer below from @carsonfarmer

I had to

find my .Rprofile file. this was located in my home user directory on my MAC.

then i opened it with atom (use whatever text editor you'd like but i did
atom .Rprofile in my user dir where the file was.

when i opened it i noticed the text in the file was this:

.libPaths(/Users/lewa8222/anaconda/bin/python)

the comment below from @kevinushey was on track - i just didn't understand what libPaths was to know i had a file with a call to it somewhere.

.libPaths - notice that the path doesn't have quotes around it. Every time i loaded R i was getting this error but i didn't notice it.

I changed the path to:

.libPaths("/Users/lewa8222/anaconda/bin/python")

and magic happened. the error went away.
I hope this helps someone else and thank you everyone who helped me resolve this!!

答:
It sounds like @kevin-ushey was on the right track: Since knitr is basically running a new R instance each time you knit the document, it is loading your .RProfile each time (assuming you have one in your user dir), and I suspect your .RProfile has that offending .libPaths(/ call in it. Try editing your .RProfile file... it looks like all you need to do it wrap whatever offending path is in there in quotes :)

Running the following from an R terminal should tell you where your user .RProfile is: file.path(Sys.getenv("HOME"), ".Rprofile").

Title: R/ RStudio - system path issue

Body:
I think I did some damage to my system path and now I am unable to knit in RStudio. I have the most current version of R and RStudio.

Here is what i'm working with

Sys.getenv()

OUTPUT:

__CF_USER_TEXT_ENCODING        0x20C97408:0x0:0x0
Apple_PubSub_Socket_Render     /private/tmp/com.apple.launchd.g6i2lhsTBr/Render
DISPLAY                        :0
DYLD_FALLBACK_LIBRARY_PATH     /Library/Frameworks/R.framework/Resources/lib:/Users/lewa8222/lib:/usr/local/lib:/usr/lib::
EDITOR                         vi
GIT_ASKPASS                    rpostback-askpass
HOME                           /Users/lewa8222
LANG                           en_US.UTF-8
LC_CTYPE                       en_US.UTF-8
LN_S                           ln -s
LOGNAME                        lewa8222
MAKE                           make
PAGER                          /usr/bin/less
PATH                           :/Users/lewa8222/anaconda/bin/python/:/Users/lewa8222/anaconda/bin/python/:/Users/lewa8222/anaconda/bin/python:/Users/lewa8222/anaconda/bin/python:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Library/TeX/texbin
R_BROWSER                      /usr/bin/open
R_BZIPCMD                      /usr/bin/bzip2
R_DOC_DIR                      /Library/Frameworks/R.framework/Resources/doc
R_GZIPCMD                      /usr/bin/gzip
R_HOME                         /Library/Frameworks/R.framework/Resources
R_INCLUDE_DIR                  /Library/Frameworks/R.framework/Resources/include
R_LIBS_SITE
R_LIBS_USER                    ~/Library/R/3.3/library
R_PAPERSIZE                    a4
R_PDFVIEWER                    /usr/bin/open
R_PLATFORM                     x86_64-apple-darwin13.4.0
R_PRINTCMD                     lpr
R_QPDF                         /Library/Frameworks/R.framework/Resources/bin/qpdf
R_RD4PDF                       times,inconsolata,hyper
R_SESSION_TMPDIR               /var/folders/43/4q82487d5xsfpxdx6nl_c1wmhckx08/T//RtmpXOclp9
R_SHARE_DIR                    /Library/Frameworks/R.framework/Resources/share
R_SYSTEM_ABI                   osx,gcc,gxx,gfortran,?
R_TEXI2DVICMD                  /usr/local/bin/texi2dvi
R_UNZIPCMD                     /usr/bin/unzip
R_ZIPCMD                       /usr/bin/zip
RMARKDOWN_MATHJAX_PATH         /Applications/RStudio.app/Contents/Resources/resources/mathjax-26
RS_RPOSTBACK_PATH              /Applications/RStudio.app/Contents/MacOS/rpostback
RS_SHARED_SECRET               0255dad0-e77a-4d8c-bba9-0dc9e68fa0ff
RSTUDIO                        1
RSTUDIO_PANDOC                 /Applications/RStudio.app/Contents/MacOS/pandoc
RSTUDIO_SESSION_PORT           23768
RSTUDIO_USER_IDENTITY          lewa8222
RSTUDIO_WINUTILS               bin/winutils
SED                            /usr/bin/sed
SHELL                          /bin/bash
SSH_AUTH_SOCK                  /private/tmp/com.apple.launchd.X0TdgERzV2/Listeners
TAR                            /usr/bin/tar
TMPDIR                         /var/folders/43/4q82487d5xsfpxdx6nl_c1wmhckx08/T/
USER                           lewa8222
XPC_FLAGS                      0x0
XPC_SERVICE_NAME               0

Notice the path

Sys.getenv("PATH")

I was trying to link my anaconda version of python as the main python kernel in RStudio / RMarkdown.

To do this i used

Sys.setenv(PATH = paste("/Users/lewa8222/anaconda/bin/python/", Sys.getenv("PATH"), sep=":"))

Not knowing that each time I think it was appending to my Path.

Now, when i try to knit a file using the knit button in rstudio it fails as follows:

Error: 1:11: unexpected '/'
1: .libPaths(/
              ^
Execution halted

Any idea how I can fix this knitr error?

I have spent a lot of time on stack overflow and Rstudio help and can't seem to find a solution that works.
Thank you
Leah

UPDATE! Thanks to the answer below from @carsonfarmer

I had to

find my .Rprofile file. this was located in my home user directory on my MAC.

then i opened it with atom (use whatever text editor you'd like but i did
atom .Rprofile in my user dir where the file was.

when i opened it i noticed the text in the file was this:

.libPaths(/Users/lewa8222/anaconda/bin/python)

the comment below from @kevinushey was on track - i just didn't understand what libPaths was to know i had a file with a call to it somewhere.

.libPaths - notice that the path doesn't have quotes around it. Every time i loaded R i was getting this error but i didn't notice it.

I changed the path to:

.libPaths("/Users/lewa8222/anaconda/bin/python")

and magic happened. the error went away.
I hope this helps someone else and thank you everyone who helped me resolve this!!


问:
Spark DataSet filter performance
I have been experimenting different ways to filter a typed data set. It turns out the performance can be quite different.

The data set was created based on a 1.6 GB rows of data with 33 columns and 4226047 rows. DataSet is created by loading csv data and mapped to a case class.

```<code>val df = spark.read.csv(csvFile).as[FireIncident]
</code>```

A filter on UnitId = 'B02' should return 47980 rows. I tested three ways as below:
1) Use typed column (~ 500 ms on local host)

```<code>df.where($"UnitID" === "B02").count()
</code>```

2) Use temp table and sql query (~ same as option 1)

```<code>df.createOrReplaceTempView("FireIncidentsSF")
spark.sql("SELECT * FROM FireIncidentsSF WHERE UnitID='B02'").count()
</code>```

3) Use strong typed class field (14,987ms, i.e. 30 times as slow)

```<code>df.filter(_.UnitID.orNull == "B02").count()
</code>```

I tested it again with the python API, for the same data set, the timing is 17,046 ms, comparable to the performance of the scala API option 3.

```<code>df.filter(df['UnitID'] == 'B02').count()
</code>```

Could someone shed some light on how 3) and the python API are executed differently from the first two options?

答:
It's because of step 3 here.

In the first two, spark doesn't need to deserialize the whole Java/Scala object - it just looks at the one column and moves on.

In the third, since you're using a lambda function, spark can't tell that you just want the one field, so it pulls all 33 fields out of memory for each row, so that you can check the one field.

I'm not sure why the fourth is so slow. It seems like it would work the same way as the first.

Title: Spark DataSet filter performance

Body:
I have been experimenting different ways to filter a typed data set. It turns out the performance can be quite different.

The data set was created based on a 1.6 GB rows of data with 33 columns and 4226047 rows. DataSet is created by loading csv data and mapped to a case class.

val df = spark.read.csv(csvFile).as[FireIncident]

A filter on UnitId = 'B02' should return 47980 rows. I tested three ways as below:
1) Use typed column (~ 500 ms on local host)

df.where($"UnitID" === "B02").count()

2) Use temp table and sql query (~ same as option 1)

df.createOrReplaceTempView("FireIncidentsSF")
spark.sql("SELECT * FROM FireIncidentsSF WHERE UnitID='B02'").count()

3) Use strong typed class field (14,987ms, i.e. 30 times as slow)

df.filter(_.UnitID.orNull == "B02").count()

I tested it again with the python API, for the same data set, the timing is 17,046 ms, comparable to the performance of the scala API option 3.

df.filter(df['UnitID'] == 'B02').count()

Could someone shed some light on how 3) and the python API are executed differently from the first two options?

ContentLicense: CC BY-SA 4.0


问:
Playing audio files from desired folder
I have 5 folders and every folder contains 5 audio files. When Someone clicks on a folder, The program should start playing all the audio files  from that folder.
I am new to android, So i have a very little Idea about it.
I tried doing it, but it shows all the audio files together.
I want it to show folder wise.

```<code>fun abs(){

    var songsURI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    var selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"
    val cursor = contentResolver.query(songsURI,null,selection,null,null)
    if(cursor!= null)
    {
        if (cursor!!.moveToFirst()){

            do
            {
                var songURL = cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.DATA))
                        var songAuth =cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                                var SongNAme = cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.TITLE))
                listSongs.add(Songinfo(songURL,songAuth,SongNAme))

            }while (cursor!!.moveToNext())
        }
        cursor!!.close()

        adapter = MySongAdapter(listSongs)
        hello.adapter = adapter
    }

}
</code>```

Please Help

答:
Below code will give you the list of songs in each directory, you should change the adapter to show the directory name and the song list.

```<code>data class SongInfo(var songURL: String, var songAuth: String, var songNAme: String)
data class DirInfo(var dir: String, var songInfo: ArrayList<SongInfo>)

private fun getAudioDirectories(): ArrayList<DirInfo> {

    var result = ArrayList<DirInfo>()

    val directories = LinkedHashMap<String, ArrayList<SongInfo>>()

    val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    val selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"

    val order = MediaStore.Audio.Media.DATE_MODIFIED + " DESC"

    val cursor = getContentResolver().query(uri, null, selection, null, order)

    cursor.let {
        it.moveToFirst()

        val pathIndex = it.getColumnIndex(MediaStore.Images.Media.DATA)

        do {
            val path = it.getString(pathIndex)

            val file = File(path)
            if (!file.exists()) {
                continue
            }

            val fileDir = file.getParent()

            var songURL = it.getString(it.getColumnIndex(MediaStore.Audio.Media.DATA))
            var songAuth = it.getString(it.getColumnIndex(MediaStore.Audio.Media.ARTIST))
            var songName = it.getString(it.getColumnIndex(MediaStore.Audio.Media.TITLE))

            if (directories.containsKey(fileDir)) {
                var songs = directories.getValue(fileDir);

                var song = SongInfo(songURL, songAuth, songName)

                songs.add(song)

                directories.put(fileDir, songs)
            } else {
                var song = SongInfo(songURL, songAuth, songName)

                var songs = ArrayList<SongInfo>()
                songs.add(song)

                directories.put(fileDir, songs)
            }
        } while (it.moveToNext())

        for (dir in directories) {
            var dirInfo: DirInfo = DirInfo(dir.key, dir.value);

            result.add(dirInfo)
        }
    }

    return result
}
</code>```

Using your Adapter we can't show list of Album with songs list, you can use this or you can take any of these libs from Android-Arsenal

Title: Playing audio files from desired folder

Body:
I have 5 folders and every folder contains 5 audio files. When Someone clicks on a folder, The program should start playing all the audio files  from that folder.
I am new to android, So i have a very little Idea about it.
I tried doing it, but it shows all the audio files together.
I want it to show folder wise.

fun abs(){

    var songsURI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    var selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"
    val cursor = contentResolver.query(songsURI,null,selection,null,null)
    if(cursor!= null)
    {
        if (cursor!!.moveToFirst()){

            do
            {
                var songURL = cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.DATA))
                        var songAuth =cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                                var SongNAme = cursor!!.getString(cursor!!.getColumnIndex(MediaStore.Audio.Media.TITLE))
                listSongs.add(Songinfo(songURL,songAuth,SongNAme))

            }while (cursor!!.moveToNext())
        }
        cursor!!.close()

        adapter = MySongAdapter(listSongs)
        hello.adapter = adapter
    }

}

Please Help

Body:
Below code will give you the list of songs in each directory, you should change the adapter to show the directory name and the song list.

data class SongInfo(var songURL: String, var songAuth: String, var songNAme: String)
data class DirInfo(var dir: String, var songInfo: ArrayList<SongInfo>)

private fun getAudioDirectories(): ArrayList<DirInfo> {

    var result = ArrayList<DirInfo>()

    val directories = LinkedHashMap<String, ArrayList<SongInfo>>()

    val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    val selection = MediaStore.Audio.Media.IS_MUSIC + "!=0"

    val order = MediaStore.Audio.Media.DATE_MODIFIED + " DESC"

    val cursor = getContentResolver().query(uri, null, selection, null, order)

    cursor.let {
        it.moveToFirst()

        val pathIndex = it.getColumnIndex(MediaStore.Images.Media.DATA)

        do {
            val path = it.getString(pathIndex)

            val file = File(path)
            if (!file.exists()) {
                continue
            }

            val fileDir = file.getParent()

            var songURL = it.getString(it.getColumnIndex(MediaStore.Audio.Media.DATA))
            var songAuth = it.getString(it.getColumnIndex(MediaStore.Audio.Media.ARTIST))
            var songName = it.getString(it.getColumnIndex(MediaStore.Audio.Media.TITLE))

            if (directories.containsKey(fileDir)) {
                var songs = directories.getValue(fileDir);

                var song = SongInfo(songURL, songAuth, songName)

                songs.add(song)

                directories.put(fileDir, songs)
            } else {
                var song = SongInfo(songURL, songAuth, songName)

                var songs = ArrayList<SongInfo>()
                songs.add(song)

                directories.put(fileDir, songs)
            }
        } while (it.moveToNext())

        for (dir in directories) {
            var dirInfo: DirInfo = DirInfo(dir.key, dir.value);

            result.add(dirInfo)
        }
    }

    return result
}

Using your Adapter we can't show list of Album with songs list, you can use this or you can take any of these libs from Android-Arsenal


问:
Selecting documents with empty strings in RavenDB Studio
This ought to be simple enough, but I can't get a select statement going in RavenDB Studio where I say "give me all documents where field NAME_x is empty".
The usual suspects don't yield anything:

```<code>NAME_5:[[EMPTY_STRING]]
</code>```

NOT NAME_5:[[EMPTY_STRING]] (just to see if the logic was backwards somehow)

```<code>NAME_5: [[NULL_VALUE]]
</code>```

The index DOES include all fields (NAME_0 through NAME_5) and there ARE plenty of records that have this

```<code>(...)
"NAME_5": "",
(...)
</code>```

so my quesion is - why don't they show up ? I guess the query's syntax is wrong, but I don't know where/how.
Thanks for a hint !

答:
This should just work.
See: http://live-test.ravendb.net/studio/index.html#databases/query/index/recentquery--187795092?&database=44438301

Here is what I get when I try.

Body:
This ought to be simple enough, but I can't get a select statement going in RavenDB Studio where I say "give me all documents where field NAME_x is empty".
The usual suspects don't yield anything:

NAME_5:[[EMPTY_STRING]]

NOT NAME_5:[[EMPTY_STRING]] (just to see if the logic was backwards somehow)

NAME_5: [[NULL_VALUE]]

The index DOES include all fields (NAME_0 through NAME_5) and there ARE plenty of records that have this

(...)
"NAME_5": "",
(...)

so my quesion is - why don't they show up ? I guess the query's syntax is wrong, but I don't know where/how.
Thanks for a hint !


问:
How can I remove a chunk of text from a Javascript string?
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

```<code>Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."]<a href="http://www.google.com/something"><img title="Lorem ipsum dolor sit, consectetur adipiscing elit." src="http://google.com/something/else.png" alt="Lorem ipsum dolor sit, consectetur adipiscing elit." width="345" /></a>[/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.
</code>```

答:
You can also use a regex:

```<code>var split = text.split(/\[\/?caption[^\]]*\]/);
</code>```

and take split[1] as result

ContentLicense: CC BY-SA 2.5

Body:
I am trying to analyze a piece of text via JavaScript and, reading up, have learned that parsing HTML with Regex is quite evil. I'd like to remove a more sinister part of my text before I analyze it.

If I've got a chunk of text like the item below, how might I (1) slice everything from [caption] to [/caption] and (2) store that text in a new var?

Sed rutrum enim sit amet sem fringilla egestas placerat mauris pretium. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris ultricies egestas malesuada. Etiam rhoncus eros a leo imperdiet vitae tincidunt purus laoreet. Mauris ut mauris quam, sed pharetra urna. Etiam eu enim mauris, vitae bibendum orci. Quisque ac sapien massa, at dignissim tellus.

[caption id="blah" align="alignleft" width="123" caption="Lorem ipsum dolor sit, consectetur adipiscing elit."][/caption]

Aenean faucibus mi sit amet leo suscipit nec egestas leo ultrices. Integer tincidunt, urna quis varius accumsan, urna quam congue nulla, ut ornare orci purus in ligula. Suspendisse varius, tellus aliquam tincidunt, ante semper elit, sit amet tincidunt elit augue eget odio. Vivamus sit amet tincidunt massa. Sed nunc ligula, feugiat quis volutpat congue, eleifend in tellus. Curabitur ut dictum felis. Nunc sodales euismod leo, in commodo elit ornare hendrerit. Cras luctus eros id nisl vestibulum elementum. Maecenas ut neque turpis. Donec ornare hendrerit rutrum. Non nibh leo, dictum ullamcorper dui.

Body:
You can also use a regex:

var split = text.split(/\[\/?caption[^\]]*\]/);

and take split[1] as result


问:
Use host list and run a command on one host for each host in list
I'm trying to figure out how you can use the host inventory in Ansible and run a command of each host but on only one of the hosts.

for instance...

if my inventory file looks like this:

```<code>[data]
data1
data2
data3

[meta]
meta1
meta2
meta3
meta4
</code>```

what I'm trying to do is run something like this on just node data1:

```<code>- name: Run this on data1
  command: "someCmd.sh -arg1 {{ item }}"
  with_items:
    - "data1"
    - "data2"
    - "data3"
    - "data4"
</code>```

I know I wouldn't explicilty get the list like that..just trying to show what I want to do. So how do I loop through the list of data hosts and run a command?

答:
I'm not sure if I understand the description correctly, but the following seems like the answer:</p>

```<code>- name: Run this on data1
  command: "someCmd.sh -arg1 {{ item }}"
  delegate_to: data1
  run_once: true
  with_items:
    - "{{ groups['data'] }}"
</code>```

Body:
I'm trying to figure out how you can use the host inventory in Ansible and run a command of each host but on only one of the hosts.

for instance...

if my inventory file looks like this:

[data]
data1
data2
data3

[meta]
meta1
meta2
meta3
meta4

what I'm trying to do is run something like this on just node data1:

- name: Run this on data1
  command: "someCmd.sh -arg1 {{ item }}"
  with_items:
    - "data1"
    - "data2"
    - "data3"
    - "data4"

I know I wouldn't explicilty get the list like that..just trying to show what I want to do. So how do I loop through the list of data hosts and run a command?

Body:
I'm not sure if I understand the description correctly, but the following seems like the answer:

- name: Run this on data1
  command: "someCmd.sh -arg1 {{ item }}"
  delegate_to: data1
  run_once: true
  with_items:
    - "{{ groups['data'] }}"


问:
Get and set preference values
My objective is manage my custom preferences. For this, I have the following code:

MainActivity.java

```<code>public class MainActivity extends ActionBarActivity implements View.OnTouchListener, GoogleMap.OnInfoWindowClickListener, LocationListener, GoogleMap.OnMapClickListener{

             public boolean onOptionsItemSelected(MenuItem item) {
                int id = item.getItemId();

                if (id == R.id.action_settings) {
                    launchPreferences(null);
                    return true;
                }

                return super.onOptionsItemSelected(item);
            }
            public void launchPreferences(View view) {
                Intent i = new Intent(this, Preferences.class);
                startActivity(i);
            }
    }
</code>```

Preferences.java

```<code>public class Preferences extends PreferenceActivity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        updatePreference();

    }
</code>```

settings.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="@+id/preferencias_principal" >
    <EditTextPreference
        android:key="@+id/perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="@+id/leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>
</code>```

arrays.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="lenguage">
        <item>English</item>
        <item>Basque</item>
        <item>Spanish</item>
    </string-array>
    <string-array name="lenguageva">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>

    <string-array name="number">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
        <item>13</item>
        <item>14</item>
        <item>15</item>
    </string-array>

</resources>
</code>```

I want to get the values of this preference, using this code:

```<code>SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Integer peri = sharedPref.getInt("@+id/perimer", 1);
Integer leng = sharedPref.getInt("@+id/leguage", 2);
</code>```

But this code return default values, peri=1 and leng=2.

Not only that, sometimes the information added by the preference activity is changed/deleted or in the ListPreference item is not appear the default item selected (as you can be seen in the image).

When I execute the code visible here, with debugger, this is the result:

What can I do?

Thank you!

答:
The main problem is the KEY @+id/perimer and @+id/leguage that you used for your EditTextPreference and ListPreference.

SharedPreferences is unable to recognize it as preference KEY. As you added resource prefix @+id, its treated as int resource id that's why still it works with below lines but doing abnormal behavior and giving you incorrect output.

```<code>    Integer peri = sharedPref.getInt("@+id/perimer", 1); // WRONG
    Integer leng = sharedPref.getInt("@+id/leguage", 2); // WRONG
</code>```

SOLUTION:

1. Do not use resource prefix @+id with preference KEY. Update your settings.xml as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <EditTextPreference
        android:key="perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>
</code>```

2. Get preference values using SharedPreferences.getString(KEY_NAME, DEFAULT_VALUE).

```<code>    // Get current values
    String peri = mSharedPreferences.getString("perimer", "1");
    String leng = mSharedPreferences.getString("leguage", "2");
</code>```

3. Add OnPreferenceChangeListener to your preferences to get the updated values and update the preference summary if needed.

```<code>    // Required to get the updated value and update summary when you input distance
    mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String peri = value.toString();

            //Update premier summary
            mPreferencePerimer.setSummary(peri);

            return true;
        }
    });

    // Required to get the updated value and update summary when you change language from list
    mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {

            String leng = value.toString();
            int lengIndex = Integer.parseInt(leng) - 1;

            // Update leguage summary
            mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
            return true;
        }
    });
</code>```

Here is the full code:

```<code>public class Preferences extends PreferenceActivity {

    // Preference Keys
    public static final String KEY_PREF_PERIMER = "perimer";
    public static final String KEY_PREF_LEGUAGE = "leguage";

    // Shared preference
    SharedPreferences mSharedPreferences;

    EditTextPreference mPreferencePerimer;
    ListPreference mPreferenceLeguage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        // Shared preference
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        // Perimer
        mPreferencePerimer = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_PERIMER);
        // Leguage
        mPreferenceLeguage = (ListPreference) getPreferenceScreen().findPreference(KEY_PREF_LEGUAGE);

        // Get current values
        String peri = mSharedPreferences.getString(KEY_PREF_PERIMER, "1");
        String leng = mSharedPreferences.getString(KEY_PREF_LEGUAGE, "2");
        int lengIndex = Integer.parseInt(leng) - 1;

        // Set preference summary
        mPreferencePerimer.setSummary(peri);
        mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);

        // Required to get the updated value and update summary when you input distance
        mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {
                String peri = value.toString();

                //Update premier summary
                mPreferencePerimer.setSummary(peri);

                return true;
            }
        });

        // Required to get the updated value and update summary when you change language from list
        mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {

                String leng = value.toString();
                int lengIndex = Integer.parseInt(leng) - 1;

                // Update leguage summary
                mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
                return true;
            }
        });
    }
}
</code>```

OUTPUT:

DEFAULT STATE

AFTER CHANGE

Hope this will help~

Title: Get and set preference values

Body:
My objective is manage my custom preferences. For this, I have the following code:

MainActivity.java

public class MainActivity extends ActionBarActivity implements View.OnTouchListener, GoogleMap.OnInfoWindowClickListener, LocationListener, GoogleMap.OnMapClickListener{

             public boolean onOptionsItemSelected(MenuItem item) {
                int id = item.getItemId();

                if (id == R.id.action_settings) {
                    launchPreferences(null);
                    return true;
                }

                return super.onOptionsItemSelected(item);
            }
            public void launchPreferences(View view) {
                Intent i = new Intent(this, Preferences.class);
                startActivity(i);
            }
    }

Preferences.java

public class Preferences extends PreferenceActivity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        updatePreference();

    }

settings.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="@+id/preferencias_principal" >
    <EditTextPreference
        android:key="@+id/perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="@+id/leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="lenguage">
        <item>English</item>
        <item>Basque</item>
        <item>Spanish</item>
    </string-array>
    <string-array name="lenguageva">
        <item>1</item>
        <item>2</item>
        <item>3</item>
    </string-array>

    <string-array name="number">
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
        <item>6</item>
        <item>7</item>
        <item>8</item>
        <item>9</item>
        <item>10</item>
        <item>11</item>
        <item>12</item>
        <item>13</item>
        <item>14</item>
        <item>15</item>
    </string-array>

</resources>

I want to get the values of this preference, using this code:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Integer peri = sharedPref.getInt("@+id/perimer", 1);
Integer leng = sharedPref.getInt("@+id/leguage", 2);

But this code return default values, peri=1 and leng=2.

Not only that, sometimes the information added by the preference activity is changed/deleted or in the ListPreference item is not appear the default item selected (as you can be seen in the image).

When I execute the code visible here, with debugger, this is the result:

What can I do?

Thank you!

Body:
The main problem is the KEY @+id/perimer and @+id/leguage that you used for your EditTextPreference and ListPreference.

SharedPreferences is unable to recognize it as preference KEY. As you added resource prefix @+id, its treated as int resource id that's why still it works with below lines but doing abnormal behavior and giving you incorrect output.

    Integer peri = sharedPref.getInt("@+id/perimer", 1); // WRONG
    Integer leng = sharedPref.getInt("@+id/leguage", 2); // WRONG

SOLUTION:

1. Do not use resource prefix @+id with preference KEY. Update your settings.xml as below:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <EditTextPreference
        android:key="perimer"
        android:title="Perimeter to list"
        android:summary="Maximum distance to list"
        android:defaultValue="2"/>
    <ListPreference
        android:key="leguage"
        android:title="Lenguage"
        android:summary="What language would you apply?"
        android:entries="@array/lenguage"
        android:entryValues="@array/lenguageva"
        android:defaultValue="1"/>

</PreferenceScreen>

2. Get preference values using SharedPreferences.getString(KEY_NAME, DEFAULT_VALUE).

    // Get current values
    String peri = mSharedPreferences.getString("perimer", "1");
    String leng = mSharedPreferences.getString("leguage", "2");

3. Add OnPreferenceChangeListener to your preferences to get the updated values and update the preference summary if needed.

    // Required to get the updated value and update summary when you input distance
    mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String peri = value.toString();

            //Update premier summary
            mPreferencePerimer.setSummary(peri);

            return true;
        }
    });

    // Required to get the updated value and update summary when you change language from list
    mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {

            String leng = value.toString();
            int lengIndex = Integer.parseInt(leng) - 1;

            // Update leguage summary
            mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
            return true;
        }
    });

Here is the full code:

public class Preferences extends PreferenceActivity {

    // Preference Keys
    public static final String KEY_PREF_PERIMER = "perimer";
    public static final String KEY_PREF_LEGUAGE = "leguage";

    // Shared preference
    SharedPreferences mSharedPreferences;

    EditTextPreference mPreferencePerimer;
    ListPreference mPreferenceLeguage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        // Shared preference
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        // Perimer
        mPreferencePerimer = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_PERIMER);
        // Leguage
        mPreferenceLeguage = (ListPreference) getPreferenceScreen().findPreference(KEY_PREF_LEGUAGE);

        // Get current values
        String peri = mSharedPreferences.getString(KEY_PREF_PERIMER, "1");
        String leng = mSharedPreferences.getString(KEY_PREF_LEGUAGE, "2");
        int lengIndex = Integer.parseInt(leng) - 1;

        // Set preference summary
        mPreferencePerimer.setSummary(peri);
        mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);

        // Required to get the updated value and update summary when you input distance
        mPreferencePerimer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {
                String peri = value.toString();

                //Update premier summary
                mPreferencePerimer.setSummary(peri);

                return true;
            }
        });

        // Required to get the updated value and update summary when you change language from list
        mPreferenceLeguage.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {

                String leng = value.toString();
                int lengIndex = Integer.parseInt(leng) - 1;

                // Update leguage summary
                mPreferenceLeguage.setSummary(mPreferenceLeguage.getEntries()[lengIndex]);
                return true;
            }
        });
    }
}

OUTPUT:

DEFAULT STATE

AFTER CHANGE

Hope this will help~


问:
ASP.NET Core 5.0 error CS0012: The type 'Object' is defined in assembly 'mscorlib
In Visual Studio 2015 I have a kproj, in this project I wanted to add a reference to an assembly that is not available in any public nuget package source, so I've created my own nuget package and this way was able to add the reference to this assembly.

The problem is that now I'm getting the following exception:

ASP.NET Core 5.0 error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Any ideas on how to overcome this?

答:
In fact, the problem is an old lib that requires an asp.net 4.0 or 4.5 vesion (less than Core).

Microsoft provides a solution for it by installing the fallowing NuGet package.

PM> Install-package Microsoft.NETCore.Portable.Compatibility

this way you will be able to run your code with old libs.


问:
HTML toggle colors in elements with every element going through the same colors
Consider this code:

```<code>var counter = 0;
function changeColor(elem) {

  var colors = ["Red", "Green", "Blue", "Orange", "Yellow", "Cyan"];
  elem.style.color = colors[counter];
  counter++;
  if (counter === colors.length) {
    counter = 0;
  }
}
</code>```

I want to make elements which will go through the array of colors, changing everytime per click. The script works, but when I click an element 2 times, and then jump to another element and click there, it will resume the 3rd color instead of going back to the first one. I know that it's because of the global counter variable, but placing it into the function causes it to reset and thus making the colors only change to "red".

I'm not sure how to tackle the problem, Im also using a this context for the elements in HTML:

```<code> <div>
      <p onclick="changeColor(this)">Hello</p>
      <p onclick="changeColor(this)">Bye</p>
      <p onclick="changeColor(this)">I love you!</p>
    </div>
</code>```

Thanks in advance,
Cheers!

答:
Each elem is a DOM-node (
-tag) object, since it is an object you can set any property you wish like counter:

function changeColor(elem) {
  var colors = ["Red", "Green", "Blue", "Orange", "Yellow", "Cyan"];
  var lastIndex = colors.length - 1;

  if (elem.counter === undefined || elem.counter == lastIndex) {
    elem.counter = 0;
  }
  else {
    elem.counter++;
  }

  elem.style.color = colors[elem.counter];
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p onclick="changeColor(this)">Hello</p>
  <p onclick="changeColor(this)">Bye</p>
  <p onclick="changeColor(this)">I love you!</p>
</div></code>```

Body:
Consider this code:

var counter = 0;
function changeColor(elem) {

  var colors = ["Red", "Green", "Blue", "Orange", "Yellow", "Cyan"];
  elem.style.color = colors[counter];
  counter++;
  if (counter === colors.length) {
    counter = 0;
  }
}

I want to make elements which will go through the array of colors, changing everytime per click. The script works, but when I click an element 2 times, and then jump to another element and click there, it will resume the 3rd color instead of going back to the first one. I know that it's because of the global counter variable, but placing it into the function causes it to reset and thus making the colors only change to "red".

I'm not sure how to tackle the problem, Im also using a this context for the elements in HTML:

Hello

Bye

I love you!

Thanks in advance,
Cheers!

Body:
Each elem is a DOM-node (<p>-tag) object, since it is an object you can set any property you wish like counter:

function changeColor(elem) {
  var colors = ["Red", "Green", "Blue", "Orange", "Yellow", "Cyan"];
  var lastIndex = colors.length - 1;

  if (elem.counter === undefined || elem.counter == lastIndex) {
    elem.counter = 0;
  }
  else {
    elem.counter++;
  }

  elem.style.color = colors[elem.counter];
};

<div>
  <p onclick="changeColor(this)">Hello</p>
  <p onclick="changeColor(this)">Bye</p>
  <p onclick="changeColor(this)">I love you!</p>
</div>


问:
oracle db column date default value not sysdate
how to set the default value for a date column for something diferent that sysdate? like 01/07/1998, im currently using</p>

```<code>ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT sysdate NOT NULL);
</code>```

答:
Just use a fixed date, either with to_date() with a string literal and matching format model, or a date literal:

```<code>ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT DATE '1998-07-01' NOT NULL);
</code>```

(assuming your example was in DD/MM/YYYY format; date literals are unambiguous, which is another advantage of using them.)

Body:
how to set the default value for a date column for something diferent that sysdate? like 01/07/1998, im currently using

ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT sysdate NOT NULL);

Body:
Just use a fixed date, either with to_date() with a string literal and matching format model, or a date literal:

ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT DATE '1998-07-01' NOT NULL);

(assuming your example was in DD/MM/YYYY format; date literals are unambiguous, which is another advantage of using them.)


答:
You should make use of groups variable and use a proper host inside your playbook. Something like:</p>

```<code>- hosts: data1
  tasks:
    - name: Run this on data1
      command: "someCmd.sh -arg1 {{ item }}"
      with_items: "{{ groups['data'] }}"
</code>```

Title: Use host list and run a command on one host for each host in list

Body:
You should make use of groups variable and use a proper host inside your playbook. Something like:

- hosts: data1
  tasks:
    - name: Run this on data1
      command: "someCmd.sh -arg1 {{ item }}"
      with_items: "{{ groups['data'] }}"


问:
Grab where CURDATE() and the day before with MySQL
```<code>offers.date = CURDATE()
</code>```

I what I currently have.

It grabs offers for today, but I also would like to grab the orders for yesterday.

How can I do this, without specifying the yesterday's date?

答:
It could also be </p>

```<code>  offers.date between (current_date() - interval 1 day) and current_date
</code>```

<p>NB: that this will fail if offers.date is a datetime value because (2017-01-02) < (2017-01-02 12:34:56) due to the fact 2017-01-02 is actually 2017-01-02 00:00:00.  </p>

Body:
offers.date = CURDATE()

I what I currently have.

It grabs offers for today, but I also would like to grab the orders for yesterday.

How can I do this, without specifying the yesterday's date?

Body:
It could also be

  offers.date between (current_date() - interval 1 day) and current_date

NB: that this will fail if offers.date is a datetime value because (2017-01-02) < (2017-01-02 12:34:56) due to the fact 2017-01-02 is actually 2017-01-02 00:00:00.


问:
powershell log - new file every day
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

```<code>$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}
</code>```

答:
I would suggest including the date/time (yyyy-MM-dd_HH-mm-ss) in the log file name (to prevent duplicate file names) and scheduling your script to run daily / hourly or whenever. Just tell the task scheduler service to end the task if it runs for X number of hours, where X is right before it is scheduled to start again. This should give you the intended result of a new file on the schedule you decide is best. This also ensures your script continues running even if the computer reboots.

If the size of the log file is your main issue, then I would suggest starting a new file based on the file size and not the date. This way you can choose exactly what size files you want to work with.

To do this, just change while($true) to while((Get-Item $log_file).Length -lt "100000") where the length is the size in bytes that you want the script to stop at.

To make your script create a new log file when the while statement is triggered, just wrap it in a function and then call the function using another while $true statement.

Here is the change:

```<code>function NetworkLogging {
    $log_file = "$PSScriptRoot\network_" + (Get-Date -f yyyy-MM-dd_HH-mm-ss) + ".log"
    $server = "server.com"
    $gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
    & ipconfig /all >> $log_file

    while((Get-Item $log_file).Length -lt "100000") {
    $timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
    $timestamp >> $log_file
    "rnrn" >> $log_file
    "ping to $server)" >> $log_file
    & ping $server >> $log_file
    }
}

while ($true){NetworkLogging}
</code>```

Title: powershell log - new file every day

Body:
I log network status (nslookup, ping, tracert) into a log file. The log file size grows and is quite difficult to work with after a while.

I am looking for a way to have a new log file created for every day. I am sure it's easy but I did not find a way.

When I set log file name to $log_file = ".\network_" + (Get-Date -f yyyy-MM-dd) + ".log" hoping it will create a new file when date changes, it does not work. Instead I get Non-authoritative answer:.

Sorry for newbie question but I really did not find any answer. Thx!

edit:

it's really simple script (shortened example below):

$log_file = ".\network_" + (Get-Date -f yyyy-MM-dd_HH-mm) + ".log"
$server = "server.com"
$gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
& ipconfig /all >> $log_file

while($true) {
$timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
$timestamp >> $log_file
"rnrn" >> $log_file
"ping to $server)" >> $log_file
& ping $server >> $log_file
}

Body:
I would suggest including the date/time (yyyy-MM-dd_HH-mm-ss) in the log file name (to prevent duplicate file names) and scheduling your script to run daily / hourly or whenever. Just tell the task scheduler service to end the task if it runs for X number of hours, where X is right before it is scheduled to start again. This should give you the intended result of a new file on the schedule you decide is best. This also ensures your script continues running even if the computer reboots.

If the size of the log file is your main issue, then I would suggest starting a new file based on the file size and not the date. This way you can choose exactly what size files you want to work with.

To do this, just change while($true) to while((Get-Item $log_file).Length -lt "100000") where the length is the size in bytes that you want the script to stop at.

To make your script create a new log file when the while statement is triggered, just wrap it in a function and then call the function using another while $true statement.

Here is the change:

function NetworkLogging {
    $log_file = "$PSScriptRoot\network_" + (Get-Date -f yyyy-MM-dd_HH-mm-ss) + ".log"
    $server = "server.com"
    $gateway = (Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
    & ipconfig /all >> $log_file

    while((Get-Item $log_file).Length -lt "100000") {
    $timestamp = "rnrn[" + (Get-Date -f yyyy-MM-dd) + " " +(Get-Date -f HH:mm:ss) + "]"
    $timestamp >> $log_file
    "rnrn" >> $log_file
    "ping to $server)" >> $log_file
    & ping $server >> $log_file
    }
}

while ($true){NetworkLogging}


问:
How do I UPDATE from a SELECT in Informix?
I'm trying to do an update using data from another table. I've tried this answer (the second part), but it is not working for me. I'm receiving a generic error message of syntax error.

I've also tried this solution and received a syntax error message too.

If I try to update just one column, it works:

```<code>UPDATE dogs
SET name =
    (
        SELECT 'Buddy'
        FROM systables
        WHERE tabid = 1
     );
</code>```

But I need to update multiples columns. Unfortunately, this is not working:

```<code>UPDATE dogs
SET (name, breed) =
    (
        SELECT 'Buddy', 'pug'
        FROM systables
        WHERE tabid = 1
    );
</code>```

Informix version is 12.10.FC8

答:
You are missing 1 more set of parentheses around the subquery.
From the Informix manual:

The subquery must be enclosed between parentheses. These parentheses
  are nested within the parentheses that immediately follow the equal (
  = ) sign. If the expression list includes multiple subqueries, each subquery must be enclosed between parentheses, with a comma ( , )
  separating successive subqueries:

```<code>UPDATE ... SET ... = ((subqueryA),(subqueryB), ... (subqueryN))
</code>```

The following examples show the use of subqueries in the SET clause:

```<code>UPDATE items
SET (stock_num, manu_code, quantity) =
  (
    (
      SELECT stock_num, manu_code
       FROM stock
       WHERE description = 'baseball'
    ),
    2
  )
WHERE item_num = 1 AND order_num = 1001;

UPDATE table1
SET (col1, col2, col3) =
  (
    (
      SELECT MIN (ship_charge), MAX (ship_charge)
      FROM orders
    ),
    '07/01/2007'
  )
WHERE col4 = 1001;
</code>```

So in order for your update to be accepted by Informix it has to be:

```<code>UPDATE dogs
SET (name, breed) =
  (
    (
      SELECT 'Buddy', 'pug'
      FROM systables
      WHERE tabid = 1
    )
  );
</code>```

Body:
I'm trying to do an update using data from another table. I've tried this answer (the second part), but it is not working for me. I'm receiving a generic error message of syntax error.

I've also tried this solution and received a syntax error message too.

If I try to update just one column, it works:

UPDATE dogs
SET name =
    (
        SELECT 'Buddy'
        FROM systables
        WHERE tabid = 1
     );

But I need to update multiples columns. Unfortunately, this is not working:

UPDATE dogs
SET (name, breed) =
    (
        SELECT 'Buddy', 'pug'
        FROM systables
        WHERE tabid = 1
    );

Informix version is 12.10.FC8

Body:
You are missing 1 more set of parentheses around the subquery.
From the Informix manual:

The subquery must be enclosed between parentheses. These parentheses
  are nested within the parentheses that immediately follow the equal (
  = ) sign. If the expression list includes multiple subqueries, each subquery must be enclosed between parentheses, with a comma ( , )
  separating successive subqueries:

UPDATE ... SET ... = ((subqueryA),(subqueryB), ... (subqueryN))

The following examples show the use of subqueries in the SET clause:

UPDATE items
SET (stock_num, manu_code, quantity) =
  (
    (
      SELECT stock_num, manu_code
       FROM stock
       WHERE description = 'baseball'
    ),
    2
  )
WHERE item_num = 1 AND order_num = 1001;

UPDATE table1
SET (col1, col2, col3) =
  (
    (
      SELECT MIN (ship_charge), MAX (ship_charge)
      FROM orders
    ),
    '07/01/2007'
  )
WHERE col4 = 1001;

So in order for your update to be accepted by Informix it has to be:

UPDATE dogs
SET (name, breed) =
  (
    (
      SELECT 'Buddy', 'pug'
      FROM systables
      WHERE tabid = 1
    )
  );


问:
Solving Brute force algorithm without itertools function
Assuming 1211 and "baba" is your pin and password.

Write two different functions that keeps looping until it gets the pin and password respectively.

i managed to write something using the itertools function but my tutor said not to use it and i should look for another way, i've only been coding for two weeks, so my understanding of python isn't wide and would really appreciate some advice. I'm really sorry about how messy my question is, this is my first time using this.

```<code>    import itertools
    import string

    for guess in itertools.product(string.lowercase, repeat=6):
      if checkguess(''.join(guess)):
        print("Password is: {0}".format(''.join(guess)))
</code>```

答:
You can use for-loop to try different combinations and find the pin or password, this is an example for the PIN:

```<code>pin = 1211
rng = int(len(str(pin)) * str(9))
for i in xrange(rng):
    if i == pin:
        print('pin is: {}'.format(i))
        break
</code>```

you can start with it and try to figure out how to do the rest :)

Body:
Assuming 1211 and "baba" is your pin and password.

Write two different functions that keeps looping until it gets the pin and password respectively.

i managed to write something using the itertools function but my tutor said not to use it and i should look for another way, i've only been coding for two weeks, so my understanding of python isn't wide and would really appreciate some advice. I'm really sorry about how messy my question is, this is my first time using this.

    import itertools
    import string

    for guess in itertools.product(string.lowercase, repeat=6):
      if checkguess(''.join(guess)):
        print("Password is: {0}".format(''.join(guess)))

Body:
You can use for-loop to try different combinations and find the pin or password, this is an example for the PIN:

pin = 1211
rng = int(len(str(pin)) * str(9))
for i in xrange(rng):
    if i == pin:
        print('pin is: {}'.format(i))
        break

you can start with it and try to figure out how to do the rest :)


问:
Multiple DKIM signatures in message?
I'm checking my postfix setup with mail-server.net. I have SPF, DKIM, and DMARC setup and working. However, mail-server.net is claiming I have 2 DKIM signatures in a single message. How is this possible? Here's what my DNS records looks like:

Name    Value   TTL Options
v=spf1 mx -all  Default Edit | Remove

201705._domainkey   v=DKIM1; h=sha256; k=rsa; s=email; p=MIIBIjANBgk...

_adsp._domainkey    dkim=all

_dmarc  v=DMARC1;p=quarantine;sp=quarantine;adkim=r;aspf=r;fo=1;rf=afrf;rua=mailto:alescher@adventurecatsnw.com

As you can see, I've only included one DKIM signature key in the txt record. I'm using opendkim as the DKIM signer. I've only one key in the key.table record and one entry in the signing.table record. Does anyone have any ideas as to what could be the issue?

答:
My error was in /etc/postfix/master.cf and now its fixed.

This was my first postfix install and I had:

```<code>smtp      inet  n       -       n       -       -       smtpd -o content_filter=spamfilter
smtps     inet  n       -       n       -       -       smtpd -o content_filter=spamfilter
submission inet n       -       n       -       -       smtpd -o content_filter=spamfilter
</code>```

I changed this to:

```<code>smtp      inet  n       -       n       -       -       smtpd
smtps     inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd -o content_filter=spamfilter
</code>```

Good luck!

Title: Multiple DKIM signatures in message?

Body:
My error was in /etc/postfix/master.cf and now its fixed.

This was my first postfix install and I had:

smtp      inet  n       -       n       -       -       smtpd -o content_filter=spamfilter
smtps     inet  n       -       n       -       -       smtpd -o content_filter=spamfilter
submission inet n       -       n       -       -       smtpd -o content_filter=spamfilter

I changed this to:

smtp      inet  n       -       n       -       -       smtpd
smtps     inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd -o content_filter=spamfilter

Good luck!


问:
Transmission of data in HTTP
I am trying to understand the basics of the internals of HTTP servers and clients with regards to how they transmit data. I have read many articles about how HTTP works but I haven't found any that answers some of my questions.
I would like to go trough the process of loading a web page as I understand it and I would appreciate if you make me notice where I got it wrong.

When I visit a site my browser asks for an HTML file to a server, for that my browser creates a socket, binds it to my ip adress, and connects it to a listening socket of the server of the site I am visiting. In order to connect my browser's socket to the server I need a port number and a hostname, the port number is 80 because this is HTTP and the hostname is obtained via DNS resolution. Now that there is a connection between sockets my browser sends a GET request. That request is an ASCII file with the contents corresponding to an HTTP request. My browser writes the ASCII raw bytes to the socket and that is written to the server's socket.

The server writes back the HTML file I requested to the socket. The HTML the server sends is just an ASCII file that the server will write byte by byte to the socket.

My browser recieves the ASCII file and parses it. Lets assume here that it finds an image tag. The browser sends an HTTP request for that image file. Here comes something I don't understand. How does the server respond? As far as I can tell the server must send back an ASCII file formed by a set of headers followed by a CRLF and then the body of the message. In this case, assuming my browser asked for a .jpeg, does the server write the headers as ASCII plaintext to the socket and then writes the raw bytes of the image to the socket?

If the HTML file has several images do we open a socket per image (per request)?

Lets assume that my browser now finds a javascript tag. When the server answers to my request for that script does the server writes the ASCII bytes of the source of the script to the socket? What happens with js libraries? Does the server have to send all the source code for each one?

On writing data to the sockets: is write(2) the correct way to do all this writing between sockets?

On the transmission of large files: if I click a button on the site that lets me download a large PDF, how is this accomplished by the server? I assume that the server tries to transmit this in pieces. As far as I can tell there is an option for chunked encoding. Is this the way? If it is, is the file divided into chunks, and these are appended to the ASCII response and written byte by byte into the socket?

Finally, how is video transmitted? I know video encoding and transmission would require entire books for a detailed explanation but if you could say something about the generalities of video transmission (for example in youtube) I would appreciate it.

Anything that you could say about HTTP on the socket level would be appreciated. Thanks.

答:
HTTP, sockets, streaming and packages transmition are different topics.

HTTP is a communication protocol to request or send data. Sockets are not used regularly by web developers because they are not very network friendly, due to the persistent connection required. How your browser manages the HTTP requests usually should not be a real concern for you.

For big chunks of data like video, streaming is maybe the best technique, because you don't need synchronization between the client and server, or an always active connection like with sockets.
The way streaming is done only depends on you and on the language you have on the server to share your content.

If you want to learn more about HTTP, I recommend to you to read a little on RFC's like RFC 7230 or RFC 7231.
To understand how data is transmitted you should really know the basis of Abstraction Layers and for video streaming, you might learn how to make one video streaming server with NodeJs, (you might pick another language of your preference), or just search and install an NPM package that already does that job for you.

Title: Transmission of data in HTTP


问:
Whats wrote with this break;
After adding break, my code no longer works.

```<code>alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }
</code>```

答:
```<code>break; alert("Entering");
</code>```

It's to late to alert after breaking as it immediately exits the loop and doesn't execute instruction after itself there.

Title: Whats wrote with this break;

Body:
After adding break, my code no longer works.

alert("Warning: Game is made for the age of 18 and over.");
var a = prompt("Are you ready to enter this game?");
if (a == "yes") {alert("Entering");}
else if (a == "no") {while(true)
var a = prompt("Are you ready to enter this game?");
if(a == "yes") {break; alert("Entering");} }

Body:
break; alert("Entering");

It's to late to alert after breaking as it immediately exits the loop and doesn't execute instruction after itself there.


问:
how to redirect user and admin into respective form in java after pressing login button
how to redirect user login into respective page, i have mainmenu form for admin and usermainmenu form for user. i tried this below codes but i get only one usermainmenu no matter i change</p>

```<code>con = Connect.ConnectDB();
    String sql = "SELECT User_Type as 'Type', username, password FROM Users, User_Type WHERE Users.User_Type_ID = User_Type.User_Type_ID and username=? and password =? and (User_Type='admin' &&  User_Type='user');";

    //String sql= "select * from Users where username= '" + txtUserName.getText() + "' and password ='" + txtPassword.getText() + "'";
    try {

        pst = con.prepareStatement(sql);
        pst.setString(1, txtUserName.getText());
        pst.setString(2, txtPassword.getText());
        rs = pst.executeQuery();
        String username = txtUserName.getText();
        String password = txtPassword.getText();

        while (!rs.next()) {
            if (username.trim().equals(txtUserName.getText().equals(username)) && password.trim().equals(txtPassword.getText().equals(password) && username.trim().equals(User_Type))) {

                UserMainMenu frm = new UserMainMenu();
                frm.setVisible(true);
                rs.close();
            } else {
                MainMenu frm = new MainMenu();
                frm.setVisible(true);
                rs.close();
            }
        }
</code>```

答:
You call rs.close() everytime. When you close ResultSet, you can't still iterate over it. Close it after you are done with checking. Also I believe while(!rs.next()) should be while(rs.next()). The former means that the condition will be true, if rs contains no data.

edit: ..wait, I'm not sure I understand what you want to accomplish. Above was written having in mind that you want to iterate over whole ResultSet. And you probably still do.

edit4: I know what it is.

Inside your while loop, look at what Strings are you actually comparing. You are not using data from your ResultSet. Oh boy, I got confused by this:

firststring.trim().equals(otherString.equals(firstString)).

equals() returns boolean true or false, so basically you were checking if your string is equal to true/false. And in this case it is always false.

```<code>if ( rs.getString(1).equals(User_Type) && rs.getString(2).equals(txtUserName.getText()) && rs.getString(3).equals(txtPassword.getText()) )
</code>```

And then you have to provide else if for checking if what it found was an Admin user. Otherwise what comes in else block will be invoked every time the first condition was false.

I would write it as:

```<code>    String username = txtUserName.getText().trim();
    String password = txtPassword.getText().trim();
    pst = con.prepareStatement(sql);
    pst.setString(1, username);
    pst.setString(2, password);
    rs = pst.executeQuery();

    final String User_Type = "user";
    final String Admin_Type = "admin";

    String rsUserType, rsUsername, rsPassword;

    while (rs.next()) {
        rsUserType = rs.getString(1);
        rsUsername = rs.getString(2);
        rsPassword = rs.getString(3);

        if (rsUserType.equals(User_Type) && rsUsername.equals(username) && rsPassword.equals(password)) {

            SwingUtilities.invokeLater(() -> {
                UserMainMenu frm = new UserMainMenu();
                frm.setVisible(true);
            });
            rs.close();

        } else if (rsUserType.equals(Admin_Type) && rsUsername.equals(username) && rsPassword.equals(password)) {

            SwingUtilities.invokeLater(() -> {
                MainMenu frm = new MainMenu();
                frm.setVisible(true);
            });
            rs.close();
        }
    }
</code>```

Also, your SQL query fails. I don't really know how your table looks, but give this a try:

```<code>SELECT UT.User_Type, U.username, U.password
FROM Users U
INNER JOIN User_Type UT ON U.User_type_ID = UT.User_Type_ID
WHERE UT.User_Type LIKE "admin" OR  UT.User_Type LIKE "user" ;
</code>```

In SQL there is AND instead of &&. If you want to combine data from two tables, you need to JOIN them. There are different JOIN types, depending on what you want to accomplish. INNER JOIN gives us an intersection of both tables, based ON given condition. This query will give you all users and admins. Anyway, you can also just search for one specific row in your SQL query, just as you tried to, and then only check if(!rs.isClosed()), then get User_Type you found to decide which menu to open.

Body:
how to redirect user login into respective page, i have mainmenu form for admin and usermainmenu form for user. i tried this below codes but i get only one usermainmenu no matter i change

con = Connect.ConnectDB();
    String sql = "SELECT User_Type as 'Type', username, password FROM Users, User_Type WHERE Users.User_Type_ID = User_Type.User_Type_ID and username=? and password =? and (User_Type='admin' &&  User_Type='user');";

    //String sql= "select * from Users where username= '" + txtUserName.getText() + "' and password ='" + txtPassword.getText() + "'";
    try {

        pst = con.prepareStatement(sql);
        pst.setString(1, txtUserName.getText());
        pst.setString(2, txtPassword.getText());
        rs = pst.executeQuery();
        String username = txtUserName.getText();
        String password = txtPassword.getText();

        while (!rs.next()) {
            if (username.trim().equals(txtUserName.getText().equals(username)) && password.trim().equals(txtPassword.getText().equals(password) && username.trim().equals(User_Type))) {

                UserMainMenu frm = new UserMainMenu();
                frm.setVisible(true);
                rs.close();
            } else {
                MainMenu frm = new MainMenu();
                frm.setVisible(true);
                rs.close();
            }
        }

Body:
You call rs.close() everytime. When you close ResultSet, you can't still iterate over it. Close it after you are done with checking. Also I believe while(!rs.next()) should be while(rs.next()). The former means that the condition will be true, if rs contains no data.

edit: ..wait, I'm not sure I understand what you want to accomplish. Above was written having in mind that you want to iterate over whole ResultSet. And you probably still do.

edit4: I know what it is.

Inside your while loop, look at what Strings are you actually comparing. You are not using data from your ResultSet. Oh boy, I got confused by this:

firststring.trim().equals(otherString.equals(firstString)).

equals() returns boolean true or false, so basically you were checking if your string is equal to true/false. And in this case it is always false.

if ( rs.getString(1).equals(User_Type) && rs.getString(2).equals(txtUserName.getText()) && rs.getString(3).equals(txtPassword.getText()) )

And then you have to provide else if for checking if what it found was an Admin user. Otherwise what comes in else block will be invoked every time the first condition was false.

I would write it as:

    String username = txtUserName.getText().trim();
    String password = txtPassword.getText().trim();
    pst = con.prepareStatement(sql);
    pst.setString(1, username);
    pst.setString(2, password);
    rs = pst.executeQuery();

    final String User_Type = "user";
    final String Admin_Type = "admin";

    String rsUserType, rsUsername, rsPassword;

    while (rs.next()) {
        rsUserType = rs.getString(1);
        rsUsername = rs.getString(2);
        rsPassword = rs.getString(3);

        if (rsUserType.equals(User_Type) && rsUsername.equals(username) && rsPassword.equals(password)) {

            SwingUtilities.invokeLater(() -> {
                UserMainMenu frm = new UserMainMenu();
                frm.setVisible(true);
            });
            rs.close();

        } else if (rsUserType.equals(Admin_Type) && rsUsername.equals(username) && rsPassword.equals(password)) {

            SwingUtilities.invokeLater(() -> {
                MainMenu frm = new MainMenu();
                frm.setVisible(true);
            });
            rs.close();
        }
    }

Also, your SQL query fails. I don't really know how your table looks, but give this a try:

SELECT UT.User_Type, U.username, U.password
FROM Users U
INNER JOIN User_Type UT ON U.User_type_ID = UT.User_Type_ID
WHERE UT.User_Type LIKE "admin" OR  UT.User_Type LIKE "user" ;

In SQL there is AND instead of &&. If you want to combine data from two tables, you need to JOIN them. There are different JOIN types, depending on what you want to accomplish. INNER JOIN gives us an intersection of both tables, based ON given condition. This query will give you all users and admins. Anyway, you can also just search for one specific row in your SQL query, just as you tried to, and then only check if(!rs.isClosed()), then get User_Type you found to decide which menu to open.


问:
SQL Insert From PowerQuery
I need to convert a query on excel to a Insert on SQL, I wont to create a function  that will work on any query, and Invoke it, so he need to be quite reusable.

```<code>let
    SQL = (TableX as table) => let
        // Get Columns Name abd use on the columns INSERT
        SOURCE = TableX,
        Names = Table.ColumnNames(SOURCE),
        ListN = Table.FromList(Names),
        TransposeN = Table.Transpose(ListN),
        CombineN = Table.CombineColumns(TransposeN,Table.ColumnNames(TransposeN),Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"M"),
        ColunmsAsText = List.Single(CombineN[M]),
        // ColumnsasText is all the Columns Name
        // This part I cant do I need to format all columns acording to the type and Combine They
        COLUNMS = (ListN as text) => let
            TYPE = some.function.to.get.type(SOURCE[ListN]),
            if TYPE = date then FIELDS = FIELDS & "'" & Date.ToText([ListN], "yyyy-MM-dd") & "'," else
            if TYPE = text then FIELDS = FIELDS & "'" & [ListN] & "'," else
            if TYPE = number then FIELDS = FIELDS & [ListN] & "," else FIELDS = FIELDS & "#error,"
   in
        FIELDS
        INSERT = "INSERT INTO " & "TABLENAME" & " (" & ColunmsAsText & ") VALUES (" & FIELDS & ");",
        NEWCOLUMNADD = Table.AddColumn(SOURCE, "SQL", each INSERT)
in
    NEWCOLUMNADD
in
    SQL
</code>```

The problem is the FIELDS variable where, I need to compose a string of all columns, and the function "some.function.to.get.type", and the output 'll be something like this, for each row:

```<code> INSERT INTO (Column_name1, Column_name2, Column_name3) value (15, '2017-05-20', 'Text hear');
</code>```

Tanks for the help.

答:
You want Value.Type

```<code>Value.Type("abc") = type text
</code>```

Title: SQL Insert From PowerQuery

Body:
I need to convert a query on excel to a Insert on SQL, I wont to create a function  that will work on any query, and Invoke it, so he need to be quite reusable.

let
    SQL = (TableX as table) => let
        // Get Columns Name abd use on the columns INSERT
        SOURCE = TableX,
        Names = Table.ColumnNames(SOURCE),
        ListN = Table.FromList(Names),
        TransposeN = Table.Transpose(ListN),
        CombineN = Table.CombineColumns(TransposeN,Table.ColumnNames(TransposeN),Combiner.CombineTextByDelimiter(",", QuoteStyle.None),"M"),
        ColunmsAsText = List.Single(CombineN[M]),
        // ColumnsasText is all the Columns Name
        // This part I cant do I need to format all columns acording to the type and Combine They
        COLUNMS = (ListN as text) => let
            TYPE = some.function.to.get.type(SOURCE[ListN]),
            if TYPE = date then FIELDS = FIELDS & "'" & Date.ToText([ListN], "yyyy-MM-dd") & "'," else
            if TYPE = text then FIELDS = FIELDS & "'" & [ListN] & "'," else
            if TYPE = number then FIELDS = FIELDS & [ListN] & "," else FIELDS = FIELDS & "#error,"
   in
        FIELDS
        INSERT = "INSERT INTO " & "TABLENAME" & " (" & ColunmsAsText & ") VALUES (" & FIELDS & ");",
        NEWCOLUMNADD = Table.AddColumn(SOURCE, "SQL", each INSERT)
in
    NEWCOLUMNADD
in
    SQL

The problem is the FIELDS variable where, I need to compose a string of all columns, and the function "some.function.to.get.type", and the output 'll be something like this, for each row:

 INSERT INTO (Column_name1, Column_name2, Column_name3) value (15, '2017-05-20', 'Text hear');

Tanks for the help.

Body:
You want Value.Type

Value.Type("abc") = type text