问:
Paperclip and Amazon S3 Issue
I have a rails app running on Heroku. I am using paperclip for some simple image uploads for user avatars and some other things, I have S3 set as my backend and everything seems to be working fine except when trying to push to S3 I get the following error:

```<code>The AWS Access Key Id you provided does not exist in our records.
</code>```

Thinking I mis-pasted my access key and secret key, I tried again, still no luck. Thinking maybe it was just a buggy key I deactivated it and generated a new one. Still no luck.

Now for both keys I have used the S3 browser app on OS X and have been able to connect to each and view my current buckets and add/delete buckets. Is there something I should be looking out for? I have my application's S3 and paperclip setup like so

```<code>development:
  bucket: (unique name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

test:
  bucket: (unique name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

production:
  bucket: (unique_name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

has_attached_file :cover,
    :styles => {
      :thumb => "50x50"
    },
    :storage => :s3,
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
    :path => ":class/:id/:style/:filename"
</code>```

EDIT NOTE: The ENV['S3_KEY'] and ENV['S3_SECRET'] are environment variables in heroku which i have tried even using my keys directly and it still doesn't work

Note: I just added the (unique name) bits, those aren't actually there--I have also verified bucket names, but I don't even think this is getting that far. I also have my heroku environment vars setup correctly and have them setup on dev

答:
I kept getting the same AWS::S3::InvalidAccessKeyId error, and had a very similar s3.yml file. As x1a4 recommended, I used ERB in my yaml file and it worked. Here's what it looks like now:

```<code># myapp/config/s3.yml

development: &DEFAULTS
  bucket: myapp_dev
  access_key_id: <%= ENV['S3_KEY'] %>
  secret_access_key: <%= ENV['S3_SECRET'] %>

test:
  <<: *DEFAULTS
  bucket: myapp_test

production:
  <<: *DEFAULTS
  bucket: myapp

staging:
  <<: *DEFAULTS
  bucket: myapp_staging
</code>```

I guess this might a tad too indirect for some folks, but it seemed like the cleanest implementation to me.

Title: Paperclip and Amazon S3 Issue

Body:
I have a rails app running on Heroku. I am using paperclip for some simple image uploads for user avatars and some other things, I have S3 set as my backend and everything seems to be working fine except when trying to push to S3 I get the following error:

The AWS Access Key Id you provided does not exist in our records.

Thinking I mis-pasted my access key and secret key, I tried again, still no luck. Thinking maybe it was just a buggy key I deactivated it and generated a new one. Still no luck.

Now for both keys I have used the S3 browser app on OS X and have been able to connect to each and view my current buckets and add/delete buckets. Is there something I should be looking out for? I have my application's S3 and paperclip setup like so

development:
  bucket: (unique name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

test:
  bucket: (unique name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

production:
  bucket: (unique_name)
  access_key_id: ENV['S3_KEY']
  secret_access_key: ENV['S3_SECRET']

has_attached_file :cover,
    :styles => {
      :thumb => "50x50"
    },
    :storage => :s3,
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
    :path => ":class/:id/:style/:filename"

EDIT NOTE: The ENV['S3_KEY'] and ENV['S3_SECRET'] are environment variables in heroku which i have tried even using my keys directly and it still doesn't work

Note: I just added the (unique name) bits, those aren't actually there--I have also verified bucket names, but I don't even think this is getting that far. I also have my heroku environment vars setup correctly and have them setup on dev

Body:
I kept getting the same AWS::S3::InvalidAccessKeyId error, and had a very similar s3.yml file. As x1a4 recommended, I used ERB in my yaml file and it worked. Here's what it looks like now:

# myapp/config/s3.yml

development: &DEFAULTS
  bucket: myapp_dev
  access_key_id: <%= ENV['S3_KEY'] %>
  secret_access_key: <%= ENV['S3_SECRET'] %>

test:
  <<: *DEFAULTS
  bucket: myapp_test

production:
  <<: *DEFAULTS
  bucket: myapp

staging:
  <<: *DEFAULTS
  bucket: myapp_staging

I guess this might a tad too indirect for some folks, but it seemed like the cleanest implementation to me.


来源: stackexchange

问:
Propagating logs in shared library to jenkins job console
I am trying to write a shared libray which combines of global variables and shared functions to perform automated task of build and deployment for our project

The project layout as below:

The project has two major parts:

Global shared variables which are placed in vars folder

Supporting groovy scripts to abstract logics which in turn will be called in the global variable.

Inside the groovy class, I am using println to log debugging information

But it never got printed out when it is invoked through jenkins pipeline job

The log console of jenkins job as below:

Can someone show me how to propage logs from groovy class to jenkins job console as I can see only log from println in the global shared script is shown in log console.

答:
I just found a way to do it by calling println step that is available in  the jenkins job

Basically I create a wrapper function as below in Groovy class PhoenixEurekaService:

The steps is actually the jenkins job environment passed into Groovy class via constructor. By this way we can call any steps available in jenkins job in Groovy class.

In global groovy script PhoenixLib.groovy

I am not sure is there other way to do that...

ContentLicense: CC BY-SA 3.0


问:
Compilation issue with boost library
I am trying to compile some source codes. However it is throwing some error related to boost library. Here is the error

```<code>undefined reference to `boost::re_detail::get_mem_block()'
main.cpp:(.text+0x40a6): undefined reference to `boost::re_detail::verify_options(unsigned int, boost::regex_constants::_match_flags)'
main.cpp:(.text+0x40db): undefined reference to `boost::re_detail::put_mem_block(void*)'
main.cpp:(.text+0x430a): undefined reference to `boost::re_detail::put_mem_block(void*)'
main.o: In function `_ZN7Command12createVectorIdEEvRKSsRSt6vectorIT_SaIS4_EES4_.constprop.1207':
main.cpp:(.text+0x436e): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
main.cpp:(.text+0x439f): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
main.cpp:(.text+0x43d0): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<
</code>```

I have the boost regex library installed in my system and I have given the path to the library using -L option and specified the library using -lboost_regex option as well. What could be the issue?

It does find the library. But still throwing an error

答:
I met the same problem, and it has been solved. So maybe you had installed an older version of boost before, and the linker linkes the older version.

Try to remove all installed boost library, and reinstall the boost library, your problem will be solved.

Title: Compilation issue with boost library

Body:
I am trying to compile some source codes. However it is throwing some error related to boost library. Here is the error

undefined reference to `boost::re_detail::get_mem_block()'
main.cpp:(.text+0x40a6): undefined reference to `boost::re_detail::verify_options(unsigned int, boost::regex_constants::_match_flags)'
main.cpp:(.text+0x40db): undefined reference to `boost::re_detail::put_mem_block(void*)'
main.cpp:(.text+0x430a): undefined reference to `boost::re_detail::put_mem_block(void*)'
main.o: In function `_ZN7Command12createVectorIdEEvRKSsRSt6vectorIT_SaIS4_EES4_.constprop.1207':
main.cpp:(.text+0x436e): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
main.cpp:(.text+0x439f): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
main.cpp:(.text+0x43d0): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<

I have the boost regex library installed in my system and I have given the path to the library using -L option and specified the library using -lboost_regex option as well. What could be the issue?

It does find the library. But still throwing an error


问:
Pandas, groupby and count
I have a dataframe say like this

```<code>>>> df = pd.DataFrame({'user_id':['a','a','s','s','s'],
                    'session':[4,5,4,5,5],
                    'revenue':[-1,0,1,2,1]})

>>> df
   revenue  session user_id
0       -1        4       a
1        0        5       a
2        1        4       s
3        2        5       s
4        1        5       s
</code>```

And each value of session and revenue represents a kind of type, and I want to count the number of each kind say the number of revenue=-1 and session=4 of user_id=a is 1.

And I found simple call count() function after groupby() can't output the result I want.

```<code>>>> df.groupby('user_id').count()
         revenue  session
user_id
a              2        2
s              3        3
</code>```

How can I do that?

答:
You seem to want to group by several columns at once:

```<code>df.groupby(['revenue','session','user_id'])['user_id'].count()
</code>```

should give you what you want

ContentLicense: CC BY-SA 4.0

Title: Pandas, groupby and count

Body:
I have a dataframe say like this

>>> df = pd.DataFrame({'user_id':['a','a','s','s','s'],
                    'session':[4,5,4,5,5],
                    'revenue':[-1,0,1,2,1]})

>>> df
   revenue  session user_id
0       -1        4       a
1        0        5       a
2        1        4       s
3        2        5       s
4        1        5       s

And each value of session and revenue represents a kind of type, and I want to count the number of each kind say the number of revenue=-1 and session=4 of user_id=a is 1.

And I found simple call count() function after groupby() can't output the result I want.

>>> df.groupby('user_id').count()
         revenue  session
user_id
a              2        2
s              3        3

How can I do that?

Body:
You seem to want to group by several columns at once:

df.groupby(['revenue','session','user_id'])['user_id'].count()

should give you what you want


问:
Setting values in matrix based on values in vector
If I have a 3 x 3 matrix called tmp and vector data such that

```<code>tmp = [1,0,0;2,0,0;3,0,0];
data = [1,3];
data = transpose(data);
</code>```

In every row whose first element matches an element in data, I want to update that value in the second column to 1. This would result in tmp looking like this:

```<code>tmp = [1,1,0;2,0,0;3,1,0];
</code>```

Is there a way I can do this without a for loop?

答:
Like this:

```<code>tmp(:,2) = ismember(tmp(:,1),data)
</code>```

Results:

```<code>tmp =

     1     1     0
     2     0     0
     3     1     0
</code>```

Body:
If I have a 3 x 3 matrix called tmp and vector data such that

tmp = [1,0,0;2,0,0;3,0,0];
data = [1,3];
data = transpose(data);

In every row whose first element matches an element in data, I want to update that value in the second column to 1. This would result in tmp looking like this:

tmp = [1,1,0;2,0,0;3,1,0];

Is there a way I can do this without a for loop?

Body:
Like this:

tmp(:,2) = ismember(tmp(:,1),data)

Results:

tmp =

     1     1     0
     2     0     0
     3     1     0


问:
How to display a countdown on a single line in the console?
I need a countdown timer in python but without skipping line.

```<code>from time import sleep

for c in range (4,0,-1):
   print(c)
   sleep(1)
</code>```

this code makes the countdown by jumping the lines
ex:

```<code>print('3')
print('2')
print('1')
</code>```

I need that in the same line show first 3, then 2, last 1.
ex:

```<code>print('3,' + sleep(1) + '2,' + sleep(1) + '1.')
</code>```

答:
If you want delete previous number in console,
you can do like

```<code>from time import sleep
import os

for i in range(4, 0, -1):
    os.system("cls")
    print(i)
    sleep(1)
</code>```

this.

or you can use end parameter in print function.

```<code>from time import sleep

for i in range(4, 0, -1):
    print(i, end = '\r')
    sleep(1)
</code>```

like this.

Body:
I need a countdown timer in python but without skipping line.

from time import sleep

for c in range (4,0,-1):
   print(c)
   sleep(1)

this code makes the countdown by jumping the lines
ex:

print('3')
print('2')
print('1')

I need that in the same line show first 3, then 2, last 1.
ex:

print('3,' + sleep(1) + '2,' + sleep(1) + '1.')

Body:
If you want delete previous number in console,
you can do like

from time import sleep
import os

for i in range(4, 0, -1):
    os.system("cls")
    print(i)
    sleep(1)

this.

or you can use end parameter in print function.

from time import sleep

for i in range(4, 0, -1):
    print(i, end = '\r')
    sleep(1)

like this.


问:
Excel - How to determine the number of "A"s in one column based on a specified date range in another?
I have 2 columns on excel, one with referral dates, the other with referral source. It looks something like this:

I would like the count the number of the different referral source based on the different years.

So far I've tried to look for solutions but only have come up with various dead ends. I've tried something like this.

```<code>IF(AND(C2:C20>DATE(2011,1,1),C2:C20< DATE(2011,12,31)),COUNTIF(D2:D20,"A"))
</code>```

However all it does is return the total number of "A"s in D2:D20, and does not factor in the condition of the date range. I definitely must have missed something out.

Some help please?

答:
Firstly, you need >= and <= on your dates to include the first and last day of the year. Then you can use COUNTIFS which is counting with multiple criteria.</p>

```<code>=COUNTIFS(C2:C20,">=" & DATE(2011,1,1),C2:C20,"<=" & DATE(2011,12,31),D2:D20,"A")
</code>```

Body:
I have 2 columns on excel, one with referral dates, the other with referral source. It looks something like this:

I would like the count the number of the different referral source based on the different years.

So far I've tried to look for solutions but only have come up with various dead ends. I've tried something like this.

IF(AND(C2:C20>DATE(2011,1,1),C2:C20< DATE(2011,12,31)),COUNTIF(D2:D20,"A"))

However all it does is return the total number of "A"s in D2:D20, and does not factor in the condition of the date range. I definitely must have missed something out.

Some help please?

Body:
Firstly, you need >= and <= on your dates to include the first and last day of the year. Then you can use COUNTIFS which is counting with multiple criteria.

=COUNTIFS(C2:C20,">=" & DATE(2011,1,1),C2:C20,"<=" & DATE(2011,12,31),D2:D20,"A")


问:
Use Bundle-NativeCode on Linux does not work
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

```<code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .
</code>```

The build.properties looks like

```<code>source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/
</code>```

In the start method of my Activator class I call

```<code>System.loadLibrary("systemcommand");
</code>```

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

```<code>java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path
</code>```

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

```<code>java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib
</code>```

答:
I think i found the solution.

We only build the plugin which was not working and copy it to the destination platform directory. After this we start the application as wtach the log files whether the library was foud or not.

What we miss, was to delete the configurations folder. The new plugin was not unzipp and the library was not existing in the configurations directory.

Im sorry and thank you for your answers.

EDIT :

The configuration folder is placed at

```<code><installation>/eclipse/configuration/
</code>```

At least delete everything without the file

```<code><installation>/eclipse/configuration/config.ini
</code>```

OwnerDisplayName: Markus Lausberg

Body:
I create a plugin which includes the following folder structure:

src

native/so/libsystemcommand.so

META-INF/MANIFEST.MF

The manifest include the command

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Commands Plug-in
Bundle-SymbolicName: de.system.commands;singleton:=true
Bundle-Version: 1.0.0
Bundle-Activator: de.system.commands.CommandsPlugin
Bundle-Localization: plugin
Bundle-NativeCode: native/so/libsystemcommand.so; osname = Linux; processor = x86
Require-Bundle: org.eclipse.core.runtime,
 org.apache.commons.logging
Eclipse-AutoStart: true
Export-Package: de.system.commands,
 de.system.commands.jni,
 de.system.commands.utils
Bundle-ClassPath: .

The build.properties looks like

source.. = src/
output.. = bin/
bin.includes = META-INF/,\
               .,\
               native/

In the start method of my Activator class I call

System.loadLibrary("systemcommand");

At runtime the library is not found and a UnsatisfiedLinkError is thrown.

java.lang.UnsatisfiedLinkError: no libsystemcommand in java.library.path

Do I have to set more attributes in the plugin? Do I have to unzip some informations on the target platform?

EDIT:

java.library.path=/opt/jdk/j2re1.4.2_16/lib/i386/client:/opt/jdk/j2re1.4.2_16/lib/i386:/opt/jdk/j2re1.4.2_16/../lib/i386::/opt/dsa/lib:/opt/dsa/lib

LastEditorDisplayName: Markus Lausberg

Body:
I think i found the solution.

We only build the plugin which was not working and copy it to the destination platform directory. After this we start the application as wtach the log files whether the library was foud or not.

What we miss, was to delete the configurations folder. The new plugin was not unzipp and the library was not existing in the configurations directory.

Im sorry and thank you for your answers.

EDIT :

The configuration folder is placed at

<installation>/eclipse/configuration/

At least delete everything without the file

<installation>/eclipse/configuration/config.ini


问:
XNA Reach profile with VMWare - Vertex Buffers not working?
Running XNA app, using Reach profile, in VMWare Fusion host OS Mac OSX, VM is Windows XP SP 3 (my dual-boot OS).  Running on MacBook Pro w/NVidia 320M graphics card

When I am booted in to XP natively, my code works.  The code is drawing cubes that are set up using vertex buffers

When another friend runs this same code on Windows 7, it also works for him just fine

When I am running my code in the VM, it doesn't work.  I have billboarding sprites running in a shader program and this part displays fine.  I get no crashing or errors, the geometry just doesn't appear.  I tried Debug and Release.  This is very basic operation so I'm thinking VMWare isn't the problem, but it's my code....

Also, if I switch my DrawIndexedPrimitives to DrawUserIndexPrimitives (using memory objects instead of vertex buffers) everything works fine...   An acceptable solution would be to know how I can query the hardware to figure out if this will work or not work so that my code can conditionally use either memory objects or vertex buffers.

My init code:

```<code>  var vertexArray = verts.ToArray();
  var indexArray = indices.ToArray();

  indexBuffer = new IndexBuffer(GraphicsDevice, typeof(Int16), indexArray.Length, BufferUsage.WriteOnly);
  indexBuffer.SetData(indexArray);

  vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), vertexArray.Length,
    BufferUsage.WriteOnly);
  vertexBuffer.SetData(vertexArray);
</code>```

My Draw code:

```<code> // problem isn't here, tried no cull
  GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
  GraphicsDevice.BlendState = BlendState.AlphaBlend;
  GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
// Update View and Projection
  TileEffect.View = ((Game1)Game).Camera.View;
  TileEffect.Projection = ((Game1)Game).Camera.Projection;

  TileEffect.CurrentTechnique.Passes[0].Apply();

  GraphicsDevice.SetVertexBuffer(vertexBuffer);
  GraphicsDevice.Indices = indexBuffer;

  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, indices.Count, 0, indices.Count / 3);
</code>```

For LoadContent:

```<code> TileEffect = new BasicEffect(GraphicsDevice)
  {
    World = Matrix.Identity,
    View = ((Game1)Game).Camera.View,
    Projection = ((Game1)Game).Camera.Projection,
    VertexColorEnabled = true
  };
</code>```

答: Switching from indicies resolved the issue although I still don't know why it would..</p>

ContentLicense: CC BY-SA 2.5

Body:
Running XNA app, using Reach profile, in VMWare Fusion host OS Mac OSX, VM is Windows XP SP 3 (my dual-boot OS).  Running on MacBook Pro w/NVidia 320M graphics card

When I am booted in to XP natively, my code works.  The code is drawing cubes that are set up using vertex buffers

When another friend runs this same code on Windows 7, it also works for him just fine

When I am running my code in the VM, it doesn't work.  I have billboarding sprites running in a shader program and this part displays fine.  I get no crashing or errors, the geometry just doesn't appear.  I tried Debug and Release.  This is very basic operation so I'm thinking VMWare isn't the problem, but it's my code....

Also, if I switch my DrawIndexedPrimitives to DrawUserIndexPrimitives (using memory objects instead of vertex buffers) everything works fine...   An acceptable solution would be to know how I can query the hardware to figure out if this will work or not work so that my code can conditionally use either memory objects or vertex buffers.

My init code:

  var vertexArray = verts.ToArray();
  var indexArray = indices.ToArray();

  indexBuffer = new IndexBuffer(GraphicsDevice, typeof(Int16), indexArray.Length, BufferUsage.WriteOnly);
  indexBuffer.SetData(indexArray);

  vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), vertexArray.Length,
    BufferUsage.WriteOnly);
  vertexBuffer.SetData(vertexArray);

My Draw code:

 // problem isn't here, tried no cull
  GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
  GraphicsDevice.BlendState = BlendState.AlphaBlend;
  GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
// Update View and Projection
  TileEffect.View = ((Game1)Game).Camera.View;
  TileEffect.Projection = ((Game1)Game).Camera.Projection;

  TileEffect.CurrentTechnique.Passes[0].Apply();

  GraphicsDevice.SetVertexBuffer(vertexBuffer);
  GraphicsDevice.Indices = indexBuffer;

  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, indices.Count, 0, indices.Count / 3);

For LoadContent:

 TileEffect = new BasicEffect(GraphicsDevice)
  {
    World = Matrix.Identity,
    View = ((Game1)Game).Camera.View,
    Projection = ((Game1)Game).Camera.Projection,
    VertexColorEnabled = true
  };


问:
docker exec bash behaves weirdly
When I do:

docker exec -ti myContainer /bin/bash

I have a new bash terminal on running container myContainer.

Now when I write

docker exec -ti lescompanions /bin/bash -c "echo youpi"

docker only outputs youpi and returns with no interactive terminal created. I was actually expecting docker to create the terminal and run echo youpi within the newly created terminal.

Where am I wrong?

---- EDIT ----

Now how shall I run echo youpi in the new terminal on the existing container and not have the terminal return to the host after the execution of echo youpi?

答:
docker exec takes a command to run a process inside the container while the -it flag attaches an interactive session against that process.

Your session will only live as long as the command given to exec

As others have mentioned the command /bin/bash -c "echo youpi" simply uses bash to run the command echo "echo youpi" and terminates, hence your terminal session terminates also.

Title: docker exec bash behaves weirdly


问:
GPIO Button not changing the light that is on
I had trouble making out what I wanted to say in the title but I am currently trying to change the selection of lights that are turned on whenever the button is clicked that is on my breadboard.  Currently clicking the button does nothing despite my better judgment of the code is correct.  Since I am still learning how to work with Python, RaspPi, and such this is super frustrating. </p>

```<code>import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN)  #GPIO pin for colour change
GPIO.setup(20, GPIO.IN)  #GPIO for exit
GPIO.setup(22, GPIO.OUT) #GPIO Pin for red LED
GPIO.setup(12, GPIO.OUT) #GPIO Pin for blue LED

colorCheck = 0

try:
   while True:
    if ( GPIO.input(18) == True ):

        if (colorCheck < 3):
            colorCheck = colorCheck + 1;
        else:
            colorCheck = 1;

    if (colorCheck == 1):
        GPIO.output(12, GPIO.HIGH)
        GPIO.output(22, GPIO.LOW)
    elif (colorCheck == 2):
        GPIO.output(12, GPIO.LOW)
        GPIO.output(22, GPIO.HIGH)
    elif (colorCheck == 3):
        GPIO.output(12, GPIO.HIGH)
        GPIO.output(22, GPIO.HIGH)
except KeyboardInterrupt:
    GPIO.cleanup()
</code>```

答: In Python, explicitly comparing a boolean value to True (or False) is almost always a mistake.  It's completely pointless at best: the result of that comparison is itself a boolean value, why is that somehow usable, but the original value wasn't?  And it can be actively harmful, as you're throwing away Python's ability to treat a wide range of values as "truthy" (non-zero numbers, non-empty strings or containers, etc.).  In this particular case, the return value from GPIO.input() is actually an integer (0 or 1, I think), so comparing it to True guarantees that your code will never detect the button press.  So just write if GPIO.input(18): - note that those parentheses you're putting around all of your if's are unnecessary.

Body:
I had trouble making out what I wanted to say in the title but I am currently trying to change the selection of lights that are turned on whenever the button is clicked that is on my breadboard.  Currently clicking the button does nothing despite my better judgment of the code is correct.  Since I am still learning how to work with Python, RaspPi, and such this is super frustrating.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN)  #GPIO pin for colour change
GPIO.setup(20, GPIO.IN)  #GPIO for exit
GPIO.setup(22, GPIO.OUT) #GPIO Pin for red LED
GPIO.setup(12, GPIO.OUT) #GPIO Pin for blue LED

colorCheck = 0

try:
   while True:
    if ( GPIO.input(18) == True ):

        if (colorCheck < 3):
            colorCheck = colorCheck + 1;
        else:
            colorCheck = 1;

    if (colorCheck == 1):
        GPIO.output(12, GPIO.HIGH)
        GPIO.output(22, GPIO.LOW)
    elif (colorCheck == 2):
        GPIO.output(12, GPIO.LOW)
        GPIO.output(22, GPIO.HIGH)
    elif (colorCheck == 3):
        GPIO.output(12, GPIO.HIGH)
        GPIO.output(22, GPIO.HIGH)
except KeyboardInterrupt:
    GPIO.cleanup()


问:
Fast-paced SpriteKit game has irregular CPU activity and is jittery/lags despite frame rate staying high - Swift
I'm having the issue on a simple but fast-paced SpriteKit game, but I've reduced my code just to a bouncing ball and still get the issue to a lesser extent:

```<code>override func didMove(to view: SKView) {
    super.didMove(to: view)

    physicsWorld.contactDelegate = self
    physicsWorld.speed = 1
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)

    let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    borderBody.contactTestBitMask = BallCategory

    addBall()
}

func addBall() {
    let size = CGSize(width: 20, height: 20)
    let position = CGPoint(x: frame.width / 2, y: 50)

    let texture = SKTexture(image: #imageLiteral(resourceName: "whiteCircle"))
    let ball = SKSpriteNode(texture: texture, size: size)
    ball.position = position
    ball.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
    ball.fillColor = .white
    ball.lineWidth = 0
    addStandardProperties(node: ball, name: "ball", z: 5, contactTest: 0, category: BallCategory)
    ball.physicsBody?.isDynamic = true
    addChild(ball)
    launchBall()
}

func addStandardProperties(node: SKNode, name: String, z: CGFloat, contactTest: UInt32, category: UInt32) {

    node.name = name
    node.zPosition = z
    node.physicsBody?.isDynamic = false
    node.physicsBody?.affectedByGravity = false
    node.physicsBody?.mass = 0
    node.physicsBody?.restitution = 1
    node.physicsBody?.friction = 0
    node.physicsBody?.linearDamping = 0
    node.physicsBody?.angularDamping = 0
    node.physicsBody?.angularVelocity = 0
    node.physicsBody?.contactTestBitMask = contactTest
    node.physicsBody?.categoryBitMask = category

}

func launchBall() {
    let ball = childNode(withName: "ball")!
    ball.physicsBody?.velocity = CGVector(dx: 0, dy: 500)
}
</code>```

This code results in a ball (SKSpriteNode) bouncing up and down.  When I run this, CPU usage starts at around 10% on my iPhone 6s and then after increases to around 25-30% after maybe 30-60 seconds (no idea why it's increasing).  Throughout all of this, the frame rate stays very close to 60 FPS, usually going no lower than 58 FPS (it's the same way when I run the full game).

Almost any time an alert pops up (e.g., text messages, logging into Game Center, etc.), the lag shows up and shows up at random times when I'm running the full game.

I've also tried deleting and re-running the app, cleaning the project, deleting derived data and running in Release mode.  None of these worked permanently.

Should I give up on SpriteKit and try another framework?  If so, which?  Cocos2D?

Any help is appreciated.

答:
Turns out I had 2 SKViews in my view controller.  By default, when you start a project as a SpriteKit game, Xcode sets the view controller root/superview of the GameViewController as an SKView.  At some point, I had added a second SKView because I didn't intend for the scene to take up the entire screen and I apparently didn't realize that the VC root view was still set as an SKView.  So every time GameViewController loaded, it was loading two SKViews, which is why I saw 120 FPS in Xcode.

I fixed the issue by simply removing the SKView class designation from the VC root view.

Body:
I'm having the issue on a simple but fast-paced SpriteKit game, but I've reduced my code just to a bouncing ball and still get the issue to a lesser extent:

override func didMove(to view: SKView) {
    super.didMove(to: view)

    physicsWorld.contactDelegate = self
    physicsWorld.speed = 1
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)

    let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    borderBody.contactTestBitMask = BallCategory

    addBall()
}

func addBall() {
    let size = CGSize(width: 20, height: 20)
    let position = CGPoint(x: frame.width / 2, y: 50)

    let texture = SKTexture(image: #imageLiteral(resourceName: "whiteCircle"))
    let ball = SKSpriteNode(texture: texture, size: size)
    ball.position = position
    ball.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
    ball.fillColor = .white
    ball.lineWidth = 0
    addStandardProperties(node: ball, name: "ball", z: 5, contactTest: 0, category: BallCategory)
    ball.physicsBody?.isDynamic = true
    addChild(ball)
    launchBall()
}

func addStandardProperties(node: SKNode, name: String, z: CGFloat, contactTest: UInt32, category: UInt32) {

    node.name = name
    node.zPosition = z
    node.physicsBody?.isDynamic = false
    node.physicsBody?.affectedByGravity = false
    node.physicsBody?.mass = 0
    node.physicsBody?.restitution = 1
    node.physicsBody?.friction = 0
    node.physicsBody?.linearDamping = 0
    node.physicsBody?.angularDamping = 0
    node.physicsBody?.angularVelocity = 0
    node.physicsBody?.contactTestBitMask = contactTest
    node.physicsBody?.categoryBitMask = category

}

func launchBall() {
    let ball = childNode(withName: "ball")!
    ball.physicsBody?.velocity = CGVector(dx: 0, dy: 500)
}

This code results in a ball (SKSpriteNode) bouncing up and down.  When I run this, CPU usage starts at around 10% on my iPhone 6s and then after increases to around 25-30% after maybe 30-60 seconds (no idea why it's increasing).  Throughout all of this, the frame rate stays very close to 60 FPS, usually going no lower than 58 FPS (it's the same way when I run the full game).

Almost any time an alert pops up (e.g., text messages, logging into Game Center, etc.), the lag shows up and shows up at random times when I'm running the full game.

I've also tried deleting and re-running the app, cleaning the project, deleting derived data and running in Release mode.  None of these worked permanently.

Should I give up on SpriteKit and try another framework?  If so, which?  Cocos2D?

Any help is appreciated.


问:
How to create json array in json array codeigniter
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

```<code>Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------
</code>```

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

```<code>Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------
</code>```

Here is my output of JSON format that I wanted:

```<code>var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];
</code>```

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.

答:
Thanks, all, for the valuable responses.
I just got the solution.

After searching for any solution by using any available function in mysql (which I have used are json_extract() and group_concat() ), yet it didn't give the best format like what I wanted.

Inspired by the answers above,
I have made my code like this in Codeigniter that works perfectly:

```<code>$parent   = array();
$children = array();
$profile  = array();

$parent_query = $this->db->query("select firstname, lastname, rating, id from parent")->result_array();

for($i = 0; $i < count($parent_query); $i++)
{
   $children_query = $this->db->query("select name from children where idparent = '$parent_query[$i]['id']'")->result_array();

   $parent[$i]['firstname'] = $parent_query[$i]['firstname'];
   $parent[$i]['lastname']  = $parent_query[$i]['lastname'];
   $parent[$i]['rating']    = $parent_query[$i]['rating'];

   for($j = 0; $j < count($children_query); $j++)
   {
      $children[] = $children_query[$j]['name'];
   }

   $parent[$i]['children']  = $children;
}

$profile = json_encode($parent);
</code>```

The result given:

```<code>[
   {
      "firstname":"John",
      "lastname":"Doe",
      "rating":9.3,
      "children":[
         "John A",
         "John B",
         "John C"
      ],
      "id":1
   },
   {
      "firstname":"Marry",
      "lastname":"Jane",
      "rating":8.5,
      "children":[
         "Jane A",
         "Jane B"
      ],
      "id":2
   },
   {
      "firstname":"Paijo",
      "lastname":"Masni",
      "rating":9.8,
      "children":[
         "Bang Jo",
         "Kak Jo"
      ],
      "id":3
   }
]
</code>```

Body:
I have been searching for the solution on how to create JSON array in JSON object from Mysql query. Need help from any of you.

My source data in mysql:

Table: parent
--------------------------------------
| id | firstname | lastname | rating |
--------------------------------------
|  1 | John      | Doe      | 9.3    |
|  2 | Marry     | Jane     | 8.5    |
|  3 | Paijo     | Masni    | 9.8    |
--------------------------------------

Table: children
------------------------------
| id |  idparent  | name     |
------------------------------
|  1 |  1         | John A   |
|  2 |  1         | John B   |
|  3 |  1         | John C   |
|  4 |  2         | Jane A   |
|  5 |  2         | Jane B   |
|  6 |  3         | Bang Jo  |
|  7 |  3         | Kak Jo   |
------------------------------

My MySQL Query:

Select p.firstname, p.lastname, p.rating, c.name as children

from parent p join children c on p.id = c.idparent

Output:
-------------------------------------------------
| id | firstname | lastname | rating | children |
-------------------------------------------------
|  1 | John      | Doe      | 9.3    | John A   |
|  1 | John      | Doe      | 9.3    | John B   |
|  1 | John      | Doe      | 9.3    | John C   |
|  2 | Marry     | Jane     | 8.5    | Jane A   |
|  2 | Marry     | Jane     | 8.5    | Jane B   |
|  3 | Paijo     | Masni    | 9.8    | Bang Jo  |
|  3 | Paijo     | Masni    | 9.8    | Kak Jo   |
-------------------------------------------------

Here is my output of JSON format that I wanted:

var profile = [
    {
        "firstname": "John",
        "lastname": "Doe",
        "rating": 9.3,
        "children": [
            "John A",
            "John B",
            "John C"
        ],
        "id": 1
    },
    {
        "firstname": "Marry",
        "lastname": "Jane",
        "rating": 8.5,
        "children": [
            "Jane A",
            "Jane B"
        ],
        "id": 2
    },
    {
        "firstname": "Paijo",
        "lastname": "Masni",
        "rating": 9.8,
        "children": [
            "Bang Jo",
            "Kak Jo"
        ],
        "id": 3
    }
];

The one I got stuck from generating the JSON is on the children: [], I want to have an array with double-quote "" separated by comma ',' inside the [].

Thank you.

NB:
Currenty I am using codeigniter for my coding. If you have faced this kind of problem on codeigniter before, I'm looking forward to getting the sharing from you.

Body:
Thanks, all, for the valuable responses.
I just got the solution.

After searching for any solution by using any available function in mysql (which I have used are json_extract() and group_concat() ), yet it didn't give the best format like what I wanted.

Inspired by the answers above,
I have made my code like this in Codeigniter that works perfectly:

$parent   = array();
$children = array();
$profile  = array();

$parent_query = $this->db->query("select firstname, lastname, rating, id from parent")->result_array();

for($i = 0; $i < count($parent_query); $i++)
{
   $children_query = $this->db->query("select name from children where idparent = '$parent_query[$i]['id']'")->result_array();

   $parent[$i]['firstname'] = $parent_query[$i]['firstname'];
   $parent[$i]['lastname']  = $parent_query[$i]['lastname'];
   $parent[$i]['rating']    = $parent_query[$i]['rating'];

   for($j = 0; $j < count($children_query); $j++)
   {
      $children[] = $children_query[$j]['name'];
   }

   $parent[$i]['children']  = $children;
}

$profile = json_encode($parent);

The result given:

[
   {
      "firstname":"John",
      "lastname":"Doe",
      "rating":9.3,
      "children":[
         "John A",
         "John B",
         "John C"
      ],
      "id":1
   },
   {
      "firstname":"Marry",
      "lastname":"Jane",
      "rating":8.5,
      "children":[
         "Jane A",
         "Jane B"
      ],
      "id":2
   },
   {
      "firstname":"Paijo",
      "lastname":"Masni",
      "rating":9.8,
      "children":[
         "Bang Jo",
         "Kak Jo"
      ],
      "id":3
   }
]


问:
group memberships in (AD) ldap Realm
I use the JAAS Framework for the authentification and authorization process in a java ee enterprise application. I use GlassFish as the application server. My realm configuration looks like:

```<code><auth-realm name="ads-realm" classname="com.sun.enterprise.security.auth.realm.ldap.LDAPRealm">
  <property name="jaas-context" value="ldapRealm" />
  <property name="base-dn" value="CN=Users,DC=company,DC=intern" />
  <property name="directory" value="ldap://ad.company.intern:389" />
  <property name="search-filter" value="(&(objectClass=user)(sAMAccountName=%s))" />
  <property name="search-bind-password" value="****" />
  <property name="search-bind-dn" value="ldapSvc@company.intern" />
</auth-realm>
</code>```

This configuration works fine in my environment. See following log entries:

```<code>FEIN: JAAS login complete.
FEIN: JAAS authentication committed.
FEIN: Password login succeeded for xyz
</code>```

but i don't receive a LDAP Group membership(s) from my Active Directory

```<code>FEIN: LDAP: Group memberships found:
FEIN: LDAP: login succeeded for: xyz
</code>```

Which configuration/entry/mapping have I to do, to receive a group membership from AD?

Surely, I can add the property

```<code><property name="assign-groups" value="Users" />
</code>```

to my GlassFish configuration, but that is not exactly what i want.

答:
You need to add this extra property:

group-search-filter Search filter to find group memberships for the user. The default value is uniquemember=%d (%d expands to the user element DN). In the case of Active Directory this should be member=%d

Title: group memberships in (AD) ldap Realm

Body:
I use the JAAS Framework for the authentification and authorization process in a java ee enterprise application. I use GlassFish as the application server. My realm configuration looks like:

<auth-realm name="ads-realm" classname="com.sun.enterprise.security.auth.realm.ldap.LDAPRealm">
  <property name="jaas-context" value="ldapRealm" />
  <property name="base-dn" value="CN=Users,DC=company,DC=intern" />
  <property name="directory" value="ldap://ad.company.intern:389" />
  <property name="search-filter" value="(&(objectClass=user)(sAMAccountName=%s))" />
  <property name="search-bind-password" value="****" />
  <property name="search-bind-dn" value="ldapSvc@company.intern" />
</auth-realm>

This configuration works fine in my environment. See following log entries:

FEIN: JAAS login complete.
FEIN: JAAS authentication committed.
FEIN: Password login succeeded for xyz

but i don't receive a LDAP Group membership(s) from my Active Directory

FEIN: LDAP: Group memberships found:
FEIN: LDAP: login succeeded for: xyz

Which configuration/entry/mapping have I to do, to receive a group membership from AD?

Surely, I can add the property

<property name="assign-groups" value="Users" />

to my GlassFish configuration, but that is not exactly what i want.


问:
Check C++ shared dependencies at runtime (ldd on self)
Is there a way to check or access the names of the libraries a C++ binary  is dynamically linked to within the binary itself?

Essentially I want to run ldd on a binary, without running ldd.

The use case is using dlopen from dlfcn.h. I have a C++ library which is linked to libpython, but I don't know if its libpython3.5m.so, libpython3.4m.so, libpython2.7.so, etc...

I want to call

```<code>void* handle = dlopen( "@PYTHON_LIBRARY@", RTLD_LAZY | RTLD_GLOBAL );
</code>```

where "@PYTHON_LIBRARY@" resolves to the path to whatever the current libpython the module is currently dynamically linked to.

Is there any way to do this?

答:
I want to call void *handle = dlopen("...", ...)

Presumably you want to then call dlsym(handle, "SomePythonSymbol").

That is a pointless thing to do. Instead of performing dynamic lookup, simply call the SomePythonSymbol directly.

To answer your original "what version of libpython am I linked to" question, on a GLIBC-based system you can use dl_iterate_phdr to enumerate all currently loaded shared libraries.

If you already have a symbol that you know is defined in libpython, dladdr1 will make finding the library even easier.

Body:
Is there a way to check or access the names of the libraries a C++ binary  is dynamically linked to within the binary itself?

Essentially I want to run ldd on a binary, without running ldd.

The use case is using dlopen from dlfcn.h. I have a C++ library which is linked to libpython, but I don't know if its libpython3.5m.so, libpython3.4m.so, libpython2.7.so, etc...

I want to call

void* handle = dlopen( "@PYTHON_LIBRARY@", RTLD_LAZY | RTLD_GLOBAL );

where "@PYTHON_LIBRARY@" resolves to the path to whatever the current libpython the module is currently dynamically linked to.

Is there any way to do this?


问:
summing list inside list by position in python
I have a list that looks like this and I would like to sum up the values at each position so as produce a list with only three values

```<code>print x
[[0, 0, -1], [0, 0, -1], [0, 0, 0], [1, 0, 0], [0, 0, 1]]
</code>```

For example, x[0][1] should be summed with the value in x[1][1], x[2][1], x[3][1], x[4][1]. Likewise x[0][2] should be summed with x[1][2], x[2][2], etc.

the output should look like this

```<code>print output
[1, 0, -1]
</code>```

答:
Just combine for loops:

```<code>outlist=[]
for i in range(len(L[0])):
    sum = 0
    for subL in L:
        sum += subL[i]
    outlist.append(sum)

print(outlist)
</code>```

Output:

```<code>[1, 0, -1]
</code>```

Body:
I have a list that looks like this and I would like to sum up the values at each position so as produce a list with only three values

print x
[[0, 0, -1], [0, 0, -1], [0, 0, 0], [1, 0, 0], [0, 0, 1]]

For example, x[0][1] should be summed with the value in x[1][1], x[2][1], x[3][1], x[4][1]. Likewise x[0][2] should be summed with x[1][2], x[2][2], etc.

the output should look like this

print output
[1, 0, -1]

Body:
Just combine for loops:

outlist=[]
for i in range(len(L[0])):
    sum = 0
    for subL in L:
        sum += subL[i]
    outlist.append(sum)

print(outlist)

Output:

[1, 0, -1]


问:
Why does Windows sometimes start using port that I use for IIS Express?
Sometimes when I try to run the IIS Express from visual studio, I get this message:

If I check what process is using the port, I get the PID 4 which is the System process on my computer right now:

```<code>D:\>netstat -a -n -o | find "15134"
  TCP    0.0.0.0:15134          0.0.0.0:0              LISTENING       4
  TCP    [::]:15134             [::]:0                 LISTENING       4
  TCP    [::1]:15134            [::1]:50081            ESTABLISHED     4
  TCP    [::1]:50081            [::1]:15134            ESTABLISHED     7676

D:\>tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0        304 K
</code>```

I connected to the port on Telnet and this was the response (I just typed random letters, not a valid HTTP request):

```<code>HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 15 Nov 2017 11:41:09 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/str
ict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Verb</h2>
<hr><p>HTTP Error 400. The request verb is invalid.</p>
</BODY></HTML>
</code>```

How to prevent this from happening? And how to deal with this problem, short of changing the development port or restarting the PC?

答:
PID 4 and Server: Microsoft-HTTPAPI/2.0 together mean that the port is being used by something hooked to http.sys driver.

Thus, reboot your machine is rarely a solution. Changing to another port is more realistic an option.

Note that, there can be other causes for "port is in use" issues, so this answer does not attempt to cover them all.

Body:
Sometimes when I try to run the IIS Express from visual studio, I get this message:

If I check what process is using the port, I get the PID 4 which is the System process on my computer right now:

D:\>netstat -a -n -o | find "15134"
  TCP    0.0.0.0:15134          0.0.0.0:0              LISTENING       4
  TCP    [::]:15134             [::]:0                 LISTENING       4
  TCP    [::1]:15134            [::1]:50081            ESTABLISHED     4
  TCP    [::1]:50081            [::1]:15134            ESTABLISHED     7676

D:\>tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0         24 K
System                           4 Services                   0        304 K

I connected to the port on Telnet and this was the response (I just typed random letters, not a valid HTTP request):

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Wed, 15 Nov 2017 11:41:09 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/str
ict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

How to prevent this from happening? And how to deal with this problem, short of changing the development port or restarting the PC?


问:
Putting multiple elements in array through loop
I have multiple inputs in a file like this:

<form action="card_generate.php">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
</form>```
</div>
</div>

in the file card_generate.php this have to go in an array i have wrote:</p>

<pre class="lang-php prettyprint-override"><code>$tabs = array($_POST["tZero"], $_POST["tOne"], $_POST["tTwo"], $_POST["tThree"]);
</code>```

Is there a way I can put these values in an array through a loop or something instead of putting each value in an array one by one, there can be more values than four values.

答:
Use input name array,

```<code><form action="card_generate.php">
<input type="text" name="t[]">
        <input type="text" name="t[]">
        <input type="text" name="t[]">
        <input type="text" name="t[]">
</form>
</code>```

And, you will get in post,

```<code>print_r($_POST['t']);
</code>```

Body:
I have multiple inputs in a file like this:

<form action="card_generate.php">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
</form>

in the file card_generate.php this have to go in an array i have wrote:

$tabs = array($_POST["tZero"], $_POST["tOne"], $_POST["tTwo"], $_POST["tThree"]);

Is there a way I can put these values in an array through a loop or something instead of putting each value in an array one by one, there can be more values than four values.

Body:
Use input name array,

<form action="card_generate.php">
<input type="text" name="t[]">
        <input type="text" name="t[]">
        <input type="text" name="t[]">
        <input type="text" name="t[]">
</form>

And, you will get in post,

print_r($_POST['t']);


问:
Cassandra: customer data per keyspace
Problem: one of our new customers want the data to be stored in his own country (law regulations). However we use existing customer's data spread across few datacenters in different countries.

Question: how we can separate new customer's data to reside in its own country without much changing existing Cassandra architecture?

Potential Solution #1: to use separate keyspace for this customer. Schemas will be the same between keyspaces what adds the complexity for data migration and so on. DataStax support confirmed that it is possible to configure keyspace per region.
However Spring Data Cassandra we use, doesn't allow to choose keyspace dynamically.
The only way is to use CqlTemplate and to run use keyspace blabla everytime before the call or to add keyspace before the table select * from blabla.mytable but it sounds as a hack for me.

Potential Solution #2 to use separate environment for new client but management rejects to do it.

Any other ways to achieve this goal?

答:
Advice with 2 keyspaces is correct.
If question is about having just 2 keyspaces why not configure 2 keyspaces.
for Region Dependent client - write to both

for others - write to one (main) keyspace only.
No data migration will be required.
Here is sample how to configure Spring Repositories to hit different keyspaces:
http://valchkou.com/spring-boot-cassandra.html#multikeyspace

the choice of repository can be simple if else

```<code>if (org in (1,2,3)) {
   repoA.save(entity)
   repoB.save(entity)
} else {
   repoA.save(entity)
}
</code>```

Title: Cassandra: customer data per keyspace

Body:
Advice with 2 keyspaces is correct.
If question is about having just 2 keyspaces why not configure 2 keyspaces.
for Region Dependent client - write to both

for others - write to one (main) keyspace only.
No data migration will be required.
Here is sample how to configure Spring Repositories to hit different keyspaces:
http://valchkou.com/spring-boot-cassandra.html#multikeyspace

the choice of repository can be simple if else

if (org in (1,2,3)) {
   repoA.save(entity)
   repoB.save(entity)
} else {
   repoA.save(entity)
}


问:
Prototype Access & Behavior
1.1: Why does accessing x directly on linkingObject not work but accessing it on linkingObject.prototype does?

1.2: Once linkingObject is searched for x, shouldn't the engine by default then search its prototype for x? Why do I need to explicitly state .prototype?

1.3: To further illustrate how weird this is, you can see that baseObject is the prototype of linkingObject and it even states that it contains the xproperty.

```<code>const baseObject = function() {};

baseObject.prototype.x = 5;

const linkingObject = Object.create(baseObject);

console.log(linkingObject.x); // 1.1: undefined
console.log(linkingObject.prototype.x); // 1.2: 5
console.log(linkingObject.prototype); // 1.3: baseObject { x:5 }
</code>```

答:
You have confused the prototype property of a function object with the first entry in an object's inheritance chain. The latter is often written as [[prototype]] because it it is an internal value referring to the start of the inheritance chain.

The [[prototype]] internal property (called a "slot") of an object is set to the prototype property of its constructor, or in the case of objects created by  Object.create, the object value supplied as first argument.

So you set the [[prototype]] value of linkingObject to the function baseObject. Searching linkingObject will find prototype in the inheritance chain (it's a property of baseObject) and then find linkingObject.prototype.x as a defined property of the inherited prototype value.

But baseObject the function does not have an x property itself, so searching for the non-existent linkingObject.x property returns undefined.

Title: Prototype Access & Behavior

Body:
1.1: Why does accessing x directly on linkingObject not work but accessing it on linkingObject.prototype does?

1.2: Once linkingObject is searched for x, shouldn't the engine by default then search its prototype for x? Why do I need to explicitly state .prototype?

1.3: To further illustrate how weird this is, you can see that baseObject is the prototype of linkingObject and it even states that it contains the xproperty.

const baseObject = function() {};

baseObject.prototype.x = 5;

const linkingObject = Object.create(baseObject);

console.log(linkingObject.x); // 1.1: undefined
console.log(linkingObject.prototype.x); // 1.2: 5
console.log(linkingObject.prototype); // 1.3: baseObject { x:5 }


问:
FreshMvvm PushNewNavigationServiceModal not working
I'm trying to change from FreshNavigationContainer to FreshMasterDetailNavigationContainer when the user is loggedin within the method SuccessfulLogin by using freshMvvm method PushNewNavigationServiceModal but nothing is happening.

```<code>    public void SuccessfulLogin()
    {
        App.IsLoggedIn = true;
        var masterDetailNav = new FreshMasterDetailNavigationContainer();
        masterDetailNav.Init("Menu");
        masterDetailNav.AddPage<ProfilePageModel>("Profile", null);
        CoreMethods.PushNewNavigationServiceModal(masterDetailNav);
    }
</code>```

Edit :
I just noticed that after using this method navigation isn't working anymore.

答:
You need to use CoreMethods.SwitchOutRootNavigation

First Setup your NavigationStacks

```<code>public class NavigationStacks
{
    public static string LoginNavigationStack = "LoginNavigationStack";
    public static string MainAppStack = "MainAppStack";
}
</code>```

In you App.xaml.cs define the Navigations

```<code>FreshNavigationContainer loginMain;
FreshMasterDetailNavigationContainer masterDetailNav;

var loginPage = FreshPageModelResolver.ResolvePageModel<UserLoginPageModel>();
loginMain = new FreshNavigationContainer(loginPage, NavigationStacks.LoginNavigationStack);

var masterDetailNav = new FreshMasterDetailNavigationContainer(NavigationStacks.MainAppStack);
masterDetailNav.Init("Menu");
masterDetailNav.AddPage<ProfilePageModel>("Profile", null);
</code>```

Then in your Login ViewModel

```<code>public void SuccessfulLogin()
{
    App.IsLoggedIn = true;
    CoreMethods.SwitchOutRootNavigation(NavigationStacks.MainAppStack);
}
</code>```

Body:
I'm trying to change from FreshNavigationContainer to FreshMasterDetailNavigationContainer when the user is loggedin within the method SuccessfulLogin by using freshMvvm method PushNewNavigationServiceModal but nothing is happening.

    public void SuccessfulLogin()
    {
        App.IsLoggedIn = true;
        var masterDetailNav = new FreshMasterDetailNavigationContainer();
        masterDetailNav.Init("Menu");
        masterDetailNav.AddPage<ProfilePageModel>("Profile", null);
        CoreMethods.PushNewNavigationServiceModal(masterDetailNav);
    }

Edit :
I just noticed that after using this method navigation isn't working anymore.

Body:
You need to use CoreMethods.SwitchOutRootNavigation

First Setup your NavigationStacks

public class NavigationStacks
{
    public static string LoginNavigationStack = "LoginNavigationStack";
    public static string MainAppStack = "MainAppStack";
}

In you App.xaml.cs define the Navigations

FreshNavigationContainer loginMain;
FreshMasterDetailNavigationContainer masterDetailNav;

var loginPage = FreshPageModelResolver.ResolvePageModel<UserLoginPageModel>();
loginMain = new FreshNavigationContainer(loginPage, NavigationStacks.LoginNavigationStack);

var masterDetailNav = new FreshMasterDetailNavigationContainer(NavigationStacks.MainAppStack);
masterDetailNav.Init("Menu");
masterDetailNav.AddPage<ProfilePageModel>("Profile", null);

Then in your Login ViewModel

public void SuccessfulLogin()
{
    App.IsLoggedIn = true;
    CoreMethods.SwitchOutRootNavigation(NavigationStacks.MainAppStack);
}


问:
How to put the Y-axis of a chart to the right-side of it
I created a chart in Billboard.js which looks like this:

```<code>var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": columns
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": label,
                "position": "outer-center"
            },
        },
        "y": {
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});
</code>```

Now it looks like the classic style, X axis on the bottom and Y axis on the left. I want to move the Y axis on the right of the table.

I've tried many ways to do it but without success like these ones:

-changing its name from y to y2

-adding the same code but with y2:

```<code>"y": {
    "label": {
    "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

"y2": {
    "label": {
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
</code>```

I addied show attribute inside the label like this:

```<code>"y": {
    "label": {
        "show": false,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
"y2": {
    "label": {
        "show": true,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
</code>```

Any ideas?

答:
I think, @Nouphal pointed exactly what to do.
The key point is set data.axes options to bound datas to y2 axis.

https://naver.github.io/billboard.js/release/latest/doc/Options.html#.data:axes

I made working demo with your code(except the data value), so replace it setting with your data and will work.

var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": [
          // replace with your data value
          ['x', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06'],
          ["data1", 30, 200, 100, 400, 150, 250],
          ["data2", 50, 20, 10, 40, 15, 25]
        ],
        "axes": {
          "data1": "y2",
          "data2": "y2"
        }
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": "label",
                "position": "outer-center"
            },
        },
        "y": {
          "show": false
        },
        "y2": {
            "show": true,
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css">
</head>
<body>
  <div id="main-chart"></div>
</body>
</html></code>```

Body:
I created a chart in Billboard.js which looks like this:

var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": columns
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": label,
                "position": "outer-center"
            },
        },
        "y": {
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});

Now it looks like the classic style, X axis on the bottom and Y axis on the left. I want to move the Y axis on the right of the table.

I've tried many ways to do it but without success like these ones:

-changing its name from y to y2

-adding the same code but with y2:

"y": {
    "label": {
    "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

"y2": {
    "label": {
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

I addied show attribute inside the label like this:

"y": {
    "label": {
        "show": false,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},
"y2": {
    "label": {
        "show": true,
        "text": "Energy (kWh)",
        "position": "outer-middle"
    },
},

Any ideas?

Body:
I think, @Nouphal pointed exactly what to do.
The key point is set data.axes options to bound datas to y2 axis.

https://naver.github.io/billboard.js/release/latest/doc/Options.html#.data:axes

I made working demo with your code(except the data value), so replace it setting with your data and will work.

var chart = bb.generate({
    "data": {
        "type": "line",
        "x": "x",
        "columns": [
          // replace with your data value
          ['x', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06'],
          ["data1", 30, 200, 100, 400, 150, 250],
          ["data2", 50, 20, 10, 40, 15, 25]
        ],
        "axes": {
          "data1": "y2",
          "data2": "y2"
        }
    },
    "point": {
        "show": false
    },
    "legend": {
        "show": false
    },
    "axis": {
        "x": {
            "localtime": false,
            "type": "timeseries",
            "tick": {
                count: 7,
                "format": "%b %d, %Y",
                "rotate": 45,
                "multiline": true
            },
             "label": {
                "text": "label",
                "position": "outer-center"
            },
        },
        "y": {
          "show": false
        },
        "y2": {
            "show": true,
            "label": {
                "text": "Energy (kWh)",
                "position": "outer-middle"
            },
        },
    },
    "bindto": "#main-chart"
});

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css">
</head>
<body>
  <div id="main-chart"></div>
</body>
</html>


问:
Is there anyway to use the property like behavior?
I have the following formula

```<code>X := X + F*(1-i div n);
</code>```

Where

```<code>X, F, i, n: integer;
</code>```

The code I'm using is this

```<code>F := 7; // the initial speed with no friction.
n := 10; // the animation number of steps.
Hn := n * 2 ;
X := 0;  // first Pos
i := 1;
J := 1;
while J < Hn do
begin
  X := X + F * (1 - i div n);
  if X > Xmax then X := 0;  <-- line (1).
  if i >= n then Dec(i)
  else Inc(i);
  Inc(J);
end;
</code>```

If it was possible I would like to use this but without class/record implementation(not inside a class/record implementation/method).not the exact syntax, just the same principle, instead of direct assignment to X the SetX is called then the result is assigned to X.

```<code>X: integer write SetX; // This is not a correct delphi syntax. I added it to explain the behavior I want.

function SetX(aValue: integer): integer;
const
  Xmax: SomeIntegerValue;
begin
  if aValue > Xmax then result := 0
  else result := aValue;
end;
</code>```

So I could omit Line (1). If this was possible, all the lines after the formula would be omitted and the while loop would look like this

```<code>while J < Hn do  // J will be incremented each time the loop wants to read it.
begin
  X := X + F * (1 - i div n);
end;
</code>```

Is there anyway to use the property like behavior?

Note: I'm looking for a way to alter the assignment and reading ways of a variable like you do in a property of a record/class.

答:
I found a way to do what I wanted. I know that overloading the := operator is not possible, However forcing the compiler to produce the same behavior as the overloaded operator would behave is possible.

The overloading would not let me control the LSA (Left Side Argument). but it gave full control to implicitly convert any TType (in my case it is an integer) to TXinteger. So all I had to do is make sure that every operator would result in a TType which will force the compiler to implicitly convert that to a TXinteger.

Forcing the compiler to use my implicit operator every time it wants to assign something to TXinteger means I control the assignment Hence I overloaded the := operator.

the following is a test example that makes omitting Line(1) possible.

```<code>program Project4;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
   TXinteger = record
     X: integer;
     class operator Add(a, b: TXinteger): integer;
     class operator Add(a: TXinteger; b:integer): integer;
     class operator Add(a: integer; b:TXinteger): integer;
     class operator Implicit(a: Integer): TXinteger;
     class operator Implicit(a: TXinteger): Integer;
   end;

// Example implementation of Add
class operator TXinteger.Add(a, b: TXinteger): integer;
begin
  result := a.X + b.X;
end;(**)

class operator TXinteger.Add(a: TXinteger; b:integer): integer;
begin
  result := a.X + b;
end;

class operator TXinteger.Add(a: integer; b:TXinteger): integer;
begin
  result := a + b.X;
end;

class operator TXinteger.Implicit(a: Integer): TXinteger;
const
  Xmax: integer = 10;
begin
  if a > Xmax then result.X := 0 else result.X := a;
end;

class operator TXinteger.Implicit(a: TXinteger): Integer;
begin
  result := a.X;
end;

var
X: TXinteger;
Hn, F, i,J, n: integer;
begin
  try
  F := 7;
  n := 10;
  Hn := n * 2 ;
  X := 0;
  i := 1;
  J := 1;
  while J < Hn do
    begin
    X := X + F * (1 - i div n);
    // Line (1)  is gone now.
    if i >= n then Dec(i)
    else Inc(i);
    Inc(J);
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
</code>```

Note: for this case it is pointless to do all of this just to omit one line of code. I wanted to share this because it gives an idea of how one could overload the := operator.

What I wanted is this:

Alter how X:Integer is read (value read from the variable x's storage).

Alter how X:Integer is assigned.

by overloading all the operators that use the value of X, I completed the first.
And by forcing the compiler as explained above, I completed the second.

Thank you all for your help.

Body:
I have the following formula

X := X + F*(1-i div n);

Where

X, F, i, n: integer;

The code I'm using is this

F := 7; // the initial speed with no friction.
n := 10; // the animation number of steps.
Hn := n * 2 ;
X := 0;  // first Pos
i := 1;
J := 1;
while J < Hn do
begin
  X := X + F * (1 - i div n);
  if X > Xmax then X := 0;  <-- line (1).
  if i >= n then Dec(i)
  else Inc(i);
  Inc(J);
end;

If it was possible I would like to use this but without class/record implementation(not inside a class/record implementation/method).not the exact syntax, just the same principle, instead of direct assignment to X the SetX is called then the result is assigned to X.

X: integer write SetX; // This is not a correct delphi syntax. I added it to explain the behavior I want.

function SetX(aValue: integer): integer;
const
  Xmax: SomeIntegerValue;
begin
  if aValue > Xmax then result := 0
  else result := aValue;
end;

So I could omit Line (1). If this was possible, all the lines after the formula would be omitted and the while loop would look like this

while J < Hn do  // J will be incremented each time the loop wants to read it.
begin
  X := X + F * (1 - i div n);
end;

Is there anyway to use the property like behavior?

Note: I'm looking for a way to alter the assignment and reading ways of a variable like you do in a property of a record/class.

Body:
I found a way to do what I wanted. I know that overloading the := operator is not possible, However forcing the compiler to produce the same behavior as the overloaded operator would behave is possible.

The overloading would not let me control the LSA (Left Side Argument). but it gave full control to implicitly convert any TType (in my case it is an integer) to TXinteger. So all I had to do is make sure that every operator would result in a TType which will force the compiler to implicitly convert that to a TXinteger.

Forcing the compiler to use my implicit operator every time it wants to assign something to TXinteger means I control the assignment Hence I overloaded the := operator.

the following is a test example that makes omitting Line(1) possible.

program Project4;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
   TXinteger = record
     X: integer;
     class operator Add(a, b: TXinteger): integer;
     class operator Add(a: TXinteger; b:integer): integer;
     class operator Add(a: integer; b:TXinteger): integer;
     class operator Implicit(a: Integer): TXinteger;
     class operator Implicit(a: TXinteger): Integer;
   end;

// Example implementation of Add
class operator TXinteger.Add(a, b: TXinteger): integer;
begin
  result := a.X + b.X;
end;(**)

class operator TXinteger.Add(a: TXinteger; b:integer): integer;
begin
  result := a.X + b;
end;

class operator TXinteger.Add(a: integer; b:TXinteger): integer;
begin
  result := a + b.X;
end;

class operator TXinteger.Implicit(a: Integer): TXinteger;
const
  Xmax: integer = 10;
begin
  if a > Xmax then result.X := 0 else result.X := a;
end;

class operator TXinteger.Implicit(a: TXinteger): Integer;
begin
  result := a.X;
end;

var
X: TXinteger;
Hn, F, i,J, n: integer;
begin
  try
  F := 7;
  n := 10;
  Hn := n * 2 ;
  X := 0;
  i := 1;
  J := 1;
  while J < Hn do
    begin
    X := X + F * (1 - i div n);
    // Line (1)  is gone now.
    if i >= n then Dec(i)
    else Inc(i);
    Inc(J);
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Note: for this case it is pointless to do all of this just to omit one line of code. I wanted to share this because it gives an idea of how one could overload the := operator.

What I wanted is this:

Alter how X:Integer is read (value read from the variable x's storage).

Alter how X:Integer is assigned.

by overloading all the operators that use the value of X, I completed the first.
And by forcing the compiler as explained above, I completed the second.

Thank you all for your help.


问:
Using es6 spread to concat multiple arrays
We all know you can do:

```<code>let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]
</code>```

But how do you make this dynamic to concat N arrays?

答:
let fruits = ["apples", "bananas", "pears"];
let vegetables = ["corn", "potatoes", "carrots"];

let produce = [...fruits, ...vegetables];

console.log(produce);```

Body:
We all know you can do:

let arr1 = [1,2,3];
let arr2 = [3,4,5];
let arr3 = [...arr1, ...arr2]; // [1,2,3,3,4,5]

But how do you make this dynamic to concat N arrays?


问:
Is it possible to perform vibration from iOS widget?
I know that we can able to perform vibration from iOS mobile app.

But I need to know whether we can perform vibration from Today extension / Widget on some action like a button action?

答:
This has already been answered here.</p>

```<code>import AudioToolbox
//Swift:
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
//Obj-c:
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
</code>```

Body:
This has already been answered here.

import AudioToolbox
//Swift:
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
//Obj-c:
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);


问:
sonar Setting up in Azure cloud and automate through VSTS
I just gone through some documents regarding the sonar and azure cloud ,I am new to Sonar and Azure Cloud.As per the documentation which I gone through,I got some idea on this.I have installed sonar plugin in VSTS and tried to connect to azure but As per my understanding we need to set proxy in azure servers so that I can connect to azure.But still I am not having the approach to connect sonar with Azure.Do we need to setup any private agent in VSTS and install sonar or any subscription we need to add in Azure ( End point).Please share your thoughts on this.</p>

答:
You can create a Microsoft SQL Server VM in azure, then configure/install sonarqube and map 80 port (Public port) to Sonarqube port (default is 9000).
A related article: How to setup a SonarQube server in Azure.

On the other hand, the public IP address may be changed, you can use a static public IP address, more information you can refer to: Create a VM with a static public IP address using the Azure portal.

Regarding the sonarqube server just can be accessible from intranet, you need to setup a private build agent (can access that sonarqube from this build agent machine), then queue build with this private build agent.


问:
DocuSign REST API: Adding a Carbon Copy Recipient With Document Visibility
I can successfully add recipients to an existing DocuSign envelopes using REST API. When I add a signer to the envelope I am also able to specify the Document Visibility using excludedDocuments element. However I cannot set the document visibility using this parameter for the carbon copy recipient. My business requirement is that one carbon copy recipient should not receive some of the documents in the envelope.

Below is my JSON request:

```<code>{
  "carbonCopies": [
    {
      "email": "123@hotmail.com",
      "excludedDocuments": [
        "1"
      ],
      "name": "testCC1",
      "recipientId": "5"
    }
  ],
  "signers": [
    {
      "email": "123@gmail.com",
      "excludedDocuments": [
        "1"
      ],
      "name": "ssgmail signer",
      "recipientId": "7"
    }
  ]
}
</code>```

Both the above recipients are added successfully. The first recipient(signer) is setup properly without visibility to document 1. The second recipient(carbon copy) is set up with full visibility.

Interestingly I can go to DocuSign interface and correct the envelope to remove the visibility for the carbon copy recipient. So I think DocuSign does support this functionality.

Any idea how I can add/change the visibility of individual documents for the carbon copy recipient for an existing envelope using the rest / soap API?

Note:-

Frankly I do not know how to query the document visibility in an envelope/recipient using API. For this I go to the "View/Modify Document Visibility" link in the correct envelop screen to check the current visibility setting.

I have set the  the Document Visibility to "Must Sign to View Unless Sender Account" to enable the Document Visibility feature.

答:
You are missing one property in the JSON Request, "enforceSignerVisibility":true, I have below request which is working fine with DocumentVisibility:

```<code>{
  "documents": [
    {
      "documentBase64": "<Base64>",
      "documentId": "1",
      "fileExtension": "docx",
      "name": "Challenge3"
    },
    {
      "documentBase64": "<Base64>",
      "documentId": "2",
      "fileExtension": "docx",
      "name": "Challenge4"
    }
  ],
  "emailSubject": "Test Subject",
  "recipients": {
    "signers": [
      {
        "email": "Signer@gmail.com",
        "name": "Signer",
        "recipientId": "2",
        "routingOrder":1,
        "excludedDocuments":[2],
        "tabs": {
          "signHereTabs": [
            {
              "documentId": "1",
              "recipientId": "1",
              "xPosition": "300",
              "yPosition": "300",
              "pageNumber":1
            }
          ]
        }
      }
    ],
    "carbonCopies": [
      {
        "email": "CC@gmail.com",
        "name": "CC",
        "recipientId": "1",
        "routingOrder":1,
        "excludedDocuments":[1]
      }
    ]
  },
  "status": "sent",
  "enforceSignerVisibility":true
}
</code>```

Body:
I can successfully add recipients to an existing DocuSign envelopes using REST API. When I add a signer to the envelope I am also able to specify the Document Visibility using excludedDocuments element. However I cannot set the document visibility using this parameter for the carbon copy recipient. My business requirement is that one carbon copy recipient should not receive some of the documents in the envelope.

Below is my JSON request:

{
  "carbonCopies": [
    {
      "email": "123@hotmail.com",
      "excludedDocuments": [
        "1"
      ],
      "name": "testCC1",
      "recipientId": "5"
    }
  ],
  "signers": [
    {
      "email": "123@gmail.com",
      "excludedDocuments": [
        "1"
      ],
      "name": "ssgmail signer",
      "recipientId": "7"
    }
  ]
}

Both the above recipients are added successfully. The first recipient(signer) is setup properly without visibility to document 1. The second recipient(carbon copy) is set up with full visibility.

Interestingly I can go to DocuSign interface and correct the envelope to remove the visibility for the carbon copy recipient. So I think DocuSign does support this functionality.

Any idea how I can add/change the visibility of individual documents for the carbon copy recipient for an existing envelope using the rest / soap API?

Note:-

Frankly I do not know how to query the document visibility in an envelope/recipient using API. For this I go to the "View/Modify Document Visibility" link in the correct envelop screen to check the current visibility setting.

I have set the  the Document Visibility to "Must Sign to View Unless Sender Account" to enable the Document Visibility feature.

Body:
You are missing one property in the JSON Request, "enforceSignerVisibility":true, I have below request which is working fine with DocumentVisibility:

{
  "documents": [
    {
      "documentBase64": "<Base64>",
      "documentId": "1",
      "fileExtension": "docx",
      "name": "Challenge3"
    },
    {
      "documentBase64": "<Base64>",
      "documentId": "2",
      "fileExtension": "docx",
      "name": "Challenge4"
    }
  ],
  "emailSubject": "Test Subject",
  "recipients": {
    "signers": [
      {
        "email": "Signer@gmail.com",
        "name": "Signer",
        "recipientId": "2",
        "routingOrder":1,
        "excludedDocuments":[2],
        "tabs": {
          "signHereTabs": [
            {
              "documentId": "1",
              "recipientId": "1",
              "xPosition": "300",
              "yPosition": "300",
              "pageNumber":1
            }
          ]
        }
      }
    ],
    "carbonCopies": [
      {
        "email": "CC@gmail.com",
        "name": "CC",
        "recipientId": "1",
        "routingOrder":1,
        "excludedDocuments":[1]
      }
    ]
  },
  "status": "sent",
  "enforceSignerVisibility":true
}


问:
Passing an array of vectors to a uniform
I am trying to implement multiple lights in my shader but I have trouble to fill the uniform with my light data.

My vertex shader:

```<code>attribute vec3 aVertex;
attribute vec3 aNormal;
attribute vec2 aTexture;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat4 uNMatrix;

uniform vec3 uAmbientColor;
uniform vec3 uPointLightingLocation[16];
uniform vec3 uPointLightingColor[16];

varying vec2 vTexture;
varying vec3 vLightWeighting;

void main(void) {
    vec4 mvPosition = uMVMatrix * vec4(aVertex, 1.0);
    gl_Position = uPMatrix * mvPosition;
    vTexture = aTexture;

    int i;
    for (i = 0; i < 16; i++) {
        vec3 lightDirection = normalize(uPointLightingLocation[i] - mvPosition.xyz);
        vec4 transformedNormal = uNMatrix * vec4(aNormal, 1.0);
        float directionalLightWeighting = max(dot(transformedNormal.xyz, lightDirection), 0.0);
        if (i == 0) {
            vLightWeighting = uAmbientColor + uPointLightingColor[i] * directionalLightWeighting;
        } else {
            vLightWeighting = vLightWeighting * (uAmbientColor + uPointLightingColor[i] * directionalLightWeighting);
        }
    }
}
</code>```

Code that shows only the latest light:

```<code>for (var light in this.lightsDirection) {
    gl.uniform3fv(this.shaderProgram.pointLightingLocationUniform, this.lightsDirection[light]);
    gl.uniform3fv(this.shaderProgram.pointLightingColorUniform, this.lightsColor[light]);
}
</code>```

As the uniform uPointLightingLocation is a vec3 array with the size of 16, I thought that it would be possible to pass the complete array to the uniform, but I have no working solution.

When I try to pass the complete array this.lightsColor (without the index) I see no light at all.

答:
gl.uniform3fv expects a flattened array of floats.  Also, you are calling it multiple times with the same uniform location.  So, the last one wins.  Imagine that uniform3fv is a low-level copy command, and you give it (destination, source).  It just copies a buffer from one place to another.

Assuming your example has only 3 lights, you could assign the location uniform this way:

```<code>var locations = [
  1.0, 0, 0,
  0, 1.0, 0,
  0, 0, 0
];
gl.uniform3fv(shaderProgram.pointLightingLocationUniform, locations);
</code>```

I would also recommend using a more simple shader when you are debugging problems like this.  With something like the following in your vertex shader:

```<code>for (int i = 0; i < 3; i++) {
  vColor += uPointLightingLocation[i];
}
</code>```

And fragment shader:

```<code>gl_FragColor = vec4(vColor, 1);
</code>```

Then, if your polygons are yellow you know it is working.

Body:
I am trying to implement multiple lights in my shader but I have trouble to fill the uniform with my light data.

My vertex shader:

attribute vec3 aVertex;
attribute vec3 aNormal;
attribute vec2 aTexture;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat4 uNMatrix;

uniform vec3 uAmbientColor;
uniform vec3 uPointLightingLocation[16];
uniform vec3 uPointLightingColor[16];

varying vec2 vTexture;
varying vec3 vLightWeighting;

void main(void) {
    vec4 mvPosition = uMVMatrix * vec4(aVertex, 1.0);
    gl_Position = uPMatrix * mvPosition;
    vTexture = aTexture;

    int i;
    for (i = 0; i < 16; i++) {
        vec3 lightDirection = normalize(uPointLightingLocation[i] - mvPosition.xyz);
        vec4 transformedNormal = uNMatrix * vec4(aNormal, 1.0);
        float directionalLightWeighting = max(dot(transformedNormal.xyz, lightDirection), 0.0);
        if (i == 0) {
            vLightWeighting = uAmbientColor + uPointLightingColor[i] * directionalLightWeighting;
        } else {
            vLightWeighting = vLightWeighting * (uAmbientColor + uPointLightingColor[i] * directionalLightWeighting);
        }
    }
}

Code that shows only the latest light:

for (var light in this.lightsDirection) {
    gl.uniform3fv(this.shaderProgram.pointLightingLocationUniform, this.lightsDirection[light]);
    gl.uniform3fv(this.shaderProgram.pointLightingColorUniform, this.lightsColor[light]);
}

As the uniform uPointLightingLocation is a vec3 array with the size of 16, I thought that it would be possible to pass the complete array to the uniform, but I have no working solution.

When I try to pass the complete array this.lightsColor (without the index) I see no light at all.

Body:
gl.uniform3fv expects a flattened array of floats.  Also, you are calling it multiple times with the same uniform location.  So, the last one wins.  Imagine that uniform3fv is a low-level copy command, and you give it (destination, source).  It just copies a buffer from one place to another.

Assuming your example has only 3 lights, you could assign the location uniform this way:

var locations = [
  1.0, 0, 0,
  0, 1.0, 0,
  0, 0, 0
];
gl.uniform3fv(shaderProgram.pointLightingLocationUniform, locations);

I would also recommend using a more simple shader when you are debugging problems like this.  With something like the following in your vertex shader:

for (int i = 0; i < 3; i++) {
  vColor += uPointLightingLocation[i];
}

And fragment shader:

gl_FragColor = vec4(vColor, 1);

Then, if your polygons are yellow you know it is working.


问:
How to structure custom binary protocol TCP request
I'm working on a code challenge which, in short, provides a server that encodes/decodes the data sent in the request. It is a TCP/IP server with the following custom binary request/response structures:

I need to create a desktop client that will send requests and receive responses, and display data accordingly. I'm having trouble understanding how the request would be formed, and how I would send the request to the TCP/IP server (using C#). Could someone provide perhaps an example of what this might look like?

答:
not sure about your checksum, but constructing a packet would look something like

```<code>        byte[] CreatePacket(string s, Operation op)
        {
            var packet = new List<byte>();
            packet.AddRange(BitConverter.GetBytes((UInt16) 0x1092));
            packet.Add(1);
            var data = Encoding.ASCII.GetBytes(s);
            packet.AddRange(BitConverter.GetBytes((UInt32) (9 + data.Length)));
            packet.Add((byte) (op == Operation.Encode ? 1 : 2));
            packet.AddRange(data);
            packet.Add(CheckSum(packet));
            return packet.ToArray();
        }
</code>```

given

```<code>    enum Operation
    {
        Encode,
        Decode,
    }
</code>```

and

```<code>server.Send(CreatePacket("test string", Operation.Encode))
</code>```

Also with the checksum spec...

```<code>        byte CheckSum(List<byte> packet)
        {
            return (byte)(packet.Select((b, i) => (value: b, index: i))
                .Sum(o => (o.value & (1 << (o.index % 8))) > 0 ? 1 :0) % 256);
        }
</code>```

Body:
not sure about your checksum, but constructing a packet would look something like

        byte[] CreatePacket(string s, Operation op)
        {
            var packet = new List<byte>();
            packet.AddRange(BitConverter.GetBytes((UInt16) 0x1092));
            packet.Add(1);
            var data = Encoding.ASCII.GetBytes(s);
            packet.AddRange(BitConverter.GetBytes((UInt32) (9 + data.Length)));
            packet.Add((byte) (op == Operation.Encode ? 1 : 2));
            packet.AddRange(data);
            packet.Add(CheckSum(packet));
            return packet.ToArray();
        }

given

    enum Operation
    {
        Encode,
        Decode,
    }

and

server.Send(CreatePacket("test string", Operation.Encode))

Also with the checksum spec...

        byte CheckSum(List<byte> packet)
        {
            return (byte)(packet.Select((b, i) => (value: b, index: i))
                .Sum(o => (o.value & (1 << (o.index % 8))) > 0 ? 1 :0) % 256);
        }


问:
Django update fields base on the current fields values
Given the schema:

```<code>stats {
  id: integer
  total: integer
  total_accepted: integer
  total_rejecged: integer
}
</code>```

I need to update the record at one go like this:

```<code>UPDATE stats SET total = total + 1, total_accepted = total_accepted + 1 WHERE id=1
</code>```

So how to achieve it in Django without using a raw sql?

答:
What you need is the query expressions:

So using the query expressions (F() method) your query will look like this:

```<code>Stats.objects.filter(id=1).update(total=F('total') + 1, total_accepted=F('total_accepted') + 1)
</code>```

Body:
Given the schema:

stats {
  id: integer
  total: integer
  total_accepted: integer
  total_rejecged: integer
}

I need to update the record at one go like this:

UPDATE stats SET total = total + 1, total_accepted = total_accepted + 1 WHERE id=1

So how to achieve it in Django without using a raw sql?

Body:
What you need is the query expressions:

So using the query expressions (F() method) your query will look like this:

Stats.objects.filter(id=1).update(total=F('total') + 1, total_accepted=F('total_accepted') + 1)


问:
Receive data from Post request in TEST mode Django Rest
how i can get token in Test mode if it generates after login

```<code>client = APIClient()
client.post('/api/login/', {'username': 'username', 'password': 'password'}, format='json')
</code>```

and after request have to back response of Token key in json. Using requests to dev server works fine but how to use in TEST mode?

答:
You can you django-rest-framework test cases. When test case runs it will create a new database so we do not have any data in the database.
After it will call method setUp to create required data to be used in test.

```<code>from rest_framework.test import APITestCase

class AccountTests(APITestCase):

   def setUp(self):
       super(AccountTests, self).setUp()
       user = User.objects.create(user_name='username')
       user.set_password('password')
       user.save()
       self.token = Token.objects.create(user=user)

   def test_login(self):
      url = '/api/login/'
      data = {'username': 'username', 'password': 'password'}
      response = self.client.post(url, data, format='json')
      # key = response.json()['token']
      # self.assertEqual(key, self.token.key)
</code>```

Body:
how i can get token in Test mode if it generates after login

client = APIClient()
client.post('/api/login/', {'username': 'username', 'password': 'password'}, format='json')

and after request have to back response of Token key in json. Using requests to dev server works fine but how to use in TEST mode?

Body:
You can you django-rest-framework test cases. When test case runs it will create a new database so we do not have any data in the database.
After it will call method setUp to create required data to be used in test.

from rest_framework.test import APITestCase

class AccountTests(APITestCase):

   def setUp(self):
       super(AccountTests, self).setUp()
       user = User.objects.create(user_name='username')
       user.set_password('password')
       user.save()
       self.token = Token.objects.create(user=user)

   def test_login(self):
      url = '/api/login/'
      data = {'username': 'username', 'password': 'password'}
      response = self.client.post(url, data, format='json')
      # key = response.json()['token']
      # self.assertEqual(key, self.token.key)


问:
Join with Multiple Tables
I am getting a syntax error with the following problem and can't seem to figure out, hope you guys can help me!

I have these tables (they are populated):

I am trying to retrieve the first and last name of all the passengers scheduled in a certain flight number so what I have is this:

```<code>SELECT PassFName, PassLName
FROM Passenger
INNER JOIN PassID ON Passenger.PassID = Reservation.PassID
INNER JOIN FlightNum ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];
</code>```

However, I am getting error:

Not sure why and I have also noticed in the last line it is misspelling FlightNum.ScheduledFlight. Any idea what am I doing wrong?

Thank you!

答:
Gordon's point is valid, but he's got his parentheses misplaced and missed the other big issues. This query is more than a little whacked, with table names and field names flip-flopped. Here's what I would guess would work...</p>

```<code>SELECT
       PassFName
     , PassLName
FROM (
     Passenger
     INNER JOIN Reservation
        ON Passenger.PassID = Reservation.PassID
     )
INNER JOIN ScheduledFlight
    ON Reservation.FlightNum = ScheduledFlight.FlightNum
WHERE
     ScheduledFlight.FlightNum = [Enter Flight Number];
</code>```

Title: Join with Multiple Tables

Body:
I am getting a syntax error with the following problem and can't seem to figure out, hope you guys can help me!

I have these tables (they are populated):

I am trying to retrieve the first and last name of all the passengers scheduled in a certain flight number so what I have is this:

SELECT PassFName, PassLName
FROM Passenger
INNER JOIN PassID ON Passenger.PassID = Reservation.PassID
INNER JOIN FlightNum ON FlightNum.Reservation = FlightNum.ScheduledFlight
WHERE ScheduledFlight.FlightNum = [Enter Flight Number];

However, I am getting error:

Not sure why and I have also noticed in the last line it is misspelling FlightNum.ScheduledFlight. Any idea what am I doing wrong?

Thank you!

Body:
Gordon's point is valid, but he's got his parentheses misplaced and missed the other big issues. This query is more than a little whacked, with table names and field names flip-flopped. Here's what I would guess would work...

SELECT
       PassFName
     , PassLName
FROM (
     Passenger
     INNER JOIN Reservation
        ON Passenger.PassID = Reservation.PassID
     )
INNER JOIN ScheduledFlight
    ON Reservation.FlightNum = ScheduledFlight.FlightNum
WHERE
     ScheduledFlight.FlightNum = [Enter Flight Number];