问:
Read a zipped file as a pandas DataFrame
I'm trying to unzip a csv file and pass it into pandas so I can work on the file.

The code I have tried so far is:

```<code>import requests, zipfile, StringIO
r = requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip')
z = zipfile.ZipFile(StringIO.StringIO(r.content))
crime2013 = pandas.read_csv(z.read('crime_incidents_2013_CSV.csv'))
</code>```

After the last line, although python is able to get the file, I get a "does not exist" at the end of the error.

Can someone tell me what I'm doing incorrectly?

答:
For "zip" files, you can use import zipfile and your code will be working simply with these lines:

```<code>import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
   with z.open("Crime_Incidents_in_2013.csv") as f:
      train = pd.read_csv(f, header=0, delimiter="\t")
      print(train.head())    # print the first 5 rows
</code>```

And the result will be:

```<code>X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0  -77.054968548763071,38.899775938598317,0925135...
1  -76.967309569035052,38.872119553647011,1003352...
2  -76.996184958456539,38.927921847721443,1101010...
3  -76.943077541353617,38.883686046653935,1104551...
4  -76.939209158039446,38.892278093281632,1125028...
</code>```

Body:
I'm trying to unzip a csv file and pass it into pandas so I can work on the file.

The code I have tried so far is:

import requests, zipfile, StringIO
r = requests.get('http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip')
z = zipfile.ZipFile(StringIO.StringIO(r.content))
crime2013 = pandas.read_csv(z.read('crime_incidents_2013_CSV.csv'))

After the last line, although python is able to get the file, I get a "does not exist" at the end of the error.

Can someone tell me what I'm doing incorrectly?

Body:
For "zip" files, you can use import zipfile and your code will be working simply with these lines:

import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
   with z.open("Crime_Incidents_in_2013.csv") as f:
      train = pd.read_csv(f, header=0, delimiter="\t")
      print(train.head())    # print the first 5 rows

And the result will be:

X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0  -77.054968548763071,38.899775938598317,0925135...
1  -76.967309569035052,38.872119553647011,1003352...
2  -76.996184958456539,38.927921847721443,1101010...
3  -76.943077541353617,38.883686046653935,1104551...
4  -76.939209158039446,38.892278093281632,1125028...


来源: stackexchange

问:
Does RAML support multiple response schemas for the same content type?
In my project all POJO class are extending parent class.As my controller has one method whose return type is parent class but actually it is returning child class here I am using a concept of polymorphism i.e. I am typecasting the child class to parent class.

In the RAML generation code:
The RAML generator code basically it uses the method signature of the controller as the signature contains parent class so it will generate the schema of Parent but actually we need schema of actual response.

Is there any to add two schemas in API response of RAML?
Or
Is there any way to get the schema of actual response of API where polymorphism concept is used ?

答: Consider using Union Type and Discriminator. An instance of a union type must meet all restrictions of at least one of the associated type. So an instance of the union type defined as Phone|Notebook must be either an instance of Phone or Notebook (or both of them). Discriminator allows to infer the concrete type of an individual object at runtime, so it's similar to the concept of polymorphism.

ContentLicense: CC BY-SA 3.0


问:
Weird error in multi-line Batch-file printing

I've been working on a project for myself, that produces a grid in batch, that can have specific points accessed and altered for better graphics with batch games and the like.

@echo off
setlocal ENABLEDELAYEDEXPANSION

!x!
:::::::::::
:: ALIAS ::
:::::::::::
:@alias
    set x=exit/b
    goto:@main
    !x!
:::::::::::
:: MAIN  ::
:::::::::::
:@main
call:$Canvas _canvas 16 16 .
set px=%~1
set py=%~2
set _canvas_point[!px!][!py!]=#
!_canvas#draw!

!x!
:::::::::::
::OBJECTS::
:::::::::::
:@objects
!x!
:$Canvas
    set this=%~1
    set /a !this!_width=%~2
    set /a !this!_height=%~3
    set !this!_default_char=%~4
    set !this!#draw=call:#$canvas_proto_draw !this!
    for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_point[%%j][%%i]=!%this%_default_char!
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
    !x!
    :#$Canvas_proto_draw
        set this=%~1
        for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
        for /L %%i in (1, 1, !%this%_height!) do (
            echo !%this%_row[%%i]!
            )
    !x!
```

<p>My problem occurs with the final output: giving it <code>1, 1</code> will result in a point showing up roughly halfway across the top row. I have no idea why this occurs, and need help. I've combed through all of the output with echo turned on and the value <code>_canvas_point[1][1]</code> does get the value of <code>#</code> on the update.</p>

<p>Here is the output:</p>

<pre class="lang-batch-file prettyprint-override"><code>C:\Home>canvas 1 1
................#...............
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................

C:\Home>
</code>```

Here is a pastebin link with the output having @echo on

Quick things:
Yes, this is a feeble attempt at object oriented programming in batch-file
Yes, I know other languages are better for this kind of thing, I just want to do it with batch-file
Yes, I have weird stylistic choices with names and labels and such. It's so I can read it better, seeing as labels are used for both goto locations and function labels.

答:
Perhaps the below example comes close to what you're trying to accomplish (object oriented .BAT file approach):</p>

```<code>@echo off
setlocal ENABLEDELAYEDEXPANSION

rem  Initialize object "_canvas" (index numbers are row then column)
call :#$proto_init _canvas 16 16 .

rem  Set a few "_canvas" array characters to non-default values
call :#$proto_set  _canvas  1  1 ?
call :#$proto_set  _canvas  8  8 #
call :#$proto_set  _canvas 16 16 $

rem  Display "_canvas"
call :#$proto_draw _canvas
endlocal
exit/b

:#$proto_init
set /a %1_height=%2, %1_width=%3, %1_len=%2 * %3
set %1_default_char=%4
set %1_data=X
for /l %%i in (1, 1, !%1_len!) do set %1_data=!%1_data!!%1_default_char!
exit /b

:#$proto_set
for /f %%i in ('set /a ^(%2 - 1^) * !%1_height! + %3') do (
  for /f %%j in ('set /a %%i + 1') do (
     set %1_data=!%1_data:~0,%%i!%4!%1_data:~%%j!
  )
)
exit/b

:#$proto_draw
for /l %%w in (!%1_width!, 1, !%1_width!) do (
  for /l %%h in (1, %%w, !%1_len!) do echo !%1_data:~%%h,%%w!
)
exit /b
</code>```

Body:
I've been working on a project for myself, that produces a grid in batch, that can have specific points accessed and altered for better graphics with batch games and the like.

@echo off
setlocal ENABLEDELAYEDEXPANSION

!x!
:::::::::::
:: ALIAS ::
:::::::::::
:@alias
    set x=exit/b
    goto:@main
    !x!
:::::::::::
:: MAIN  ::
:::::::::::
:@main
call:$Canvas _canvas 16 16 .
set px=%~1
set py=%~2
set _canvas_point[!px!][!py!]=#
!_canvas#draw!

!x!
:::::::::::
::OBJECTS::
:::::::::::
:@objects
!x!
:$Canvas
    set this=%~1
    set /a !this!_width=%~2
    set /a !this!_height=%~3
    set !this!_default_char=%~4
    set !this!#draw=call:#$canvas_proto_draw !this!
    for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_point[%%j][%%i]=!%this%_default_char!
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
    !x!
    :#$Canvas_proto_draw
        set this=%~1
        for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
        for /L %%i in (1, 1, !%this%_height!) do (
            echo !%this%_row[%%i]!
            )
    !x!

My problem occurs with the final output: giving it 1, 1 will result in a point showing up roughly halfway across the top row. I have no idea why this occurs, and need help. I've combed through all of the output with echo turned on and the value _canvas_point[1][1] does get the value of # on the update.

Here is the output:

C:\Home>canvas 1 1
................#...............
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................

C:\Home>

Here is a pastebin link with the output having @echo on

Quick things:
Yes, this is a feeble attempt at object oriented programming in batch-file
Yes, I know other languages are better for this kind of thing, I just want to do it with batch-file
Yes, I have weird stylistic choices with names and labels and such. It's so I can read it better, seeing as labels are used for both goto locations and function labels.

Body:
Perhaps the below example comes close to what you're trying to accomplish (object oriented .BAT file approach):

@echo off
setlocal ENABLEDELAYEDEXPANSION

rem  Initialize object "_canvas" (index numbers are row then column)
call :#$proto_init _canvas 16 16 .

rem  Set a few "_canvas" array characters to non-default values
call :#$proto_set  _canvas  1  1 ?
call :#$proto_set  _canvas  8  8 #
call :#$proto_set  _canvas 16 16 $

rem  Display "_canvas"
call :#$proto_draw _canvas
endlocal
exit/b

:#$proto_init
set /a %1_height=%2, %1_width=%3, %1_len=%2 * %3
set %1_default_char=%4
set %1_data=X
for /l %%i in (1, 1, !%1_len!) do set %1_data=!%1_data!!%1_default_char!
exit /b

:#$proto_set
for /f %%i in ('set /a ^(%2 - 1^) * !%1_height! + %3') do (
  for /f %%j in ('set /a %%i + 1') do (
     set %1_data=!%1_data:~0,%%i!%4!%1_data:~%%j!
  )
)
exit/b

:#$proto_draw
for /l %%w in (!%1_width!, 1, !%1_width!) do (
  for /l %%h in (1, %%w, !%1_len!) do echo !%1_data:~%%h,%%w!
)
exit /b


问:
How to use login_reuqired on Update/Create/Delete Views in Django
I am trying to use @login_reuqired decorator. For normal functions it is working fine, but when i try to use it in my UpdateView i am getting this error "AttributeError: 'function' object has no attribute 'as_view'"

This is my view.py

```<code>@login_required
class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`
</code>```

This is in my urls.py

```<code> url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'),
</code>```

Any suggestions ?

答:
You need to decorate the dispatch method:

```<code>from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(RoomUpdate, self).dispatch(*args, **kwargs)
</code>```

or you can use login_required as a function in your urls.py like this:

```<code>from django.contrib.auth.decorators import login_required

url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', login_required(views.RoomUpdate.as_view()), name='room_update'),
</code>```

Since Django 1.9+ you also can use a mixin:

```<code>from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'
</code>```

Body:
I am trying to use @login_reuqired decorator. For normal functions it is working fine, but when i try to use it in my UpdateView i am getting this error "AttributeError: 'function' object has no attribute 'as_view'"

This is my view.py

@login_required
class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`

This is in my urls.py

 url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'),

Any suggestions ?

Body:
You need to decorate the dispatch method:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(RoomUpdate, self).dispatch(*args, **kwargs)

or you can use login_required as a function in your urls.py like this:

from django.contrib.auth.decorators import login_required

url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', login_required(views.RoomUpdate.as_view()), name='room_update'),

Since Django 1.9+ you also can use a mixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'


问:
I have an Alexa skill. How do I make it work with Google Home?
I’ve already built an Alexa skill, and now I want to make that available on Google Home. Do I have to start from scratch or can I reuse its code for Actions on Google?</p>

答:
This can be done but it will require some work and you will not have to rewrite all of your code.

Check out this video on developing a Google Home Action using API.AI (that is recommended).

Once you have done the basics and started understanding how Google Home Actions differ from Amazon Alexa Skills, you can simply transfer your logic over to be similar.  The idea of intents are very similar but they have different intricacies that you must learn.

When you execute an intent it seems as if your app logic will be similar in most cases.  It is just the setup, deploying and running that are different.


问:
Not receiving data from Android using TCP connection
I am trying to receive acceleration data from my android phone to my PC.

I have tried using this JAVA code for accessing and sending data from my android:

```<code> import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener{

    String mClientMsg = "";
    Thread myCommsThread = null;
    public static final String TAG = "SocketServer";
    private CommsThread commsThread = null;
    TextView tv;
    PrintWriter out;
    private float ax, ay, az;
    private long timenow = 0, timeprev = 0, timestamp =0 ;

    private SensorManager sm;
    private Sensor sensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sm.getSensorList(Sensor.TYPE_LINEAR_ACCELERATION).get(0);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
        this.commsThread = new CommsThread();
        this.myCommsThread = new Thread(this.commsThread);
        this.myCommsThread.start();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        sm.unregisterListener(this);
        if (commsThread != null) {
            commsThread.stopComms();
        }
    }

    Handler myHandler = new Handler(){
        public void handleMessage(Message msg){
            TextView status = (TextView) findViewById(R.id.textView3);
            status.setText("Status: Streaming Now!");
        }
    };

    class CommsThread implements Runnable {
        private volatile boolean stopFlag = false;
        private ServerSocket ss = null;
        private static final int SERVERPORT = 6000;
        public void run() {
            Socket s = null;
            try {
                ss = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                s = ss.accept();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            myHandler.sendEmptyMessage(0);

            while(!stopFlag){
                try {
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
                    out.printf("*#%3.2f#%3.2f#%3.2f#%2d#*\n",ax,ay,az,(int)timestamp );
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void stopComms() {
            // TODO Auto-generated method stub
            this.stopFlag = true;
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        ax = event.values[0];
        ay = event.values[1];
        az = event.values[2];
        timenow = event.timestamp;
        timestamp = (timenow - timeprev)/1000000;
        refreshDisplay();
    }

    private void refreshDisplay() {
        // TODO Auto-generated method stub
        String output = String.format("time: %d -- x:%03.2f | Y:%03.2f | Z:%03.2f", timestamp, ax,ay,az);
        timeprev = timenow;
        tv.setText(output);
    }
}
</code>```

and this python script as server at my PC:

```<code>    import socket
from time import *
import sys

serv=socket.socket()

HOST=''
PORT = 7000
#HOST="78.91.80.123" //here I use my IP
#ADDR = (HOST,PORT)
BUFSIZE = 4096

#bind our socket to the address
try:
    serv.bind((HOST, PORT))
    serv.listen(5)
    conn,addr = serv.accept()
except KeyboardInterrupt:
    print "Keyboard Interrupt"
    serv.close()
    exit(1)
try:
    for i in range(0,3100):
        data=conn.recv(4096)
        sys.stdout.flush()
        chunk=data.split()
        sys.stdout.write("0:%s\n" % chunk[-1]) # writes the last element in the list
        sleep(0.03)

    conn.close()
    sleep(10)

except KeyboardInterrupt:
    conn.close()
    print "bye!"
except IndexError:
    conn.close()
    print "indexError"
</code>```

I have tested the python script and it works, however when I open the app, Nothing is being sent to the PC. I am kind of new in protocols so i am still trying to figure out what happens.

答:
First, you are using two different port numbers. In your Python script, you have PORT = 7000 and in your Java code you have private static final int SERVERPORT = 6000;. These must match in order to create a connection, and make sure you aren't using this port for anything else on your machine.

If your Python script is running the server, then you shouldn't use a ServerSocket in your Java code. The ServerSocket waits for incoming connections from a client. To establish a connection to your server, you'd instead want to use:

```<code>Socket s = new Socket("78.91.80.123", SERVERPORT);
</code>```

From there, you can write to the socket by viewing some examples in the corresponding Java Documentation.

Body:
I am trying to receive acceleration data from my android phone to my PC.

I have tried using this JAVA code for accessing and sending data from my android:

 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener{

    String mClientMsg = "";
    Thread myCommsThread = null;
    public static final String TAG = "SocketServer";
    private CommsThread commsThread = null;
    TextView tv;
    PrintWriter out;
    private float ax, ay, az;
    private long timenow = 0, timeprev = 0, timestamp =0 ;

    private SensorManager sm;
    private Sensor sensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sm.getSensorList(Sensor.TYPE_LINEAR_ACCELERATION).get(0);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
        this.commsThread = new CommsThread();
        this.myCommsThread = new Thread(this.commsThread);
        this.myCommsThread.start();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        sm.unregisterListener(this);
        if (commsThread != null) {
            commsThread.stopComms();
        }
    }

    Handler myHandler = new Handler(){
        public void handleMessage(Message msg){
            TextView status = (TextView) findViewById(R.id.textView3);
            status.setText("Status: Streaming Now!");
        }
    };

    class CommsThread implements Runnable {
        private volatile boolean stopFlag = false;
        private ServerSocket ss = null;
        private static final int SERVERPORT = 6000;
        public void run() {
            Socket s = null;
            try {
                ss = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                s = ss.accept();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            myHandler.sendEmptyMessage(0);

            while(!stopFlag){
                try {
                    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
                    out.printf("*#%3.2f#%3.2f#%3.2f#%2d#*\n",ax,ay,az,(int)timestamp );
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        public void stopComms() {
            // TODO Auto-generated method stub
            this.stopFlag = true;
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        // TODO Auto-generated method stub
        ax = event.values[0];
        ay = event.values[1];
        az = event.values[2];
        timenow = event.timestamp;
        timestamp = (timenow - timeprev)/1000000;
        refreshDisplay();
    }

    private void refreshDisplay() {
        // TODO Auto-generated method stub
        String output = String.format("time: %d -- x:%03.2f | Y:%03.2f | Z:%03.2f", timestamp, ax,ay,az);
        timeprev = timenow;
        tv.setText(output);
    }
}

and this python script as server at my PC:

    import socket
from time import *
import sys

serv=socket.socket()

HOST=''
PORT = 7000
#HOST="78.91.80.123" //here I use my IP
#ADDR = (HOST,PORT)
BUFSIZE = 4096

#bind our socket to the address
try:
    serv.bind((HOST, PORT))
    serv.listen(5)
    conn,addr = serv.accept()
except KeyboardInterrupt:
    print "Keyboard Interrupt"
    serv.close()
    exit(1)
try:
    for i in range(0,3100):
        data=conn.recv(4096)
        sys.stdout.flush()
        chunk=data.split()
        sys.stdout.write("0:%s\n" % chunk[-1]) # writes the last element in the list
        sleep(0.03)

    conn.close()
    sleep(10)

except KeyboardInterrupt:
    conn.close()
    print "bye!"
except IndexError:
    conn.close()
    print "indexError"

I have tested the python script and it works, however when I open the app, Nothing is being sent to the PC. I am kind of new in protocols so i am still trying to figure out what happens.

Body:
First, you are using two different port numbers. In your Python script, you have PORT = 7000 and in your Java code you have private static final int SERVERPORT = 6000;. These must match in order to create a connection, and make sure you aren't using this port for anything else on your machine.

If your Python script is running the server, then you shouldn't use a ServerSocket in your Java code. The ServerSocket waits for incoming connections from a client. To establish a connection to your server, you'd instead want to use:

Socket s = new Socket("78.91.80.123", SERVERPORT);

From there, you can write to the socket by viewing some examples in the corresponding Java Documentation.


问:
Using New-SelfSignedCertificate for wildcard certificates
I have found this answer, but it doesn't seem to work when trying to create a wildcard certificate.

I have taken the following steps:

Added a certificate to my server with the Powershell command.

New-SelfSignedCertificate -DnsName myhostname01,*.myhostname01 -CertStoreLocation Cert:\LocalMachine\My
(I slightly censored the URL to avoid potentially unsafe situations).

Next, I used the SSL certificate in a binding on my IIS server.

I visited the page in Chrome. As expected, the certificate is marked unsafe.

I saved a local copy of the certificate, and manually added a copy of of the certificate to my Chrome trusted CA's. However, the certificate is still not recognized:

The details of the certificate look like this:

Now, the certificates and URL I am visiting and have set up in my hosts file are all the same. There are no spelling errors. My question: am I using New-SelfSignedCertificate wrong? Or am I doing something wrong somewhere else?

答:
For anyone else who might arrive at this question clinging onto what's left of their sanity, the answer that ended up working for me was this:

New-SelfSignedCertificate -Subject *.my.domain -DnsName my.domain, *.my.domain -CertStoreLocation Cert:\LocalMachine\My -NotAfter (Get-Date).AddYears(10)


问:
Pass data between UIview inside ViewController
I have a Viewcontroller, and it has a View outsite it (in between those 3 symbols (viewcontroller, first responder, exit)), and when I click on a button it shows up my View, then I created a class file for it, and the textfields data inside this View has to come back to the ViewController.
How do I do that? I only know the method by segues.
tks</p>

答:
Tell your view controller it conforms to UITextFieldDelegate protocol.

```<code>class MyViewController : UIViewController <UITextFieldDelegate>
</code>```

Ensure your UITextField delegate property is connected to the view controller.  You can do this through IB or through code.

```<code>@IBOutlet weak var myTextField: UITextField!

//... later on...

myTextField.delegate = self
</code>```

Implement any UITextFieldDelegate method from the reference in your view controller.  Example:

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("text value is: \(textField.text)")
}
</code>```

Body:
Tell your view controller it conforms to UITextFieldDelegate protocol.

class MyViewController : UIViewController <UITextFieldDelegate>

Ensure your UITextField delegate property is connected to the view controller.  You can do this through IB or through code.

@IBOutlet weak var myTextField: UITextField!

//... later on...

myTextField.delegate = self

Implement any UITextFieldDelegate method from the reference in your view controller.  Example:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("text value is: \(textField.text)")
}


问:
post and get with same method signature
In my controller I have two actions called "Friends". The one that executes depends on whether or not it's a "get" versus a "post".

So my code snippets look something like this:

```<code>// Get:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

// Post:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}
</code>```

However, this does not compile since I have two methods with the same signature (Friends). How do I go about creating this? Do I need to create just one action but differentiate between a "get" and "post" inside of it? If so, how do I do that?

答:
Your action methods can't be doing the same thing, otherwise there would be no need to to write two action methods. So if the semantics are different, why not use different names for the action methods as well?

For example, if you had a "delete" action method and GET just asks for confirmation, you might call the GET method "ConfirmDelete" and the POST method just "Delete".

Not sure if that matches your scenario, but it always did for me when I had the same problem.

ContentLicense: CC BY-SA 2.5

Title: post and get with same method signature

Body:
In my controller I have two actions called "Friends". The one that executes depends on whether or not it's a "get" versus a "post".

So my code snippets look something like this:

// Get:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

// Post:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Friends()
{
    // do some stuff
    return View();
}

However, this does not compile since I have two methods with the same signature (Friends). How do I go about creating this? Do I need to create just one action but differentiate between a "get" and "post" inside of it? If so, how do I do that?


问:
Dropdown menu shows up briefly then disappears
I'm creating a dropdown menu for my Chrome extension.  There is some Javascript code that causes the menu to show up, but when I click the button, the dropdown menu only shows up for a split second before disappearing (looks like a flicker effect). Any help would be appreciated.  Thanks!

welcome.html

```<code> <form>
                <div class="dropdown">
                <button id="dropdownbtn" class="dropbtn">Dropdown</button>
                  <div id="myDropdown" class="dropdown-content">
                    <a href="#home">Home</a>
                    <a href="#about">About</a>
                    <a href="#contact">Contact</a>
                  </div>
                </div>
                <input type="submit" id="signup" value="Get Started">
            </form>
</code>```

interface.js

```<code>    //Add dropdown
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById("dropdownbtn").addEventListener("click", myFunction);
      //  document.getElementById("dropdownbtn").addEventListener("mouseout", myFunction);
    });

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction()  {
    console.log("in toggle");

    document.getElementById("myDropdown").classList.toggle("show");

}
</code>```

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "./icons/icon.png",
    "default_popup":  "account.html"
  },
  "manifest_version": 2,
  "content_scripts": [
    {
        "css": ["style.css"],

      "js": [ "content.bundle.js", "interface.js" ],
        "matches": ["<all_urls>"]
    }
  ]
}
</code>```

答: Maybe someone can explain why, but it appears to be because you are using a <form> element to wrap the button. Removing this and re-running the above seems to keep the dropdown active indefinitely. Perhaps the way its written assumes clicking the dropdown is submitting the form, but there is nothing to submit?

Body:
I'm creating a dropdown menu for my Chrome extension.  There is some Javascript code that causes the menu to show up, but when I click the button, the dropdown menu only shows up for a split second before disappearing (looks like a flicker effect). Any help would be appreciated.  Thanks!

welcome.html

 <form>

                <button id="dropdownbtn" class="dropbtn">Dropdown</button>

                    Home
                    About
                    Contact

                <input type="submit" id="signup" value="Get Started">
            </form>

interface.js

    //Add dropdown
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById("dropdownbtn").addEventListener("click", myFunction);
      //  document.getElementById("dropdownbtn").addEventListener("mouseout", myFunction);
    });

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction()  {
    console.log("in toggle");

    document.getElementById("myDropdown").classList.toggle("show");

}

manifest.json

{
  "manifest_version": 2,

  "name": "Hello World",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "./icons/icon.png",
    "default_popup":  "account.html"
  },
  "manifest_version": 2,
  "content_scripts": [
    {
        "css": ["style.css"],

      "js": [ "content.bundle.js", "interface.js" ],
        "matches": ["<all_urls>"]
    }
  ]
}


问:
ttl not expired in JWT Auth Laravel
```<code>'ttl' => null,
'refresh_ttl' => null,
</code>```

I need the token does not expire..
It does not work, it always returns "error": "token expired"

答:
In the file vendor/tymon/jwt-auth/config/config.php change the line

```<code>'ttl' => env('JWT_TTL', 60),
</code>```

by the

```<code>'ttl' => env('JWT_TTL', null),
</code>```

Also remove exp in this line

```<code> 'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],
</code>```

Works for my

Title: ttl not expired in JWT Auth Laravel

Body:
'ttl' => null,
'refresh_ttl' => null,

I need the token does not expire..
It does not work, it always returns "error": "token expired"

Body:
In the file vendor/tymon/jwt-auth/config/config.php change the line

'ttl' => env('JWT_TTL', 60),

by the

'ttl' => env('JWT_TTL', null),

Also remove exp in this line

 'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

Works for my


问:
IConversionManager not found in documents4j while converting docx to pdf (have all the binaries)
```<code>Exception in thread "main" java.lang.NoClassDefFoundError:
com/documents4j/conversion/IConversionManager at
com.test.resume.Documents4jPOC.main(Documents4jPOC.java:29)
Caused by: java.lang.ClassNotFoundException:
com.documents4j.conversion.IConversionManager
at java.net.URLClassLoader$1.run(URLClassLoader.java:428)
at java.net.URLClassLoader$1.run(URLClassLoader.java:417)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:416)
at java.lang.ClassLoader.loadClass(ClassLoader.java:494)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:357)
at java.lang.ClassLoader.loadClass(ClassLoader.java:427)
</code>```

I'm getting the above exception when trying to convert docx to pdf using documents4j. What am I missing ?

答: You are missing the API package which contains this class. Ideally, use Maven or another tool for managing your dependencies what avoids such errors.</p>

Body:
Exception in thread "main" java.lang.NoClassDefFoundError:
com/documents4j/conversion/IConversionManager at
com.test.resume.Documents4jPOC.main(Documents4jPOC.java:29)
Caused by: java.lang.ClassNotFoundException:
com.documents4j.conversion.IConversionManager
at java.net.URLClassLoader$1.run(URLClassLoader.java:428)
at java.net.URLClassLoader$1.run(URLClassLoader.java:417)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:416)
at java.lang.ClassLoader.loadClass(ClassLoader.java:494)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:357)
at java.lang.ClassLoader.loadClass(ClassLoader.java:427)

I'm getting the above exception when trying to convert docx to pdf using documents4j. What am I missing ?


问:
How to use cscope for a project which has .c , .cpp and .h files?
I am working on a project which requires the understanding of llvm compiler source-code. To browse source code of llvm, I tried to use cscope with following command in the root directory of the source:

cscope -R *

But it doesn't work. As there are mainly .cpp and .h files but some .c files are also there. So now I don't have a clue how to make cscope work? Can someone please help?

答:
Just because this is still the most popular entry. The stdin thingy may have been added in the meantime or not, but it makes it kind of elegant:</p>

```<code>find -regex '.*\.\(c\|h\|cpp\|cxx\|hh\|hpp\|hxx\)$' | cscope -i- -b -q
</code>```

Body:
Just because this is still the most popular entry. The stdin thingy may have been added in the meantime or not, but it makes it kind of elegant:

find -regex '.*\.\(c\|h\|cpp\|cxx\|hh\|hpp\|hxx\)$' | cscope -i- -b -q


问:
When building Jenkins in Docker plugins fail to install
I have a Dockerfile for a custom Jenkins master like so:

```<code>FROM jenkins
MAINTAINER me

USER root

RUN echo 2.0 > /usr/share/jenkins/ref/jenkins.install.UpgradeWizard.state

RUN apt-get update \
      && apt-get install -y sudo \
      && apt-get install -y vim \
      && rm -rf /var/lib/apt/lists/*
RUN echo "jenkins ALL=NOPASSWD: ALL" >> /etc/sudoers

USER jenkins

# COPY plugins.txt /usr/share/jenkins/plugins.txt
# RUN /usr/local/bin/plugins.sh /usr/share/jenkins/plugins.txt
ENV JAVA_OPTS="-Xmx8192m"
ENV JENKINS_OPTS="--handlerCountStartup=100 --handlerCountMax=300"

RUN /usr/local/bin/install-plugins.sh git:2.6.0
</code>```

Everything works fine until the RUN /usr/local/bin/install-plugins.sh git:2.6.0 line. I get an error installing the plugins:

```<code>Creating initial locks...

Analyzing war...

Downloading plugins...
Downloading plugin: git from https://updates.jenkins.io/download/plugins/git/2.6.0/git.hpi
Downloading plugin: git-plugin from https://updates.jenkins.io/download/plugins/git-plugin/2.6.0/git-plugin.hpi
Failed to download plugin: git or git-plugin

WAR bundled plugins:

Installed plugins:
*:

Some plugins failed to download!
Not downloaded: git
The command '/bin/sh -c /usr/local/bin/install-plugins.sh git:2.6.0' returned a non-zero code: 1
</code>```

Am I doing something wrong or is this an issue with Jenkins/Docker?

答:
I had a very similar issue and the solution for me was to specify the proxy within the Docker file prior to plugin install. Below is the snippet of my Dockerfile</p>

```<code>FROM jenkins:latest
MAINTAINER Jose Estrada
USER root
ENV JAVA_OPTS="--handlerCountStartup=100 --handlerCountMax=300 --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhttps.proxyHost=proxy-wsa.esl.cisco.com -Dhttps.proxyPort=80"
ENV http_proxy <PROXY Settings>
ENV https_proxy <PROXY Settings>
RUN /usr/local/bin/install-plugins.sh cisco-spark-notifier:latest
</code>```

Body:
I have a Dockerfile for a custom Jenkins master like so:

FROM jenkins
MAINTAINER me

USER root

RUN echo 2.0 > /usr/share/jenkins/ref/jenkins.install.UpgradeWizard.state

RUN apt-get update \
      && apt-get install -y sudo \
      && apt-get install -y vim \
      && rm -rf /var/lib/apt/lists/*
RUN echo "jenkins ALL=NOPASSWD: ALL" >> /etc/sudoers

USER jenkins

# COPY plugins.txt /usr/share/jenkins/plugins.txt
# RUN /usr/local/bin/plugins.sh /usr/share/jenkins/plugins.txt
ENV JAVA_OPTS="-Xmx8192m"
ENV JENKINS_OPTS="--handlerCountStartup=100 --handlerCountMax=300"

RUN /usr/local/bin/install-plugins.sh git:2.6.0

Everything works fine until the RUN /usr/local/bin/install-plugins.sh git:2.6.0 line. I get an error installing the plugins:

Creating initial locks...

Analyzing war...

Downloading plugins...
Downloading plugin: git from https://updates.jenkins.io/download/plugins/git/2.6.0/git.hpi
Downloading plugin: git-plugin from https://updates.jenkins.io/download/plugins/git-plugin/2.6.0/git-plugin.hpi
Failed to download plugin: git or git-plugin

WAR bundled plugins:

Installed plugins:
*:

Some plugins failed to download!
Not downloaded: git
The command '/bin/sh -c /usr/local/bin/install-plugins.sh git:2.6.0' returned a non-zero code: 1

Am I doing something wrong or is this an issue with Jenkins/Docker?

Body:
I had a very similar issue and the solution for me was to specify the proxy within the Docker file prior to plugin install. Below is the snippet of my Dockerfile

FROM jenkins:latest
MAINTAINER Jose Estrada
USER root
ENV JAVA_OPTS="--handlerCountStartup=100 --handlerCountMax=300 --logfile=/var/log/jenkins/jenkins.log --webroot=/var/cache/jenkins/war -Dhttps.proxyHost=proxy-wsa.esl.cisco.com -Dhttps.proxyPort=80"
ENV http_proxy <PROXY Settings>
ENV https_proxy <PROXY Settings>
RUN /usr/local/bin/install-plugins.sh cisco-spark-notifier:latest


问:
Use response of XMLHttpRequest
I'm new in JS and I'm trying to create a function that check something before submit a form.
On  html I have:

```<code><form name="loginform" method="post" onsubmit="return foo()" action="adminlogin.php"> ... </form>
</code>```

The function foo() is:

```<code>foo(){
  if(..){
  return false;
  }
  else{
        var url = "credenziali.php";
        var params = "name="+username+"&password="+password;
        var http_r = new XMLHttpRequest();
        http_r.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //something
            }
        };
        http_r.open("GET", url+"?name="+username+"&pass="+password, true);
        http_r.send();
        // here I want to return false or true dependence of responseText
    }
</code>```

the comment in the function is where I want use the what the request returns.
How can I do?

答:
Try insert this before http_r.send() with your return inside.

http_r.onload = function() {
  if (http_r.status >= 200 && http_r.status < 400) {
    // Success!
  } else {
    // We reached our target server, but it returned an error
  }
};```

Title: Use response of XMLHttpRequest

Body:
I'm new in JS and I'm trying to create a function that check something before submit a form.
On  html I have:

<form name="loginform" method="post" onsubmit="return foo()" action="adminlogin.php"> ... </form>

The function foo() is:

foo(){
  if(..){
  return false;
  }
  else{
        var url = "credenziali.php";
        var params = "name="+username+"&password="+password;
        var http_r = new XMLHttpRequest();
        http_r.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //something
            }
        };
        http_r.open("GET", url+"?name="+username+"&pass="+password, true);
        http_r.send();
        // here I want to return false or true dependence of responseText
    }

the comment in the function is where I want use the what the request returns.
How can I do?


问:
Centering Bootstrap columns when they are aligned vertically
I am having a bit of trouble with bootstrap columns centering when it is collapsed to mobile view;

Some Text

more text here

```

I am using code similar to this and when I go into chrome inspect element and click the mobile button and collapse the view the first column will go on top of the second column but will not center in the middle of the page which is what I want. Do you have any ideas how I would fix this?

答:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Some Text

more text here

 ```

Here is the jsfiddle

Body:
I am having a bit of trouble with bootstrap columns centering when it is collapsed to mobile view;

Some Text

more text here

I am using code similar to this and when I go into chrome inspect element and click the mobile button and collapse the view the first column will go on top of the second column but will not center in the middle of the page which is what I want. Do you have any ideas how I would fix this?

Body:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 <div class="container">
 <div class="row">
 <div class="col-lg-2 col-xs-offset-2">
        <h1>Some Text</h1>
        <img src="http://via.placeholder.com/200x100">
    </div>
    <div class="col-lg-4">
        <h2>more text here</h2>
    </div>

 </div>
 </div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Here is the jsfiddle


问:
Best Logic to Print Prime Numbers with SQL query
What is the most efficient way to get prime numbers from 2 to 1000 via SQL in MongoDB/MySQL/CockroachDB?

My query in Oracle:

```<code>WITH NUM AS (
    SELECT LEVEL N
    FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
    SELECT  N,
            CASE WHEN EXISTS (
                                SELECT NULL
                                FROM NUM N_INNER
                                WHERE N_INNER .N > 1
                                AND N_INNER.N < NUM.N
                                AND MOD(NUM.N, N_INNER.N)=0
                            ) THEN
                'NO PRIME'
            ELSE
                'PRIME'
            END IS_PRIME
        FROM NUM
    ) B
WHERE B.IS_PRIME='PRIME'
AND B.N!=1;
</code>```

答:
Tested on sqlite3

```<code>WITH nums(n) AS
(
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM nums WHERE n < 100
)

SELECT n
FROM (
  SELECT n FROM nums
)
WHERE n NOT IN (
  SELECT n
  FROM nums
  JOIN ( SELECT n AS n2 FROM nums )
  WHERE n  <> 1
    AND n2 <> 1
    AND n  <> n2
    AND n2 <  n
    AND n % n2 = 0
  ORDER BY n
)
AND n <> 1
</code>```

Tested on Vertica 8

```<code>WITH seq AS (
  SELECT ROW_NUMBER() OVER() AS n
  FROM (
      SELECT 1
      FROM (
          SELECT date(0) + INTERVAL '1 second' AS i
          UNION ALL
          SELECT date(0) + INTERVAL '100 seconds' AS i
      ) _
      TIMESERIES tm AS '1 second' OVER(ORDER BY i)
  ) _
)
SELECT n
FROM (SELECT n FROM seq) _
WHERE n NOT IN (
  SELECT n FROM (
    SELECT s1.n AS n, s2.n AS n2
    FROM seq AS s1
    CROSS JOIN seq AS s2
    ORDER BY n, n2
  ) _
  WHERE n  <> 1
    AND n2 <> 1
    AND n  <> n2
    AND n2 <  n
    AND n % n2 = 0
)
AND n <> 1
ORDER BY n
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is the most efficient way to get prime numbers from 2 to 1000 via SQL in MongoDB/MySQL/CockroachDB?

My query in Oracle:

WITH NUM AS (
    SELECT LEVEL N
    FROM DUAL CONNECT BY LEVEL <= 1000
)
SELECT LISTAGG(B.N,'-') WITHIN GROUP(ORDER BY B.N) AS PRIMES
FROM (
    SELECT  N,
            CASE WHEN EXISTS (
                                SELECT NULL
                                FROM NUM N_INNER
                                WHERE N_INNER .N > 1
                                AND N_INNER.N < NUM.N
                                AND MOD(NUM.N, N_INNER.N)=0
                            ) THEN
                'NO PRIME'
            ELSE
                'PRIME'
            END IS_PRIME
        FROM NUM
    ) B
WHERE B.IS_PRIME='PRIME'
AND B.N!=1;

Body:
Tested on sqlite3

WITH nums(n) AS
(
    SELECT 1
    UNION ALL
    SELECT n + 1 FROM nums WHERE n < 100
)

SELECT n
FROM (
  SELECT n FROM nums
)
WHERE n NOT IN (
  SELECT n
  FROM nums
  JOIN ( SELECT n AS n2 FROM nums )
  WHERE n  <> 1
    AND n2 <> 1
    AND n  <> n2
    AND n2 <  n
    AND n % n2 = 0
  ORDER BY n
)
AND n <> 1

Tested on Vertica 8

WITH seq AS (
  SELECT ROW_NUMBER() OVER() AS n
  FROM (
      SELECT 1
      FROM (
          SELECT date(0) + INTERVAL '1 second' AS i
          UNION ALL
          SELECT date(0) + INTERVAL '100 seconds' AS i
      ) _
      TIMESERIES tm AS '1 second' OVER(ORDER BY i)
  ) _
)
SELECT n
FROM (SELECT n FROM seq) _
WHERE n NOT IN (
  SELECT n FROM (
    SELECT s1.n AS n, s2.n AS n2
    FROM seq AS s1
    CROSS JOIN seq AS s2
    ORDER BY n, n2
  ) _
  WHERE n  <> 1
    AND n2 <> 1
    AND n  <> n2
    AND n2 <  n
    AND n % n2 = 0
)
AND n <> 1
ORDER BY n


问:
How would you represent a hashtable collection in a database schema?
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

```<code>public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}
</code>```

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

```<code>table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}
</code>```

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

答:
In the simplest case, the dictionary has a key which would map to the primary key of a table - so that when you specify the values of the key, you can immediately find the matching data via a simple lookup.

In this case, you would need a table SpaceQuadrant with any general (single-valued) attributes that describe or characterize a space quadrant.  The SpaceQuadrant table would have a primary key, possibly a generated ID, possibly a natural value.  The hashtable would then consist of a table with the primary key value for cross-referencing the SpaceQuadrant, with the position (a SpaceCoordinate) and the attributes of the quadrant and coordinate.

Now, if you have an extensible DBMS, you can define a user-defined type for the SpaceCoordinate; failing that, you can use a trio of columns - x, y, z or r, theta, rho, for example - to represent the position (SpaceCoordinate).

In general terms, the structure I'm describing is quite similar to Bill Karwin's; the key (pun not intended until after I was rereading the message) difference is that it is perfectly OK in my book to have the position as part of the primary key of the sub-ordinate table if you are sure that's the best way to organize it.  You might also have an object ID column that is an alternative candidate key.  Alternatively, if objects have an existence independent of the space quadrant they happen to be in at the moment (or can exist in multiple positions - because they aren't points but are space stations or something), then you might have the SpaceObject in a separate table.  What is best depends on information that we don't have available to us.

You should be aware of the limitations of using a SpaceCoordinate as part of the primary key:

no two objects can occupy the same position (that's called a collision in a hash table, as well as in 3D space),

if the position changes, then you have to update the key data, which is more expensive than an update up non-key data,

proximity lookups will be hard - exact lookups are easy enough.

The same is true of your dictionary in memory; if you change the coordinates, you have to remove the record from the old location and place it in the new location in the dictionary (or the language has to do that for you behind the scenes).

Body:
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

OwnerDisplayName: Jonathan Leffler


问:
WPF Binding: How to databind to Grid?
I have created a class Account.

Next, I have created another class ReorderWindowController which has a field/property SelectedAccount of type Account.

Finally, I have written ReorderWindow WPF window xaml file:

```<code><Window ...

    <Window.Resources>

        <contollers:ReorderWindowController x:Key="WindowController" />

        <DataTemplate DataType="{x:Type entities:Account}">
            <Grid Width="140" Height="50" Margin="5">
                <TextBlock Text="Some awesome text" />
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="Even more awesome text" />
            </Grid>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <Grid
            Name="AccountGrid"
            DataContext="{Binding Source={StaticResource ResourceKey=WindowController},
                          Path=SelectedAccount}">
        </Grid>
    </Grid>

</Window>
</code>```

When I run my code, AccountGrid is not showing anything. Why? How do I make object data bind to the Grid and how do I make it use my data template? Thanks.

答:
Instead of a Grid use a ContentPresenter like this:</p>

```<code><Grid>
<ContentPresenter
Name="AccountGrid"
Content="{Binding Source={StaticResource ResourceKey=WindowController},                           Path=SelectedAccount}">
   </ContentPresenter>
</Grid>
</code>```

Title: WPF Binding: How to databind to Grid?

Body:
I have created a class Account.

Next, I have created another class ReorderWindowController which has a field/property SelectedAccount of type Account.

Finally, I have written ReorderWindow WPF window xaml file:

<Window ...

    <Window.Resources>

        <contollers:ReorderWindowController x:Key="WindowController" />

        <DataTemplate DataType="{x:Type entities:Account}">
            <Grid Width="140" Height="50" Margin="5">
                <TextBlock Text="Some awesome text" />
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="Even more awesome text" />
            </Grid>
        </DataTemplate>

    </Window.Resources>

    <Grid>
        <Grid
            Name="AccountGrid"
            DataContext="{Binding Source={StaticResource ResourceKey=WindowController},
                          Path=SelectedAccount}">
        </Grid>
    </Grid>

</Window>

When I run my code, AccountGrid is not showing anything. Why? How do I make object data bind to the Grid and how do I make it use my data template? Thanks.

Body:
Instead of a Grid use a ContentPresenter like this:

<Grid>
<ContentPresenter
Name="AccountGrid"
Content="{Binding Source={StaticResource ResourceKey=WindowController},                           Path=SelectedAccount}">
   </ContentPresenter>
</Grid>


问:
Matching any route using $urlRouterProvider in AngularJS and Angular-UI-Router
I'm not an AngularJS dev but I was handed a project.

Now I need to call the following method, every time a route changes. doesn't matter to which route, just any route.

```<code>window.Intercom("update");
</code>```

Now I found the following piece of code.

```<code>function config($urlRouterProvider, $stateProvider, $translateProvider, $locationProvider, $httpProvider) {
</code>```

So in that method I have access to the $urlRouterProvider, I read in the docs that here it's possible to check for matched routes, even with regex.

Now I'm wondering, is it possible to see any time the router changes url, Am I looking in the right direction?

答:
If you're using the new Angular UI Router version 1.xx

You could just use a run block like so:

```<code>angular.module('whatever').run(function($transitions){
    $transitions.onSuccess({}, function(){
        window.Intercom("update");
    });
});
</code>```

If you're using the legacy version of Angular UI Router you could just subscribe to $stateChangeSuccess events like so:

```<code>angular.module('whatever').run(function($rootScope){
    $rootScope.$on('$stateChangeSuccess', function(){
        window.Intercom("update");
    });
});
</code>```

Body:
I'm not an AngularJS dev but I was handed a project.

Now I need to call the following method, every time a route changes. doesn't matter to which route, just any route.

window.Intercom("update");

Now I found the following piece of code.

function config($urlRouterProvider, $stateProvider, $translateProvider, $locationProvider, $httpProvider) {

So in that method I have access to the $urlRouterProvider, I read in the docs that here it's possible to check for matched routes, even with regex.

Now I'm wondering, is it possible to see any time the router changes url, Am I looking in the right direction?

Body:
If you're using the new Angular UI Router version 1.xx

You could just use a run block like so:

angular.module('whatever').run(function($transitions){
    $transitions.onSuccess({}, function(){
        window.Intercom("update");
    });
});

If you're using the legacy version of Angular UI Router you could just subscribe to $stateChangeSuccess events like so:

angular.module('whatever').run(function($rootScope){
    $rootScope.$on('$stateChangeSuccess', function(){
        window.Intercom("update");
    });
});


问:
hyperledger-fabric peer0 environment
I am very new to this subject and I have to go through a fabric-sample.
But at this point I have problem
Environment variables

```<code># Environment variables for PEER0

CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
CORE_PEER_ADDRESS=peer0.org1.example.com:7051
CORE_PEER_LOCALMSPID="Org1MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
</code>```

But my docker-compose-base.yaml file has the following lines

```<code>environment:
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP
</code>```

When I run this command

```<code>peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls $CORE_PEER_TLS_ENABLED --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
</code>```

I have this error message

```<code>INFO 004 MSP configuration file not found at [/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/config.yaml]: [stat /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/config.yaml: no such file or directory]
</code>```

I am sure this error message cased by the missing/different lines in my docker-compose-base.yaml

What could I do in this case?
Just put these lines in my file?
Or something has gone wrong at some point what I did not realize?

Please bear with me as I just have started.

Thank you

edit: I have this error message

```<code>Error: Got unexpected status: BAD_REQUEST
Usage:
  peer channel create [flags]
</code>```

答:
That's not an error message, but an INFO one.
an MSP can be configured to have an OU by having that config file with the following fields in it:

```<code>OrganizationalUnitIdentifiers:
  - Certificate: "cacerts/cacert.pem"
OrganizationalUnitIdentifier: "COP"
</code>```

It's perfectly fine not to have this file and to see this INFO message.

Title: hyperledger-fabric peer0 environment

Body:
I am very new to this subject and I have to go through a fabric-sample.
But at this point I have problem
Environment variables

# Environment variables for PEER0

CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
CORE_PEER_ADDRESS=peer0.org1.example.com:7051
CORE_PEER_LOCALMSPID="Org1MSP"
CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt

But my docker-compose-base.yaml file has the following lines

environment:
      - CORE_PEER_ID=peer0.org1.example.com
      - CORE_PEER_ADDRESS=peer0.org1.example.com:7051
      - CORE_PEER_GOSSIP_EXTERNALENDPOINT=peer0.org1.example.com:7051
      - CORE_PEER_LOCALMSPID=Org1MSP

When I run this command

peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls $CORE_PEER_TLS_ENABLED --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem

I have this error message

INFO 004 MSP configuration file not found at [/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/config.yaml]: [stat /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/config.yaml: no such file or directory]

I am sure this error message cased by the missing/different lines in my docker-compose-base.yaml

What could I do in this case?
Just put these lines in my file?
Or something has gone wrong at some point what I did not realize?

Please bear with me as I just have started.

Thank you

edit: I have this error message

Error: Got unexpected status: BAD_REQUEST
Usage:
  peer channel create [flags]

Body:
That's not an error message, but an INFO one.
an MSP can be configured to have an OU by having that config file with the following fields in it:

OrganizationalUnitIdentifiers:
  - Certificate: "cacerts/cacert.pem"
OrganizationalUnitIdentifier: "COP"

It's perfectly fine not to have this file and to see this INFO message.


问:
Time format not persisting
I have a calculation sheet, that checks if the rawdata has nothing in it, and if not, it will print the value of the cell.

Somehow, the timeformat is now left centered even though the cell-format and everything is the same as the above data.

I have tinkered with it for hours now and found no solution, so here i am hoping that someone knows what's going on.

SAMPLE FILE: https://ufile.io/dpe9u

Raw Data:

Calculated Data:

Result:

In the calculated data the (local, "HVIS" means "IF")formula is:
=HVIS('80 Rådata'!H951="";"";'80 Rådata'!H951)

I checked formatting and other settings, and everything seems the same, i even formatcopied from the rows where "it worked".

答:
The data in column H sheet "80 Rådata" contains a few time values, but mainly text values that look like time values. Similar in column I, and J and K are all text values that look like times.

You can see that when you select the values and change the cell format to "General". Those that still look like times are text.

To fix that, select one of the columns, then click Data > Text to columns > Next > Next. In this step 3 of the wizard, specify that the data is a date (yes, a date). Then click Finish. Now all values are real time values, which you can verify by formatting as General again (then format back to time).

Repeat that with each column in turn.

From what I can see, the text values all have two zeros in the hour position. 00:01:30. If they had only one zero like this 0:01:30 then Excel would recognize them as time. If you don't want to repeat the data cleanup you may want to change your original data source to produce the correct format.

Title: Time format not persisting


问:
create n item long playlist-like list from multiple other lists
I'm trying to create a list with values out of three other lists (high, medium and low). The new list should evaluate from the probability_array from which list it should pick a random value. The new list should be playlist-like: before a randomly chosen value will be picked twice (from high, medium or low), all other values of the specific list (high, medium or low) must be in the newly generated list.

Any ideas, how I can achieve this. My code so far:

```<code>import numpy as np

array_length = 30

high = [(1, 2), 3, 4, 5, 6, (7, 8, 9)]
medium = [10, 11, (12, 13), 14]
low = [100, 101, 102, (103, 104)]

probability_array = np.random.choice(
    ['High', 'Medium', 'Low',],
    array_length,
    p=[4/7, 2/7, 1/7]
)
# i. e.
"""
['Low' 'High' 'High' 'High' 'High' 'High' 'Medium' 'Medium' 'High' 'Medium'
 'High' 'High' 'Medium' 'Medium' 'High' 'High' 'Medium' 'Medium' 'High'
 'High' 'High' 'High' 'High' 'Medium' 'Medium' 'High' 'High' 'High' 'Low'
 'High']
"""

# new list should look like:
"""
[102, (1, 2), 4, (7, 8, 9), 3, 6, 14, ...]
"""
</code>```

Thanks

答:
I make no claims to the efficiency of this approach (it illustrates one potential method rather than final code) but it will work by ensuring that each list (high, medium, low) is consumed entirely before it gets repeated for a second time etc. It will work for a final sequence of any length but it can easily result in the same "track" appearing back-to-back. It was not clarified in comments whether this was an issue.

```<code>import numpy as np

array_length = 30

high = [(1, 2), 3, 4, 5, 6, (7, 8, 9)]
medium = [10, 11, (12, 13), 14]
low = [100, 101, 102, (103, 104)]

# Initialise exntended lists
new_high = []
new_medium = []
new_low = []

# Create extended lists as repeating units

for x in range(3):
    np.random.shuffle(high)
    np.random.shuffle(medium)
    np.random.shuffle(low)
    new_high.extend(high)
    new_medium.extend(medium)
    new_low.extend(low)

# Probability distribution for consuming the extended lists
probability_array = np.random.choice(
    ['High', 'Medium', 'Low',],
    array_length,
    p=[4.0/7, 2.0/7, 1.0/7]
)

# Our final sequence
playlist = []

# Keep track of how far we got through each of the extended lists
high_counter, medium_counter, low_counter = 0, 0, 0

for pick in probability_array:
    if pick == 'High':
        playlist.append(new_high[high_counter])
        high_counter += 1
    elif pick == 'Medium':
        playlist.append(new_medium[medium_counter])
        medium_counter += 1
    else:
        playlist.append(new_low[low_counter])
        low_counter += 1

print(playlist)
</code>```

Body:
I'm trying to create a list with values out of three other lists (high, medium and low). The new list should evaluate from the probability_array from which list it should pick a random value. The new list should be playlist-like: before a randomly chosen value will be picked twice (from high, medium or low), all other values of the specific list (high, medium or low) must be in the newly generated list.

Any ideas, how I can achieve this. My code so far:

import numpy as np

array_length = 30

high = [(1, 2), 3, 4, 5, 6, (7, 8, 9)]
medium = [10, 11, (12, 13), 14]
low = [100, 101, 102, (103, 104)]

probability_array = np.random.choice(
    ['High', 'Medium', 'Low',],
    array_length,
    p=[4/7, 2/7, 1/7]
)
# i. e.
"""
['Low' 'High' 'High' 'High' 'High' 'High' 'Medium' 'Medium' 'High' 'Medium'
 'High' 'High' 'Medium' 'Medium' 'High' 'High' 'Medium' 'Medium' 'High'
 'High' 'High' 'High' 'High' 'Medium' 'Medium' 'High' 'High' 'High' 'Low'
 'High']
"""

# new list should look like:
"""
[102, (1, 2), 4, (7, 8, 9), 3, 6, 14, ...]
"""

Thanks

Body:
I make no claims to the efficiency of this approach (it illustrates one potential method rather than final code) but it will work by ensuring that each list (high, medium, low) is consumed entirely before it gets repeated for a second time etc. It will work for a final sequence of any length but it can easily result in the same "track" appearing back-to-back. It was not clarified in comments whether this was an issue.

import numpy as np

array_length = 30

high = [(1, 2), 3, 4, 5, 6, (7, 8, 9)]
medium = [10, 11, (12, 13), 14]
low = [100, 101, 102, (103, 104)]

# Initialise exntended lists
new_high = []
new_medium = []
new_low = []

# Create extended lists as repeating units

for x in range(3):
    np.random.shuffle(high)
    np.random.shuffle(medium)
    np.random.shuffle(low)
    new_high.extend(high)
    new_medium.extend(medium)
    new_low.extend(low)

# Probability distribution for consuming the extended lists
probability_array = np.random.choice(
    ['High', 'Medium', 'Low',],
    array_length,
    p=[4.0/7, 2.0/7, 1.0/7]
)

# Our final sequence
playlist = []

# Keep track of how far we got through each of the extended lists
high_counter, medium_counter, low_counter = 0, 0, 0

for pick in probability_array:
    if pick == 'High':
        playlist.append(new_high[high_counter])
        high_counter += 1
    elif pick == 'Medium':
        playlist.append(new_medium[medium_counter])
        medium_counter += 1
    else:
        playlist.append(new_low[low_counter])
        low_counter += 1

print(playlist)


问:
Why does this happen IEnumerable versus List
I have the following BL method

```<code>public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

```<code>public void Save()
{
   group.SomeProp = true;
}
</code>```

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

```<code>public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

答:
Okay, in the first implementation what is happening is that you are defining an iterator groupWithFalse that iterates over the elements of group that have SomeProp set to false. You've iterated over groupWithFalse and set SomeProp to true for all of those elements and now when you iterate again (the call to Any produces a second iteration), every element has SomeProp set to true since you just set it to be so and so of course Any returns false (the iteration produces the empty collection now).

To elaborate a little bit, basically when you say

```<code>IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                        where gr.SomeProp== false
                                        select gr);
</code>```

you are defining an object (groupWithFalse) that captures the logic "give me a sequence of the elements in group that have SomeProp set to false." Explicitly, this object is not actually a collection or sequence of those elements for which SomeProp is set to false. The first time that you iterate over this object (foreach), this rule will produce elements for which SomeProp is false (if there are any in group). But when you iterate a second time (Any), this rule will not produce any elements because you've modified the collection group from which this rule draws its elements from.

In the second iteration you are checking if the List<SomeClass> named groupWithFalse is the empty collection which it is not because you've added elements to it in the foreach loop that immediately precedes it.

Here's how I would write your code:

```<code>public static void SomeMethod (List<SomeClass> group) {
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    if(groupWithFalse.Any()) {
        foreach (SomeClass grFalse in groupWithFalse) {
            grFalse.Save();
        }

        // do some stuff
    }
}
</code>```

Now the code reads like "Get the elements of group for which SomeProp is false. If there are Any, Save them and then do some stuff."

Body:
I have the following BL method

public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

public void Save()
{
   group.SomeProp = true;
}

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

Body:
Okay, in the first implementation what is happening is that you are defining an iterator groupWithFalse that iterates over the elements of group that have SomeProp set to false. You've iterated over groupWithFalse and set SomeProp to true for all of those elements and now when you iterate again (the call to Any produces a second iteration), every element has SomeProp set to true since you just set it to be so and so of course Any returns false (the iteration produces the empty collection now).

To elaborate a little bit, basically when you say

IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                        where gr.SomeProp== false
                                        select gr);

you are defining an object (groupWithFalse) that captures the logic "give me a sequence of the elements in group that have SomeProp set to false." Explicitly, this object is not actually a collection or sequence of those elements for which SomeProp is set to false. The first time that you iterate over this object (foreach), this rule will produce elements for which SomeProp is false (if there are any in group). But when you iterate a second time (Any), this rule will not produce any elements because you've modified the collection group from which this rule draws its elements from.

In the second iteration you are checking if the List<SomeClass> named groupWithFalse is the empty collection which it is not because you've added elements to it in the foreach loop that immediately precedes it.

Here's how I would write your code:

public static void SomeMethod (List<SomeClass> group) {
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    if(groupWithFalse.Any()) {
        foreach (SomeClass grFalse in groupWithFalse) {
            grFalse.Save();
        }

        // do some stuff
    }
}

Now the code reads like "Get the elements of group for which SomeProp is false. If there are Any, Save them and then do some stuff."


问:
Fitting multimodal distrubtions
Let's assume we're having a linear combination of two normal distributions. I think one would call the result a multimodal distribution.

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

ls = np.linspace(0, 60, 1000)

distribution = norm.pdf(ls, 0, 5) + norm.pdf(ls, 20, 10)
distribution = (distribution * 1000).astype(int)
distribution = distribution/distribution.sum()

plt.plot(ls, distribution)
</code>```

As you can see, we are having a linear combination of two normal distributions having parameters (mu1 = 0, s1 = 5) and (mu2 = 20, s2 = 10). But of course, we usually do not know these parameters beforehand.

I would like to know how I can estimate or fit those parameters (mus and sigmas). I am confident there are methods that would allow to do this but I couldn't find any yet.

答: The problem that you describe is a special case of Gaussian Mixture model. In order to be able to estimate these parameters, you need to have some samples. If you don't have samples but you are given the curve, you could produce some samples based on the curve. Then you can use Expectation–maximization algorithm to estimate the parameters. Scikit-learn has a method that enables you to do that: sklearn.mixture.GaussianMixture. You just need to provide your samples, the number of components (n_components) which is 2 in your case, and a covariance type, which would be full in your case, as you have no prior assumptions on the covariance matrix.

Title: Fitting multimodal distrubtions

Body:
Let's assume we're having a linear combination of two normal distributions. I think one would call the result a multimodal distribution.

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

ls = np.linspace(0, 60, 1000)

distribution = norm.pdf(ls, 0, 5) + norm.pdf(ls, 20, 10)
distribution = (distribution * 1000).astype(int)
distribution = distribution/distribution.sum()

plt.plot(ls, distribution)

As you can see, we are having a linear combination of two normal distributions having parameters (mu1 = 0, s1 = 5) and (mu2 = 20, s2 = 10). But of course, we usually do not know these parameters beforehand.

I would like to know how I can estimate or fit those parameters (mus and sigmas). I am confident there are methods that would allow to do this but I couldn't find any yet.


问:
Vue & Firebase class binding
New to both Vue & Firebase here.  I'm prototyping an app that has a matrix of buttons that I'd like for all users across devices to be able to see which buttons are "active" by applying a css class to the button when the database has changed.  I'm using VueFire to bind the Firebase reference with Vue.

At first I tried something like this but it didn't work and I feel like it's probably not the right way to do it anyway.

HTML

```<code><button v-bind:class='{ "active": buttons['button1'] }'>
<button v-bind:class='{ "active": buttons['button2'] }'>
<button v-bind:class='{ "active": buttons['button3'] }'>
<button v-bind:class='{ "active": buttons['button4'] }'>
</code>```

Then, I thought I'd be able to use a method to determine if the button is active based on its name but it is not working either.

HTML

```<code><button v-bind:class='{ "active": isBtnActive("button1") }'>
<button v-bind:class='{ "active": isBtnActive("button2") }'>
<button v-bind:class='{ "active": isBtnActive("button3") }'>
<button v-bind:class='{ "active": isBtnActive("button4") }'>
</code>```

Javascript

```<code>var buttonsRef = firebase.database().ref('buttons');

var app = new Vue({
    el: '#app',
    data: {
    },
    firebase: {
        buttons: buttonsRef
    },
    methods: {
        isBtnActive: function(name) {
            return buttonsRef.child(name);
        }
    }
});
</code>```

Firebase data as JSON

```<code>{
    "buttons": {
        "button1": false,
        "button2": false,
        "button3": false,
        "button4": false
    }
}
</code>```

What am I missing?  I seems like this should be straight forward functionality.

答:
Based on that database structure, this.buttons will look something like this:

```<code>[ { ".value": true, ".key": "button1" }, { ".value": false, ".key": "button2" }, { ".value": false, ".key": "button3" }, { ".value": true, ".key": "button4" } ]
</code>```

That being the case, your isBtnActive method should look like this:

```<code>isBtnActive(btn){
  const button = this.buttons.find(b => b[".key"] === btn)
  if (button) return {active: button[".value"]}
  else return {active: false}
}
</code>```

Alternatively you could retrieve buttons as an object.

```<code>firebase: {
  buttons: {
    source: buttonsRef,
    asObject: true,
  }
},
</code>```

And change your method to

```<code>isBtnActive(btn){
  return { active: this.buttons[btn]}
}
</code>```

Or omit the method altogether.

```<code><button :class="{active: buttons['button3']}">Button 3</button>
</code>```

Title: Vue & Firebase class binding

Body:
New to both Vue & Firebase here.  I'm prototyping an app that has a matrix of buttons that I'd like for all users across devices to be able to see which buttons are "active" by applying a css class to the button when the database has changed.  I'm using VueFire to bind the Firebase reference with Vue.

At first I tried something like this but it didn't work and I feel like it's probably not the right way to do it anyway.

HTML

<button v-bind:class='{ "active": buttons['button1'] }'>
<button v-bind:class='{ "active": buttons['button2'] }'>
<button v-bind:class='{ "active": buttons['button3'] }'>
<button v-bind:class='{ "active": buttons['button4'] }'>

Then, I thought I'd be able to use a method to determine if the button is active based on its name but it is not working either.

HTML

<button v-bind:class='{ "active": isBtnActive("button1") }'>
<button v-bind:class='{ "active": isBtnActive("button2") }'>
<button v-bind:class='{ "active": isBtnActive("button3") }'>
<button v-bind:class='{ "active": isBtnActive("button4") }'>

Javascript

var buttonsRef = firebase.database().ref('buttons');

var app = new Vue({
    el: '#app',
    data: {
    },
    firebase: {
        buttons: buttonsRef
    },
    methods: {
        isBtnActive: function(name) {
            return buttonsRef.child(name);
        }
    }
});

Firebase data as JSON

{
    "buttons": {
        "button1": false,
        "button2": false,
        "button3": false,
        "button4": false
    }
}

What am I missing?  I seems like this should be straight forward functionality.

Body:
Based on that database structure, this.buttons will look something like this:

[ { ".value": true, ".key": "button1" }, { ".value": false, ".key": "button2" }, { ".value": false, ".key": "button3" }, { ".value": true, ".key": "button4" } ]

That being the case, your isBtnActive method should look like this:

isBtnActive(btn){
  const button = this.buttons.find(b => b[".key"] === btn)
  if (button) return {active: button[".value"]}
  else return {active: false}
}

Alternatively you could retrieve buttons as an object.

firebase: {
  buttons: {
    source: buttonsRef,
    asObject: true,
  }
},

And change your method to

isBtnActive(btn){
  return { active: this.buttons[btn]}
}

Or omit the method altogether.

<button :class="{active: buttons['button3']}">Button 3</button>


问:
Visual Studio Team Services: Task Colour Blue?
Why is the colour of tasks inside Visual Studio Team Services suddenly the same blue as the Backlog items? Before is was yellow and therefore easy to distinguish.

It is just everywhere where it was yellow before, now blue:

This affects not only this window but it is also in the "tree".

The process shows it still yellow (I use the scrum template with small customisation):

It should be yellow according to the process:

答: There was an issue with VSTS that was resolved last week. See https://developercommunity.visualstudio.com/content/problem/73306/cards-colour-is-only-blue.html</p>


问:
httpd local virtualhost example
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

```<code># cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
... ( lots of stuff different from the one i echoed) ...
</code>```

If I do the same thing in local firefox - localhost works as expected, example1.com works as expected, but sub.example2.com redirects me to example2.com.

Can you please help me to figure out how to configure a local sub-domain? What is missing? Based on https://httpd.apache.org/docs/2.4/vhosts/examples.html I believe what I did is correct.

-- Edit / Update ---

If I follow the advice below from Newbie and change only the rewrite rule, without making any other changes from the setup above:

```<code>    <VirtualHost 127.0.0.1:80>
        DocumentRoot "/var/www/example2/sub"
        ServerName sub.example2.com
        ServerPath "/sub/"
#        RewriteEngine On
#        RewriteRule "^(/sub/.*)" "/var/www/example2$1"

    </VirtualHost>
</code>```

I get :

```<code># curl sub.example2.com
curl: (6) Could not resolve host: sub.example2.com
</code>```

If I

```<code># cat /etc/hosts | grep sub
127.0.0.1 example2.com sub.example2.com
</code>```

It works as expected

```<code>#curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
Hello from /var/www/example2/sub/index.html
</code>```

Still this seems to be strange setup. I don't want to create /etc/hosts record for each sub-domain... Shouldn't it be possible to handle this situation only via the httpd VirtualHost setting, without changing the DNS settings locally or even worse - adding C records in the DNS of a domain(if not localhost)?  Any hint what I'm doing wrong? How can I get sub.example1.com to work without modifying the dns settings?

Regards,
Pavel

答:
Remove the rewrite rule, it is used for redirecting so you have a loop.

```<code><VirtualHost 127.0.0.1:80> DocumentRoot "/var/www/example2/sub" ServerName sub.example2.com ServerPath "/sub/"
</code>```

Title: httpd local virtualhost example

Body:
-- Original post ---

I'd like to setup a dev env to play with some apache features. I'm running httpd on fedora.

I added to hosts local redirects

# cat /etc/hosts
127.0.0.1 example1.com
127.0.0.1 example2.com

# cmkdir /var/www/example1;      echo "Hello from /var/www/example1/index.html" > /var/www/example1/index.html
# cmkdir /var/www/example2;      echo "Hello from /var/www/example2/index.html" > /var/www/example2/index.html
# cmkdir /var/www/example2/sub ; echo "Hello from /var/www/example2/sub/index.html" > /var/www/example2/sub/index.html

# cvi /etc/httpd/conf/httpd.conf
<VirtualHost _default_:80>
    DocumentRoot "/var//www/html"
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example1"
    ServerName example1.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com

</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/example2/sub"
    ServerName sub.example2.com
    ServerPath "/sub/"
    RewriteEngine On
    RewriteRule "^(/sub/.*)" "/var/www/example2$1"

</VirtualHost>

# capachectl -t ; apachectl restart

# curl localhost
Hello from /var/www/html/index.html
# curl example1.com
Hello from /var/www/example1/index.html
# curl example2.com
Hello from /var/www/example2/index.html
# curl sub.example2.com
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">

Body:
Remove the rewrite rule, it is used for redirecting so you have a loop.

<VirtualHost 127.0.0.1:80> DocumentRoot "/var/www/example2/sub" ServerName sub.example2.com ServerPath "/sub/"


问:
Performance Comparison of Shell Scripts vs high level interpreted langs (C#/Java/etc.)
First - This is not meant to be a 'which is better, ignorant nonionic war thread'... But rather, I generally need help in making an architecture decision / argument to put forward to my boss.

Skipping the details - I simply just would love to know and find the results of anyone who has done some performance comparisons of Shell vs [Insert General Purpose Programming Language (interpreted) here), such as C# or Java...

Surprisingly, I have spent some time on Google on searching here to not find any of this data. Has anyone ever done these comparisons, in different use-cases; hitting a database like in a XYX # of loops doing different types of SQL (Oracle pref, but MSSQL would do) queries such as any of the CRUD ops - and also not hitting database and just regular 50k loop type comparison doing different types of calculations, and things of that nature?

In particular - for right now, I need to a comparison of hitting an Oracle DB from a shell script vs, lets say C# (again, any GPPL thats interpreted would be fine, even the higher level ones like Python). But I also need to know about standard programming calculations / instructions/etc...

Before you ask 'why not just write a quick test yourself? The answer is: I've been a Windows developer my whole life/career and have very limited knowledge of Shell scripting - not to mention *nix as a whole.... So asking the question on here from the more experienced guys would be grealty beneficial, not to mention time saving as we are in near perputual deadline crunch as it is ;).

答:
As mentioned above, you won't be able to do SQL queries from shell. Languages which runs on a VM will take a little time upfront because of the VM factor but otherwise the difference should be negligible.

If the question really is to decrease it from 40 to 5 minutes that I will try to find out which piece is taking the majority of the time. If the query is running for the longest time then switching language won't help you much.

Again (without much detail in the question) I would start with looking into different components of the system to see which one is the bottleneck.


问:
Why must accessor functions be const? Where is the vulnerability?
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

```<code>#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}
</code>```

答:
const is not about vulneratilities! Thecnically it doesn't enforce security, safety or anything. Nothing stops you from applying const-cast to remove it or using keyword mutable to change something.

const helps to make your code cleaner. See Const-Correctness article with good explanation of the concept.

When you look at something with const you would reasonably expect it not change the state. The declaration int Class:foo() const; tells me foo() won't change the object's state and it is ok to call it from anywhere.

const is infectious. The more you use it the more you have to use it. bool Class::bar(); would have to be const if it needs to call foo().

Same applies in reverse direction. If you are passing const & to a function: void zoo(const Class &cls); then you know zoo() won't be able to modify cls's state.

Body:
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}