问:
socket implement in the thread
i have to read some data from database and send it from a tcp socket
so i fetch data from database

```<code>    #main
    while True:
        cursor.execute("UPDATE `raw` SET `zombie`='"+zombieId+"' WHERE result='pending' AND protocol='tcp' AND zombie='0' LIMIT 1;")
#       time.sleep(0.2)
        cursor.execute("select * from raw WHERE `result`='pending' AND `protocol`='tcp' and `zombie`='"+zombieId+"' limit 1;")

            if cursor.rowcount>0 :
                    waitedSig = cursor.fetchone()
                    time.sleep(0.2)
                    t = threading.Thread(target=sendData , args=((waitedSig),))
                    t.start()
                    time.sleep(0.6)
            else:
                    time.sleep(1)
</code>```

on the thread i will send data to target

```<code>    def sendData(sig):
        timedata = datetime.datetime.fromtimestamp(int(sig[16]))
        devimei = sig[23]
        devdate = timedata.strftime("%d%m%y")
        devtime = timedata.strftime("%H%M%S")
        lat= format(sig[2])
        lon= format(sig[3])
        satcount = format(sig[5])
        speed = format(sig[4])
        batery = format(sig[7])
        if sig[9]>1000:
                band='00'
        elif sig[9]>850:
                band='02'
        else:
                band='01'
        hdop  = format(sig[10])
        gsmQ =  format(sig[6])
        lac =  format(sig[12])
        cid =  format(sig[13])
str='$MGV002,'+devimei+',12345,S,'+devdate+','+devtime+',A,'+lat+',N,'+lon+',E,0,'+satcount+',00,'+hdop+','+speed+',0,,,432,11,'+lac+','
            try:
                    clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    result = clientsocket.connect(('ip',port))
                    clientsocket.send(str)
                    data = clientsocket.recv(1024)
                    print(str(datetime.datetime.now())+' -> send completed :'+format(sig[0]))
                    clientsocket.close()
            except:
                    print(str(datetime.datetime.now())+' -> connection to tcp server failed!!')
</code>```

this will work  really good but there are two boring problem:

1) if i remove 0.2 and 0.6 sleep delay the script crash due to duplicate socket usage,it seems system try to open an other socket until the previous don't finished its job yet!

2) if some thing goes wrong in the sendData function,the whole script stop working until i manually restart the script

so

1) can i create a thread queue to run one after other and don't affect each other?!

2) how can i handle errors in the thread function to close just that specific thread and script continue its work with next database record?!

答:
This looks like a good application of a thread pool. In your implementation you create one thread and socket per item in your database table, and that could tax the system extremely. Here I've created 20 workers as an example. There are diminishing returns on the number of workers as you start to stress the system.</p>

```<code>import multiprocessing.pool

def sender():
    pool = multiprocessing.pool.ThreadPool(20) # pick your size...
    cursor.execute("select * from database")
    pool.map(sendData, cursor, chunksize=1)

def sendData(sig):
        try:
                clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                result = clientsocket.connect(('ip',port))
                clientsocket.sendall(sig)
                data = clientsocket.recv(1024)
                print(str(datetime.datetime.now())+' -> send completed :'+format(sig[0]))
                clientsocket.shutdown(socket.SOCK_RDWR)
                clientsocket.close()
        except:
                print(str(datetime.datetime.now())+' -> connection to tcp server fa
</code>```

Title: socket implement in the thread

Body:
i have to read some data from database and send it from a tcp socket
so i fetch data from database

    #main
    while True:
        cursor.execute("UPDATE `raw` SET `zombie`='"+zombieId+"' WHERE result='pending' AND protocol='tcp' AND zombie='0' LIMIT 1;")
#       time.sleep(0.2)
        cursor.execute("select * from raw WHERE `result`='pending' AND `protocol`='tcp' and `zombie`='"+zombieId+"' limit 1;")

            if cursor.rowcount>0 :
                    waitedSig = cursor.fetchone()
                    time.sleep(0.2)
                    t = threading.Thread(target=sendData , args=((waitedSig),))
                    t.start()
                    time.sleep(0.6)
            else:
                    time.sleep(1)

on the thread i will send data to target

    def sendData(sig):
        timedata = datetime.datetime.fromtimestamp(int(sig[16]))
        devimei = sig[23]
        devdate = timedata.strftime("%d%m%y")
        devtime = timedata.strftime("%H%M%S")
        lat= format(sig[2])
        lon= format(sig[3])
        satcount = format(sig[5])
        speed = format(sig[4])
        batery = format(sig[7])
        if sig[9]>1000:
                band='00'
        elif sig[9]>850:
                band='02'
        else:
                band='01'
        hdop  = format(sig[10])
        gsmQ =  format(sig[6])
        lac =  format(sig[12])
        cid =  format(sig[13])
str='$MGV002,'+devimei+',12345,S,'+devdate+','+devtime+',A,'+lat+',N,'+lon+',E,0,'+satcount+',00,'+hdop+','+speed+',0,,,432,11,'+lac+','
            try:
                    clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    result = clientsocket.connect(('ip',port))
                    clientsocket.send(str)
                    data = clientsocket.recv(1024)
                    print(str(datetime.datetime.now())+' -> send completed :'+format(sig[0]))
                    clientsocket.close()
            except:
                    print(str(datetime.datetime.now())+' -> connection to tcp server failed!!')

this will work  really good but there are two boring problem:

1) if i remove 0.2 and 0.6 sleep delay the script crash due to duplicate socket usage,it seems system try to open an other socket until the previous don't finished its job yet!

2) if some thing goes wrong in the sendData function,the whole script stop working until i manually restart the script

so

1) can i create a thread queue to run one after other and don't affect each other?!

2) how can i handle errors in the thread function to close just that specific thread and script continue its work with next database record?!

Body:
This looks like a good application of a thread pool. In your implementation you create one thread and socket per item in your database table, and that could tax the system extremely. Here I've created 20 workers as an example. There are diminishing returns on the number of workers as you start to stress the system.

import multiprocessing.pool

def sender():
    pool = multiprocessing.pool.ThreadPool(20) # pick your size...
    cursor.execute("select * from database")
    pool.map(sendData, cursor, chunksize=1)

def sendData(sig):
        try:
                clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                result = clientsocket.connect(('ip',port))
                clientsocket.sendall(sig)
                data = clientsocket.recv(1024)
                print(str(datetime.datetime.now())+' -> send completed :'+format(sig[0]))
                clientsocket.shutdown(socket.SOCK_RDWR)
                clientsocket.close()
        except:
                print(str(datetime.datetime.now())+' -> connection to tcp server fa


来源: stackexchange

问:
How to set margin programmatically in android for a textview inside linearlayout?
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.</p>

```<code>import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}
</code>```

答:
Your problem is in using

```<code>LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
</code>```

Instead use:

```<code>LinearLayout.LayoutParams textViewLayoutParams =  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add margins for each textbox added to a linear layout, which is inside a scrollview. However big margins i set, it doesn't reflect on the UI. Why? I have referred quite a few things on this stack overflow itself.

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ScrollView mainScrollView;
    LinearLayout scrollViewContainer;
    ArrayList<String> stringArr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainScrollView = (ScrollView) findViewById(R.id.mainScrollView);
        scrollViewContainer = (LinearLayout)findViewById(R.id.scrollViewContainer);

        stringArr = new ArrayList<String>();
        String str1 = "In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. " +
                "The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation).";
        String str2 = "Initializes a newly created String object so that it represents the same sequence of characters as the argument; " +
                "in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed," +
                " use of this constructor is unnecessary since Strings are immutable.";

        for(int ii = 0; ii < 10; ii++){
            if(ii%2 ==  0) {
                stringArr.add(str1);
            }else{
                stringArr.add(str2);
            }
        }
        Resources r = getResources();
        float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
        float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, r.getDisplayMetrics());
        float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());

        LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        for(int ii = 0; ii < stringArr.size(); ii++){
            TextView textView = new TextView(this);
            textView.setTextSize(12f);
            textView.setText(stringArr.get(ii));
            textView.setLayoutParams(textViewLayoutParams);
            textViewLayoutParams.setMargins(10,30,10,30);
            textView.requestLayout();
            scrollViewContainer.addView(textView);
        }

    }
}

Body:
Your problem is in using

LinearLayoutCompat.LayoutParams textViewLayoutParams =  new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

Instead use:

LinearLayout.LayoutParams textViewLayoutParams =  new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);


问:
How to add files from webapp directory to jar using Maven Assembly plugin?
I have project of following structure.

I want to create a jar which will have 'config' and 'static' directories. Also that jar should have compiled classes as well.

So far, I have tried following but without success.

```<code><assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
  <id>src</id>
  <formats>
    <format>jar</format>
  </formats>
  <fileSets>
    <fileSet>
        <directory>${basedir}</directory>
        <outputDirectory/>
        <includes>
            <include>src/main/webapp/config/</include>
        </includes>
    </fileSet>
</fileSets>
</assembly>
</code>```

Any help is appreciated.

答:
I am not sure that it is possible to use assembly plugin the way you want, but you can define the webapp directory as a resource of the module like this:

```<code><build>
        <resources>
            <resource>
                <directory>src/main/</directory>
                <includes>
                    <include>webapp/**/*</include>
                </includes>
            </resource>
        </resources>
</build>
</code>```

in this case the jar that will be created, would include the compiled code and the webapp directory. (if needed you can add more  to include other resources directories.

for more information, see https://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html

Body:
I have project of following structure.

I want to create a jar which will have 'config' and 'static' directories. Also that jar should have compiled classes as well.

So far, I have tried following but without success.

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
  <id>src</id>
  <formats>
    <format>jar</format>
  </formats>
  <fileSets>
    <fileSet>
        <directory>${basedir}</directory>
        <outputDirectory/>
        <includes>
            <include>src/main/webapp/config/</include>
        </includes>
    </fileSet>
</fileSets>
</assembly>

Any help is appreciated.

Body:
I am not sure that it is possible to use assembly plugin the way you want, but you can define the webapp directory as a resource of the module like this:

<build>
        <resources>
            <resource>
                <directory>src/main/</directory>
                <includes>
                    <include>webapp/**/*</include>
                </includes>
            </resource>
        </resources>
</build>

in this case the jar that will be created, would include the compiled code and the webapp directory. (if needed you can add more  to include other resources directories.

for more information, see https://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html


问:
How to get a list of all elements that resides at the clicked point?
On user click I would like to get a list of all elements that resides at the clicked point.

For example, if user clicks on Hello here:

```<code><div><span>Hello<span></div>
</code>```

I would like to get the following list:

 element

  element

 element

 element

What would be the easiest method to get these elements ?

答:
Just javascript implementation:

```<code>window.addEventListener('click', function(e){
    console.log(document.elementFromPoint(e.pageX, e.pageY))
}, false)
</code>```

Worked for me in firefox and chrome as of 3-29-2017

ContentLicense: CC BY-SA 4.0

Body:
On user click I would like to get a list of all elements that resides at the clicked point.

For example, if user clicks on Hello here:

Hello

I would like to get the following list:

 element

  element

 element

 element

What would be the easiest method to get these elements ?

Body:
Just javascript implementation:

window.addEventListener('click', function(e){
    console.log(document.elementFromPoint(e.pageX, e.pageY))
}, false)

Worked for me in firefox and chrome as of 3-29-2017


问:
Swift Clear AVSpeechSynthesizer Before Speaking
I am using the code below to speak a string in my app.

```<code>var mySynthesizer = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "Hello World!")
myUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
myUtterance.pitchMultiplier = 1.15
myUtterance.rate = 0.5
mySynthesizer.speak(utterance)
</code>```

If the string is then changed and asked to read again, it repeats the previous string at the end of the new one.

Is it possible to clear AVSpeechSynthesizer before beginning?

Thank you

答:
I got this to work in a playground.  Nothing is repeated.</p>

```<code>//: Playground - noun: a place where people can play

import UIKit
import AVFoundation
import PlaygroundSupport

// this is needed otherwise the playground program exits before the speech is synthesized.
PlaygroundPage.current.needsIndefiniteExecution = true

var mySynthesizer = AVSpeechSynthesizer()
var helloUtterance = AVSpeechUtterance(string: "Hello World!")
helloUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
helloUtterance.pitchMultiplier = 1.25
helloUtterance.rate = 0.5
mySynthesizer.speak(helloUtterance)

let responseUtterance = AVSpeechUtterance(string: "Hey human. It's me, the world")
responseUtterance.pitchMultiplier = 0.75
responseUtterance.rate = 0.45
mySynthesizer.speak(responseUtterance)
</code>```

Body:
I am using the code below to speak a string in my app.

var mySynthesizer = AVSpeechSynthesizer()
var myUtterance = AVSpeechUtterance(string: "Hello World!")
myUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
myUtterance.pitchMultiplier = 1.15
myUtterance.rate = 0.5
mySynthesizer.speak(utterance)

If the string is then changed and asked to read again, it repeats the previous string at the end of the new one.

Is it possible to clear AVSpeechSynthesizer before beginning?

Thank you

Body:
I got this to work in a playground.  Nothing is repeated.

//: Playground - noun: a place where people can play

import UIKit
import AVFoundation
import PlaygroundSupport

// this is needed otherwise the playground program exits before the speech is synthesized.
PlaygroundPage.current.needsIndefiniteExecution = true

var mySynthesizer = AVSpeechSynthesizer()
var helloUtterance = AVSpeechUtterance(string: "Hello World!")
helloUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
helloUtterance.pitchMultiplier = 1.25
helloUtterance.rate = 0.5
mySynthesizer.speak(helloUtterance)

let responseUtterance = AVSpeechUtterance(string: "Hey human. It's me, the world")
responseUtterance.pitchMultiplier = 0.75
responseUtterance.rate = 0.45
mySynthesizer.speak(responseUtterance)


问:
How do I find starting values to fit nonlinear data?
I am attempting to calculate the two parameters that best minimize the least squares of a nonlinear model (below). I have searched for a good method for this on stackoverflow and elsewhere, but to no avail.

The data

```<code>x<-c(0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0);
y<-c(0,0.501766379,0.508975489, 0.531691175, 0.503410116, 0.539983481, 0.551075694, 0.695050048, 1);
data1 <- data.frame(x,y)
</code>```

The Model

```<code>y~(a*x^2+x*(1-x))/(a*x^2+2*x*(1-x)+b*(1-x)^2)
</code>```

My meager efforts

```<code>min.RSS <- function(data, par) {
with(data, sum((par[1]*x^2+x*(1-x))/(par[1]*x^2+2*x*(1-x)+par[2]*(1-x)^2)))
           }
result <- optim(par = c(0, 1), min.RSS, data = data1$y)
</code>```

答:
I figured this out using the nls function. I was concerned about attaining suitable starting values, but nls my concerns appeared to be unfounded, as any reasonable starting values work.

The solution:

```<code>m<-nls(y ~ (a*x^2+x*(1-x))/(a*x^2+2*x*(1-x)+b*(1-x)^2), start=list(a=1,b=.5))
beta <- coefficients(m)
</code>```

This yields the desired parameters (in object "beta").

Body:
I am attempting to calculate the two parameters that best minimize the least squares of a nonlinear model (below). I have searched for a good method for this on stackoverflow and elsewhere, but to no avail.

The data

x<-c(0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0);
y<-c(0,0.501766379,0.508975489, 0.531691175, 0.503410116, 0.539983481, 0.551075694, 0.695050048, 1);
data1 <- data.frame(x,y)

The Model

y~(a*x^2+x*(1-x))/(a*x^2+2*x*(1-x)+b*(1-x)^2)

My meager efforts

min.RSS <- function(data, par) {
with(data, sum((par[1]*x^2+x*(1-x))/(par[1]*x^2+2*x*(1-x)+par[2]*(1-x)^2)))
           }
result <- optim(par = c(0, 1), min.RSS, data = data1$y)

Body:
I figured this out using the nls function. I was concerned about attaining suitable starting values, but nls my concerns appeared to be unfounded, as any reasonable starting values work.

The solution:

m<-nls(y ~ (a*x^2+x*(1-x))/(a*x^2+2*x*(1-x)+b*(1-x)^2), start=list(a=1,b=.5))
beta <- coefficients(m)

This yields the desired parameters (in object "beta").


问:
File download from C# not working, I can see in the browser response from the API
I am using a C# api and I call it from the from the UI, I am able to call it and I can see when I inspect the browser response, the returned data from the api, but it didn't force it to download the response. Here is the code I am using in the C# api

```<code>var response = HttpContext.Current.Response;
response.Clear();

string fileName = CleanFileName(string.Format("{0} test - {1}.txt", name, DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss")));
response.AddHeader("content-disposition", "attachment; filename = \"" + fileName + "\"");
response.ContentType = "text/csv";
response.AddHeader("Pragma", "must-revalidate");
response.AddHeader("Cache-Control", "must-revalidate");

byte[] byteArray = Encoding.UTF8.GetBytes(mydata);
response.AppendHeader("Content-Length", byteArray.Length.ToString());
response.BinaryWrite(byteArray);

response.End();
response.Flush();
</code>```

Thanks

答:
Probably you do async call of your API from your client side. In that case you will get all data that returned by API as result of your request and they won't be downloaded automatically.

Try to do something like this from your client side (JS):

```<code>window.open(apiDownloadLink, '_blank', '');
</code>```

It would cause postback and file will be downloaded by browser.

You can find additional information in this question

Body:
I am using a C# api and I call it from the from the UI, I am able to call it and I can see when I inspect the browser response, the returned data from the api, but it didn't force it to download the response. Here is the code I am using in the C# api

var response = HttpContext.Current.Response;
response.Clear();

string fileName = CleanFileName(string.Format("{0} test - {1}.txt", name, DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss")));
response.AddHeader("content-disposition", "attachment; filename = \"" + fileName + "\"");
response.ContentType = "text/csv";
response.AddHeader("Pragma", "must-revalidate");
response.AddHeader("Cache-Control", "must-revalidate");

byte[] byteArray = Encoding.UTF8.GetBytes(mydata);
response.AppendHeader("Content-Length", byteArray.Length.ToString());
response.BinaryWrite(byteArray);

response.End();
response.Flush();

Thanks

Body:
Probably you do async call of your API from your client side. In that case you will get all data that returned by API as result of your request and they won't be downloaded automatically.

Try to do something like this from your client side (JS):

window.open(apiDownloadLink, '_blank', '');

It would cause postback and file will be downloaded by browser.

You can find additional information in this question


问:
SQL single table with two columns
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

```<code>SELECT DISTINCT(memo)
FROM checking
</code>```

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

```<code>ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c
</code>```

The desired return:

```<code>1,a
2,c
3,e
4,g
</code>```

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.

答:
If I understand you correctly you want the first (?) primary key value corresponding to each unique memo value found?  (I'm assuming this because you can't logically have both unique memos and Id values because there is necessarily multiple ID values for each duplicated memo value...)  If the assumption is correct this will work:

```<code>SELECT m.memo,
    (SELECT TOP 1 x.id
     FROM checking x
     WHERE x.memo = m.memo
     ORDER BY x.id) as ID
FROM checking m
GROUP BY m.memo
</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL single table with two columns

Body:
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

SELECT DISTINCT(memo)
FROM checking

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c

The desired return:

1,a
2,c
3,e
4,g

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.

Body:
If I understand you correctly you want the first (?) primary key value corresponding to each unique memo value found?  (I'm assuming this because you can't logically have both unique memos and Id values because there is necessarily multiple ID values for each duplicated memo value...)  If the assumption is correct this will work:

SELECT m.memo,
    (SELECT TOP 1 x.id
     FROM checking x
     WHERE x.memo = m.memo
     ORDER BY x.id) as ID
FROM checking m
GROUP BY m.memo


问:
What's the best way to load a yaml file to Map(not an environment configuration file) in spring boot web project?
In my data framework layer, I'd like to read an yaml from src/main/resources.
The file name is mapconfigure.yaml. It's associated with the business data, not just environment configuration data.

Its content's like:

```<code>person1:
  name: aaa
  addresses:
    na: jiang
    sb: su
person2:
  name: bbb
  addresses:
    to: jiang
    bit: su
</code>```

I want to store this information into a HashMap.

Does it mean to use some spring annotation like @ConfigurationProperties?
How to achieve this in details?

In addition, I can't change the file name. It means I have to use mapconfigure.yaml as the file name, not application.yml or application.properties.

The structure of my HashMap is as follows:

```<code>HashMap<String, Setting>

@Data
public class Setting{
  private String name;
  private HashMap<String, String> addresses
}
</code>```

My expected HashMap's as follows:

```<code>{person1={name=aaa, addresses={na=jiang, sb=su}}, person2={name=bbb, addresses={to=jiang, bit=su}}}
</code>```

I'm not sure if I can use YamlMapFactoryBean class to do this.

The return type of the getObject method in YamlMapFactoryBean class is Map<String, Object>, not a generic type, like Map<String, T>.

Spring boot doc just said

Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map.

But there isn't a detailed example.

UPDATE:

In github, I created a sample. It's Here.
In this sample, I want to load myconfig.yaml to theMapProperties object in SamplePropertyLoadingTest class. Spring boot version is 1.5.1, so I can't use location attribute of @ConfigurationProperties.
How to do this?

答:
try this   </p>

```<code> YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> applicationYamlPropertySource = loader.load(
                "properties", new ClassPathResource("application.yml"), null);// null indicated common properties for all profiles.
            Map source = ((MapPropertySource) applicationYamlPropertySource).getSource();
            Properties properties = new Properties();
            properties.putAll(source);
            return properties;
        } catch (IOException e) {
            LOG.error("application.yml file cannot be found.");
        }
</code>```

Body:
In my data framework layer, I'd like to read an yaml from src/main/resources.
The file name is mapconfigure.yaml. It's associated with the business data, not just environment configuration data.

Its content's like:

person1:
  name: aaa
  addresses:
    na: jiang
    sb: su
person2:
  name: bbb
  addresses:
    to: jiang
    bit: su

I want to store this information into a HashMap.

Does it mean to use some spring annotation like @ConfigurationProperties?
How to achieve this in details?

In addition, I can't change the file name. It means I have to use mapconfigure.yaml as the file name, not application.yml or application.properties.

The structure of my HashMap is as follows:

HashMap<String, Setting>

@Data
public class Setting{
  private String name;
  private HashMap<String, String> addresses
}

My expected HashMap's as follows:

{person1={name=aaa, addresses={na=jiang, sb=su}}, person2={name=bbb, addresses={to=jiang, bit=su}}}

I'm not sure if I can use YamlMapFactoryBean class to do this.

The return type of the getObject method in YamlMapFactoryBean class is Map<String, Object>, not a generic type, like Map<String, T>.

Spring boot doc just said

Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean will load YAML as Properties and the YamlMapFactoryBean will load YAML as a Map.

But there isn't a detailed example.

UPDATE:

In github, I created a sample. It's Here.
In this sample, I want to load myconfig.yaml to theMapProperties object in SamplePropertyLoadingTest class. Spring boot version is 1.5.1, so I can't use location attribute of @ConfigurationProperties.
How to do this?

Body:
try this

 YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> applicationYamlPropertySource = loader.load(
                "properties", new ClassPathResource("application.yml"), null);// null indicated common properties for all profiles.
            Map source = ((MapPropertySource) applicationYamlPropertySource).getSource();
            Properties properties = new Properties();
            properties.putAll(source);
            return properties;
        } catch (IOException e) {
            LOG.error("application.yml file cannot be found.");
        }


问:
Why seems to have padding on this p background?
I have the follow html code:

```<code><div class="row">
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">The title</p>
 </a>
</div>
<div class="col">
 <a href="id">
  <img src="file">
   <p class="titulo-noticia">Another title</p>
 </a>
</div>
</div>
</code>```

This must show a row with two images with a footer that it is the title.

The css is the following:

```<code>.col{
    display: table-cell;
}

.row{
    display: row;
}

.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}
</code>```

My problem is that the
 have a size of 1196*51, but the background color not fullfill this size. I attach an image:

The black color is not the full size of
 tag.

How can achieve to fullfill the p with the color?

答:
I'm not sure I understand ur question since you did not formulate it that clearm, the extra width and height might a margin, try:

```<code>.titulo-noticia{
 margin: 0;
}
</code>```

Instead of a screenshot try to include some more code so we can see for our selfs what the problem is:)

Hope this helped.

Body:
I have the follow html code:

The title

Another title

This must show a row with two images with a footer that it is the title.

The css is the following:

.col{
    display: table-cell;
}

.row{
    display: row;
}

.titulo-noticia{
    display: block;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    text-align: center;
    background: #000;
    background: rgba(0,0,0, .8);
    color: #fff;
    font-size: 18px;
}

My problem is that the
 have a size of 1196*51, but the background color not fullfill this size. I attach an image:

The black color is not the full size of
 tag.

How can achieve to fullfill the p with the color?

Body:
I'm not sure I understand ur question since you did not formulate it that clearm, the extra width and height might a margin, try:

.titulo-noticia{
 margin: 0;
}

Instead of a screenshot try to include some more code so we can see for our selfs what the problem is:)

Hope this helped.


问:
Limit the number of queried items from GeoFire
I have a lot of entry in the same location. I would like only to get the 10 latest added items using Geofire. I know that it can be done easily with firebase using Query.limitToLast() but I don't know how to do it with Geofire.

If it is not possible, do you have any workaround that I can apply ?

答:
There is only one solution for this :

you should begin a query with a small radius,

and each time you reach onGeoQueryReady() ("All data has been loaded"), you increase the radius by a small amount of the geoquery with .setRadius(r) until you reach the limit you want

based on this https://github.com/firebase/geofire-js/issues/59


问:
SwiftyJSON: Remove all object from an array
I'm trying to clear out all items in an array created with SwiftyJSON using removeAll() but it is not working. What am I doing wrong?

```<code>let itemsArray = ["One", "Two"]
var jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
let item = jsonObject.arrayValue
</code>```

答:
You can't modify JSON's array:

Solution

The only option for cleaning the array:

```<code>jsonObject = JSON([String]())
//jsonObject = JSON([Any]())
</code>```

Full Sample

```<code>let itemsArray = ["One", "Two", "Three"]
var tempArray = itemsArray
var jsonObject = JSON(itemsArray)

let array: [String]? = []
jsonObject.arrayObject = array
print("===========================================")
print("Original array:\n\(jsonObject)")
//jsonObject = JSON([Any]())
jsonObject = JSON([String]())
print("Empty JSON array:\n\(jsonObject)")
print("===========================================")

// Not working
print("\nNot working exaple 1:")
jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
print("JSON: jsonObject.arrayObject?.removeAll() = \n\(jsonObject)")
tempArray.removeAll()
print("!!! But [string].removeAll() = \(tempArray)")
print("===========================================")

print("\nNot working exaple 2:")
tempArray = itemsArray
for _ in 0..<jsonObject.arrayObject!.count {
    jsonObject.arrayObject!.removeLast()
    tempArray.removeLast()
}

print("JSON: for ... { jsonObject.arrayObject!.removeLast() } = \n\(jsonObject)")
print("!!! But [String]:for ...{ tempArray.removeLast() } = \(tempArray)")
</code>```

Result

Body:
I'm trying to clear out all items in an array created with SwiftyJSON using removeAll() but it is not working. What am I doing wrong?

let itemsArray = ["One", "Two"]
var jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
let item = jsonObject.arrayValue

Body:
You can't modify JSON's array:

Solution

The only option for cleaning the array:

jsonObject = JSON([String]())
//jsonObject = JSON([Any]())

Full Sample

let itemsArray = ["One", "Two", "Three"]
var tempArray = itemsArray
var jsonObject = JSON(itemsArray)

let array: [String]? = []
jsonObject.arrayObject = array
print("===========================================")
print("Original array:\n\(jsonObject)")
//jsonObject = JSON([Any]())
jsonObject = JSON([String]())
print("Empty JSON array:\n\(jsonObject)")
print("===========================================")

// Not working
print("\nNot working exaple 1:")
jsonObject = JSON(itemsArray)
jsonObject.arrayObject?.removeAll()
print("JSON: jsonObject.arrayObject?.removeAll() = \n\(jsonObject)")
tempArray.removeAll()
print("!!! But [string].removeAll() = \(tempArray)")
print("===========================================")

print("\nNot working exaple 2:")
tempArray = itemsArray
for _ in 0..<jsonObject.arrayObject!.count {
    jsonObject.arrayObject!.removeLast()
    tempArray.removeLast()
}

print("JSON: for ... { jsonObject.arrayObject!.removeLast() } = \n\(jsonObject)")
print("!!! But [String]:for ...{ tempArray.removeLast() } = \(tempArray)")

Result


问:
Using Dynamic Table name in ADO.NET Source Editor
I have an SSIS data flow task where I am trying to load data from a source table using ADO.NET Source Editor into a SQL Server table.

The problem:

The source table name is dynamic and depends on the current date.

Example: If I want to load today's data then the table name would be Sample_03292017_data and if loading tomorrow's data then it would be Sample_03302017_Data.

I did some research and found how to pass parameters to an ADO.NET Source Editor to use in where conditions but I couldn't find anything on how to use this parameter in a table name.

Does anyone know how I can achieve this? My query is really simple:

```<code>select * from Sample_[DateParameter]_Data.
</code>```

I am using Visual Studio Data Tools 2010.

答:
You should use dynamic SQL to achieve this. If you are using ADO.net as Connection Type, copy and paste the following to your SQL statement:

```<code>Declare @SQL VARCHAR(MAX)
SET @SQL = 'Select * from ' + @TABLE
EXEC(@SQL)
</code>```

In the parameter page, you need to Add new parameter which has @TABLE as the parameter name and leave the size as -1. The @Table variable should be decided by the expression from variable setting page.

Body:
I have an SSIS data flow task where I am trying to load data from a source table using ADO.NET Source Editor into a SQL Server table.

The problem:

The source table name is dynamic and depends on the current date.

Example: If I want to load today's data then the table name would be Sample_03292017_data and if loading tomorrow's data then it would be Sample_03302017_Data.

I did some research and found how to pass parameters to an ADO.NET Source Editor to use in where conditions but I couldn't find anything on how to use this parameter in a table name.

Does anyone know how I can achieve this? My query is really simple:

select * from Sample_[DateParameter]_Data.

I am using Visual Studio Data Tools 2010.

Body:
You should use dynamic SQL to achieve this. If you are using ADO.net as Connection Type, copy and paste the following to your SQL statement:

Declare @SQL VARCHAR(MAX)
SET @SQL = 'Select * from ' + @TABLE
EXEC(@SQL)

In the parameter page, you need to Add new parameter which has @TABLE as the parameter name and leave the size as -1. The @Table variable should be decided by the expression from variable setting page.


问:
Media Query Struggles
So I'm working on making my site responsive and am having issues past the 1700px breakpoint.

My Problem

Here's my html:

```<code><div class="container-1">
<div class="header">
  <h2>OneDrive/ODB</h2><br><a class="one" href="#Anchor">Report a SharePoint bug here</a>
 </div>
 <div class="table-col-1">
  <div class="border-1">
 <div class="table-head-1">
   <h1>Issues with OneDrive/ODB on the web?</h1>
  </div>
<div class="text-container">
 <p class="table-text">Post and vote on feature suggestions & improvements on UserVoice:</p>
    <br><a href="#" class="button">ODC/ODB web</a>
    </div>
</div>
</div>
</code>```

My CSS for previous breakpoint:

```<code>.table-col-1{
padding: 1.5em;
display: inline-block;
width: 20%;
}

.table-head-1{
padding: 1.5em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}

.table-text{
font-size: 15px;
line-height: 18px;
padding-bottom: 1.5em;
}

.text-container{
padding-top: 1.5em;
padding-bottom: 3em;
}

.border-1{
border: 2px solid #000000;
}
</code>```

My CSS for the breakpoint that's not working:

```<code>@media screen and (min-width: 1700px) and (max-width: 4000px){
.table-head-1{
padding: 1.3em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}
}
</code>```

If I try and add a width, let's say 100%, to that or even to .table-col-1 I get this issue.

Please help. Thanks!

答:
Assigning width to 100% doesn't seem to work in this case because your code also adds extra padding to the div which is not needed.

So,can you please try changing the style properties of "table-col-1" to padding: 1.5em 0em; and width to 100%. A working example of this is here : https://jsfiddle.net/m70y6jnd/

Do let me know in comments below if this doesn't help you.

Title: Media Query Struggles

Body:
So I'm working on making my site responsive and am having issues past the 1700px breakpoint.

My Problem

Here's my html:

OneDrive/ODB

Report a SharePoint bug here

Issues with OneDrive/ODB on the web?

Post and vote on feature suggestions & improvements on UserVoice:

ODC/ODB web

My CSS for previous breakpoint:

.table-col-1{
padding: 1.5em;
display: inline-block;
width: 20%;
}

.table-head-1{
padding: 1.5em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}

.table-text{
font-size: 15px;
line-height: 18px;
padding-bottom: 1.5em;
}

.text-container{
padding-top: 1.5em;
padding-bottom: 3em;
}

.border-1{
border: 2px solid #000000;
}

My CSS for the breakpoint that's not working:

@media screen and (min-width: 1700px) and (max-width: 4000px){
.table-head-1{
padding: 1.3em;
background-color: #515251;
display: inline-block;
border-bottom: 2px solid #000000;
}
}

If I try and add a width, let's say 100%, to that or even to .table-col-1 I get this issue.

Please help. Thanks!


问:
CSS: Why is vertical-align: baseline stop working on Firefox when using overflow: hidden?
You can reproduce this by running this test case. The results are shown in the screenshot below. The issue is that on Firefox, when adding a overflow: hidden on the "block" (with grey background in the screenshot), the block stop being aligned as I'd like it to be: instead of the baseline of the text in the block being align to the the baseline of the parent box, it is as if the bottom of the block was aligned on the baseline of the parent box. As you can see in the screenshot, this doesn't happen with Chrome.

Is this a Firefox bug?

How to get the expected result on Firefox (baseline alignment with overflow: hidden)?

Note: Using vertical-align: middle on "block" doesn't cut it, as what I really want is baseline alignment. You can see more clearly that vertical-align: middle doesn't do baseline alignment by setting padding: 1em 0 .1em 0 (more padding at the top of the box), which give you:

答:
try ```
.label {
        float: left;
        line-height: 30px;
        margin-right: 5px;
        }
```

this will get the desired result in both FF and Chrome/Safari.  Did not test in IE however.

Body:
try

.label {
        float: left;
        line-height: 30px;
        margin-right: 5px;
        }

this will get the desired result in both FF and Chrome/Safari.  Did not test in IE however.


问:
Reading a text file of values 0-1 in R: data gets corrupted when converted to numeric
I am trying to read the simplest of csv files but there seems to be a problem when trying to convert the data to numerical. This is the minimal code and output:

```<code>initialsoltext=read.csv('initialsol.txt', header = FALSE, sep = "")
initialsoltext

output:  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 [1  0  0  0  0  1  0  0  1  0]
as.numeric(initialsoltext)
output:  [1] 1 0 0 0 0 1 0 0 1 1
</code>```

The csv file is not the issue since the text is read properly - what can possibly happen during the conversion of the last 0?
I tried replacing the "[" and "]" thinking that maybe the last bracket was read as a 1 but it doesn't make a difference.
Thanks to anyone who can help,

答:
It is reading the first and last values as factors (as they are attached to the square brackets), and the as.numeric is then reproducing the factor number, which is 1, as there is only one value. Try str(initialsoltext) to check the variable types. To avoid this, add stringsAsFactors=FALSE to the read.csv arguments.

It is probably easier to read it in as you are and then remove the brackets with something like initialsoltext2 <- as.numeric(gsub("[]\\[]","",as.character(initialsoltext))) - this produces a vector of integers that you can then convert to a data.frame if you wish

Body:
I am trying to read the simplest of csv files but there seems to be a problem when trying to convert the data to numerical. This is the minimal code and output:

initialsoltext=read.csv('initialsol.txt', header = FALSE, sep = "")
initialsoltext

output:  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 [1  0  0  0  0  1  0  0  1  0]
as.numeric(initialsoltext)
output:  [1] 1 0 0 0 0 1 0 0 1 1

The csv file is not the issue since the text is read properly - what can possibly happen during the conversion of the last 0?
I tried replacing the "[" and "]" thinking that maybe the last bracket was read as a 1 but it doesn't make a difference.
Thanks to anyone who can help,


问:
Sorting all worksheets in the workbook
I have this code that actually do exactly what I want to:

goes to the specific range, copy the table in a new range and reorder the table.

Here is the code:

```<code> Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = Range("CZ269:DA294")
Set aCell = Range("DA269")

Range("CW269:CX294").Select
Selection.Copy

Range("CZ269:DA294").Select
ActiveSheet.Paste

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub
</code>```

The problem is: the code is not working in all worksheets, it is repeating n times in the first worksheet.

答:
You never tell the code to go to the next worksheet. Also, your selections don't look necessary.

```<code> Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = worksheets(I).Range("CZ269:DA294")
Set aCell = worksheets(I).Range("DA269")

worksheets(I).Range("CW269:CX294").Copy  worksheets(I).Range("CZ269:DA294")

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub
</code>```

Also  - Since you are sorting the range, I am guessing that it containsvalues, rather than formulas.  If that is the case, you can replace

worksheets(I).Range("CW269:CX294").Copy  worksheets(I).Range("CZ269:DA294")

with

worksheets(I).Range("CZ269:DA294").Value = worksheets(I).Range("CW269:CX294").Value

The advantage of this is that it is slightly faster, and doesn't use your clipboard.

Title: Sorting all worksheets in the workbook

Body:
I have this code that actually do exactly what I want to:

goes to the specific range, copy the table in a new range and reorder the table.

Here is the code:

 Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = Range("CZ269:DA294")
Set aCell = Range("DA269")

Range("CW269:CX294").Select
Selection.Copy

Range("CZ269:DA294").Select
ActiveSheet.Paste

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub

The problem is: the code is not working in all worksheets, it is repeating n times in the first worksheet.

Body:
You never tell the code to go to the next worksheet. Also, your selections don't look necessary.

 Sub copy_paste_sort()

Dim oneRange As Range
Dim aCell As Range
Dim WS_Count As Integer
Dim I As Integer

         ' Set WS_Count equal to the number of worksheets in the active
         ' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count

Set oneRange = worksheets(I).Range("CZ269:DA294")
Set aCell = worksheets(I).Range("DA269")

worksheets(I).Range("CW269:CX294").Copy  worksheets(I).Range("CZ269:DA294")

oneRange.Sort Key1:=aCell, Order1:=xlDescending, Header:=xlNo

    Next I

End Sub

Also  - Since you are sorting the range, I am guessing that it containsvalues, rather than formulas.  If that is the case, you can replace

worksheets(I).Range("CW269:CX294").Copy  worksheets(I).Range("CZ269:DA294")

with

worksheets(I).Range("CZ269:DA294").Value = worksheets(I).Range("CW269:CX294").Value

The advantage of this is that it is slightly faster, and doesn't use your clipboard.


问:
Append Element Into Element
It might sound stupid , but i didn't find the correct way to achieve this . I want to create an element(in our example a div element) and add to it the textarea value . In my example it seems that the element is created but i cant embed it into the #notesPosition . I achieve this with JQuery but i`am not sure whats the best way to do it with pure Javascript.

var notesPositionToAdd = document.getElementById('notesPosition');
var notesTextareaBtn = document.getElementById('btnAddNotes');

notesTextareaBtn.addEventListener('click', function(e) {
  e.preventDefault();
  var notesTextarea = document.getElementById('addNotesTextarea').value;
  console.log(notesTextarea);
  var newEl = document.createElement('div');

  newEl.append(notesTextarea);
  newEl.className += " col-lg-2";
  console.log(newEl);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row ">
  <div class="col-lg-4 col-md-4 col-sm-4 col-12 offset-md-8 ">
    <form id="newNoteForm">
      <div class="form-group offset-lg-6">
        <i class="fa fa-times text-md-right " aria-hidden="true"></i>
        <label for="addNotesTextarea">Add notes !</label>
        <textarea class="form-control" id="addNotesTextarea" rows="3"></textarea>
        <input class="btn btn-danger btn-sm" type="submit" value="Add" id="btnAddNotes">
      </div>
    </form>
  </div>
</div>
<div class="row" id="notesPosition">

</div></code>```

答:
If you want to addTextNode() then you can...

```<code>var div = document.createElement('div');
var txt = document.createTextNode('Whatever Text');
    div.appendChild(txt);
</code>```

alternatively

```<code>var div = document.createElement('div')
    div.innerHTML = 'Whatever Text' // Whatever text parsed, <p>Words</p> is OK
</code>```

alternatively

```<code>var div - document.createElement('div')
    div.textContent = 'Whatever' // Not parsed as HTML
</code>```

Title: Append Element Into Element

Body:
It might sound stupid , but i didn't find the correct way to achieve this . I want to create an element(in our example a div element) and add to it the textarea value . In my example it seems that the element is created but i cant embed it into the #notesPosition . I achieve this with JQuery but i`am not sure whats the best way to do it with pure Javascript.

var notesPositionToAdd = document.getElementById('notesPosition');
var notesTextareaBtn = document.getElementById('btnAddNotes');

notesTextareaBtn.addEventListener('click', function(e) {
  e.preventDefault();
  var notesTextarea = document.getElementById('addNotesTextarea').value;
  console.log(notesTextarea);
  var newEl = document.createElement('div');

  newEl.append(notesTextarea);
  newEl.className += " col-lg-2";
  console.log(newEl);

});

    <form id="newNoteForm">

        Add notes !
        <textarea class="form-control" id="addNotesTextarea" rows="3"></textarea>
        <input class="btn btn-danger btn-sm" type="submit" value="Add" id="btnAddNotes">

    </form>

Body:
If you want to addTextNode() then you can...

var div = document.createElement('div');
var txt = document.createTextNode('Whatever Text');
    div.appendChild(txt);

alternatively

var div = document.createElement('div')
    div.innerHTML = 'Whatever Text' // Whatever text parsed, <p>Words</p> is OK

alternatively

var div - document.createElement('div')
    div.textContent = 'Whatever' // Not parsed as HTML


问:
Save nested object with serializer in django rest framework
I'm getting a Json response to save it in my database, I need to get the items in line_items object. My Serializer and View works fine if I remove the line_items attribute in the model, but when I try to get that object and save it in the database nothing happens. Maybe I'm missing something in my serializer?

Json Structure:

```<code>{
    "id": 123456,
    "email": "jon@doe.ca",
    "created_at": "2017-03-29T15:56:48-04:00",
    "line_items": [
        {
            "id": 56789,
            "title": "Aviator sunglasses",
            "quantity": 1
         },

    {
        "id": 98765,
        "title": "Mid-century lounger",
        "quantity": 1
    }

    ]
}
</code>```

My model:

```<code>class Line(models.Model):
    title = models.CharField(max_length=100)
    quantity = models.IntegerField()

class Order(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    total_price = models.DecimalField(max_digits=6,decimal_places=2)
    line_items = models.ForeignKey(Line)
</code>```

My Serializer:

```<code>class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'
</code>```

My View:

```<code>@api_view(['POST'])
def orders(request):
    if request.method == 'POST':
        json_str = json.dumps(request.data)
        resp = json.loads(json_str)
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
I think you should add an explicit line_items field to OrderSerializer. Like this:</p>

```<code>class OrderSerializer(ModelSerializer):
    line_items = LineSerializer(many=True)
    class Meta:
        model = Order
        fields = '__all__'
</code>```

Body:
I'm getting a Json response to save it in my database, I need to get the items in line_items object. My Serializer and View works fine if I remove the line_items attribute in the model, but when I try to get that object and save it in the database nothing happens. Maybe I'm missing something in my serializer?

Json Structure:

{
    "id": 123456,
    "email": "jon@doe.ca",
    "created_at": "2017-03-29T15:56:48-04:00",
    "line_items": [
        {
            "id": 56789,
            "title": "Aviator sunglasses",
            "quantity": 1
         },

    {
        "id": 98765,
        "title": "Mid-century lounger",
        "quantity": 1
    }

    ]
}

My model:

class Line(models.Model):
    title = models.CharField(max_length=100)
    quantity = models.IntegerField()

class Order(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField()
    total_price = models.DecimalField(max_digits=6,decimal_places=2)
    line_items = models.ForeignKey(Line)

My Serializer:

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

My View:

@api_view(['POST'])
def orders(request):
    if request.method == 'POST':
        json_str = json.dumps(request.data)
        resp = json.loads(json_str)
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

Body:
I think you should add an explicit line_items field to OrderSerializer. Like this:

class OrderSerializer(ModelSerializer):
    line_items = LineSerializer(many=True)
    class Meta:
        model = Order
        fields = '__all__'


问:
Loading Selenium Page Objects Based on Browser Window Size
We are building a web application that has expandable workspaces on the sides of the page that expand and contract based on page size. when the workplace is contracted the page objects of the expanded list are not visible to be initialized when the class is called as the site is being developed in Angular 2.0

We are also building an automated test framework with Selenium with C# bindings and using the Page Object Model to run our automation. Is it possible load objects based on the window into a single page class like this

```<code>public class PageObjectClass
{
    public PageObjectClass(IwebDriver driver)
    {
        PageFactory.InitElements(driver, this)
    }

    private IWebElement anObjectVisibleWhenContracted
    //load an object that is not visible based on window size
}
</code>```

Or do I need to get the size of the window when I call the class and have separate classes based on window width in the test scripts like this?

```<code>if (driver.Manage().Window.Size.Width < 1280)
{
    someVar = new PageObjectClass(driver):
}
else
{
    someOtherVar = new exp[andedPageObjects
}
//do stuff here
</code>```

答:
I figured this out on my own. In the classes where I needed to deal with expandable workspaces, I declared all my variables in the class and didn't assign them any values before running PageFactory.InitElements

In the class constructor I passed in a Size variable along with the WebDriver that has the current size of the window. Then the objects that were appropriate for the window size were all loaded based on that

Just took a little restructuring and now it's working like a charm. Class structure looks like this now

```<code>public class ClassName: InheritedClass
{

    #region Page Objects

    private IWebElement object1;
    private IWebElement object2;

    #endregion

    public ClassName(IWebDriver driver, Size winSize)
    {
        PageFactory.InitElements(driver, this);

        if (winSize.Width > 1440)
        {
            object1= driver.FindElement(expanded By phrase locator);
            object1 = driver.FindElement(expanded By phrase locator);
        }
        else
        {
            object1= driver.FindElement(contracted By phrase locator);
            object1 = driver.FindElement(contracted By phrase locator);
        }
    }

    #region Page Methods that use these objects
    #endregion
}
</code>```

Body:
We are building a web application that has expandable workspaces on the sides of the page that expand and contract based on page size. when the workplace is contracted the page objects of the expanded list are not visible to be initialized when the class is called as the site is being developed in Angular 2.0

We are also building an automated test framework with Selenium with C# bindings and using the Page Object Model to run our automation. Is it possible load objects based on the window into a single page class like this

public class PageObjectClass
{
    public PageObjectClass(IwebDriver driver)
    {
        PageFactory.InitElements(driver, this)
    }

    private IWebElement anObjectVisibleWhenContracted
    //load an object that is not visible based on window size
}

Or do I need to get the size of the window when I call the class and have separate classes based on window width in the test scripts like this?

if (driver.Manage().Window.Size.Width < 1280)
{
    someVar = new PageObjectClass(driver):
}
else
{
    someOtherVar = new exp[andedPageObjects
}
//do stuff here

Body:
I figured this out on my own. In the classes where I needed to deal with expandable workspaces, I declared all my variables in the class and didn't assign them any values before running PageFactory.InitElements

In the class constructor I passed in a Size variable along with the WebDriver that has the current size of the window. Then the objects that were appropriate for the window size were all loaded based on that

Just took a little restructuring and now it's working like a charm. Class structure looks like this now

public class ClassName: InheritedClass
{

    #region Page Objects

    private IWebElement object1;
    private IWebElement object2;

    #endregion

    public ClassName(IWebDriver driver, Size winSize)
    {
        PageFactory.InitElements(driver, this);

        if (winSize.Width > 1440)
        {
            object1= driver.FindElement(expanded By phrase locator);
            object1 = driver.FindElement(expanded By phrase locator);
        }
        else
        {
            object1= driver.FindElement(contracted By phrase locator);
            object1 = driver.FindElement(contracted By phrase locator);
        }
    }

    #region Page Methods that use these objects
    #endregion
}


问:
Regex credit card number tests
I'm testing one application where Regex pattern match credit card then such numbers should be highlighted. I'm using site http://regexpal.com/ to create test credit credit card numbers for my testing. my requirement is to have valid credit card numbers which can have "-" and/or "," between them.I was not successful to build such a number as when i test it using the site

http://regexpal.com.

I need few credit numbers with scenarios below

valid credit card number which can have "-" between any digit.

valid credit card number which can have "," between any digit.

valid credit card number which can have cobination of  "," or "-" between any digit.

答:
The accepted answer is great, but to accommodate the new MasterCard BIN, I believe that it would need to be updated to:

^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$

(the critical piece being [25][1-7][0-9]{14}, since the first digit can now be either a 2 or a 5 and the second digit can be up to 7)

Please correct me if I'm wrong!

Title: Regex credit card number tests


问:
Saved file without extension. How to re-gain its original MIME Type?
I have a function in my app where the user can copy images to the app. The app will rename the added files to numbers, counting upwards, but without any file extension.

So basically if the user adds beach.jpg it saves a copy of the file to to the path/filename: "/gallery/1"

I'm saving an entry to the sqlite database which contains the original file name (among some other infos).

I've made a sharing function so the user can select the image from the grid gallery and then share it. The problem I now have is that when I'm reading the "gallery/1" file for sharing the MIME type is null (because there's no file name extension).

So my idea was to read the file and save a copy with the original file name to some temporary folder inside my app and then share that copied file.
The problem there is that the MIME type of the file is "application/octet-stream" and not "image/jpeg".

How can I re-gain the proper MIME type of the file? I could not figure out how to achieve this.

The problem now is that the apps I can select to send the image to is very limited because of the "octet-stream" MIME type. Whatsapp etc. is not selectable from the list.

My current code (snippets) look like this:

```<code>private void shareFile() {
    ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(activity);

    List<Uri> uris = getSelectedImagesAllGalleries();
    Log.d(TAG, "shareFile() uris size: " + uris.size());

    for (Uri uri : uris) {
        Log.d(TAG, "shareFile() URI: " + uri.getPath());
        Log.d(TAG, "shareFile() URI TYPE: " + activity.getContentResolver().getType(uri)); // is now always "application/octet-stream"
        shareIntent.setType(activity.getContentResolver().getType(uri));
        shareIntent.addStream(uri);
    }

    startActivity(shareIntent.getIntent());
}

private List<Uri> getSelectedImagesAllGalleries() {
    List<Uri> selectedImages = new ArrayList<>();
    selectedImages.addAll(getSelectedImages());
    return selectedImages;
}

private List<Uri> getSelectedImages() {
    List<Uri> uriList = new ArrayList<>();
    for (Media media : mediaList) {

        Log.d(TAG, "getSelectedImages(): " + media.getOriginalFileName() + " / " + media.isSelected());

        // Here I create a copy of the file using its original file name incl. its file extension
        File fileToShare = mediaTools.createTemporaryFileForSharing(media, activity);

        if (fileToShare.exists() && media.isSelected()) {
            Uri contentUri = FileProvider.getUriForFile(activity, activity.getPackageName(), fileToShare);
            uriList.add(contentUri);
        }
    }
    return uriList;
}
</code>```

Thanks for any help in advance.

答:
You would need inspect the file header bytes and compare the Magic Bytes in the header of the file to the known values for images to figure out what type it is.

Here is an answer to another similar question with a method of how to do this: Checking File Signature

Body:
I have a function in my app where the user can copy images to the app. The app will rename the added files to numbers, counting upwards, but without any file extension.

So basically if the user adds beach.jpg it saves a copy of the file to to the path/filename: "/gallery/1"

I'm saving an entry to the sqlite database which contains the original file name (among some other infos).

I've made a sharing function so the user can select the image from the grid gallery and then share it. The problem I now have is that when I'm reading the "gallery/1" file for sharing the MIME type is null (because there's no file name extension).

So my idea was to read the file and save a copy with the original file name to some temporary folder inside my app and then share that copied file.
The problem there is that the MIME type of the file is "application/octet-stream" and not "image/jpeg".

How can I re-gain the proper MIME type of the file? I could not figure out how to achieve this.

The problem now is that the apps I can select to send the image to is very limited because of the "octet-stream" MIME type. Whatsapp etc. is not selectable from the list.

My current code (snippets) look like this:

private void shareFile() {
    ShareCompat.IntentBuilder shareIntent = ShareCompat.IntentBuilder.from(activity);

    List<Uri> uris = getSelectedImagesAllGalleries();
    Log.d(TAG, "shareFile() uris size: " + uris.size());

    for (Uri uri : uris) {
        Log.d(TAG, "shareFile() URI: " + uri.getPath());
        Log.d(TAG, "shareFile() URI TYPE: " + activity.getContentResolver().getType(uri)); // is now always "application/octet-stream"
        shareIntent.setType(activity.getContentResolver().getType(uri));
        shareIntent.addStream(uri);
    }

    startActivity(shareIntent.getIntent());
}

private List<Uri> getSelectedImagesAllGalleries() {
    List<Uri> selectedImages = new ArrayList<>();
    selectedImages.addAll(getSelectedImages());
    return selectedImages;
}

private List<Uri> getSelectedImages() {
    List<Uri> uriList = new ArrayList<>();
    for (Media media : mediaList) {

        Log.d(TAG, "getSelectedImages(): " + media.getOriginalFileName() + " / " + media.isSelected());

        // Here I create a copy of the file using its original file name incl. its file extension
        File fileToShare = mediaTools.createTemporaryFileForSharing(media, activity);

        if (fileToShare.exists() && media.isSelected()) {
            Uri contentUri = FileProvider.getUriForFile(activity, activity.getPackageName(), fileToShare);
            uriList.add(contentUri);
        }
    }
    return uriList;
}

Thanks for any help in advance.


问:
In rails, whether to use form helpers or not to?
In rails, is it recommended to use form helpers? Internally, everything boils down to plain html then why not write the html directly? Performance will obviously be better in writing direct html than using helpers. Is using form helpers like a convention or something that rails developers must follow?</p>

答:
Define performance. Your performance or the applications? Say you have the same rhtml snippet spread out across your views. Say you have it in thousands of places. Maybe you even haven't gotten it exactly the same in all places. Now your customer wants to change this  (maybe different order of presentation or some such). It'll take you a while to do this in all the views, right? And chances are you won't get it right the first time. Chances are in fact that you'll keep getting bug reports for years to come on places you've missed to change.

The customer will end up paying a lot for that gained "performance". Maybe hundreds of working hours. Maybe tens of thousands if you avoid the DRY principle on principle. Think of all the servers and all the RAM she could buy for those work hours instead. If she spent it all on hardware her application might run hundred-folds faster. Think of all the fun things you could be working with instead of monkeying around changing html snippets.

OwnerDisplayName: Chirantan

LastEditorDisplayName: tvanfosson

OwnerDisplayName: PEZ


问:
Setting a tab's background with a layer-list drawable affecting layout
I'm trying to set a custom background for the tabs in my TabWidget. They're pretty much all just a bunch of rectangle shape gradients, but I found out that by setting the background drawables, it removes the default divider between each tab. To remedy this, I used a layer-list drawable to layer a divider on top of the tabs. However, now, it's affecting the layout of the tab itself, causing the image and text label to move apart.

Intended result

What I get by using a layer-list for the background

I'm just using this to setup the backgrounds:

```<code>TabWidget tw = mTabHost.getTabWidget();
for (int i = 0; i < tw.getChildCount(); i++) {
    View v = tw.getChildAt(i);
    v.setBackgroundDrawable(getResources().getDrawable (R.drawable.tab_background));
}
</code>```

Any clues as to why this is happenings, or suggestions on what else I can do instead?

答: It seems that using the layer-list as a background reset the all of the paddings within the view to 0. A bit non-sensical, considering a background drawable conceptually shouldn't affect any of this stuff, but whatever, I suppose. Saving the previous paddings and setting them back to what they were before fixes the problem.</p>

Body:
I'm trying to set a custom background for the tabs in my TabWidget. They're pretty much all just a bunch of rectangle shape gradients, but I found out that by setting the background drawables, it removes the default divider between each tab. To remedy this, I used a layer-list drawable to layer a divider on top of the tabs. However, now, it's affecting the layout of the tab itself, causing the image and text label to move apart.

Intended result

What I get by using a layer-list for the background

I'm just using this to setup the backgrounds:

TabWidget tw = mTabHost.getTabWidget();
for (int i = 0; i < tw.getChildCount(); i++) {
    View v = tw.getChildAt(i);
    v.setBackgroundDrawable(getResources().getDrawable (R.drawable.tab_background));
}

Any clues as to why this is happenings, or suggestions on what else I can do instead?


问:
Python kernel dies while doing a division in Pandas
I have a csv the size is about 94.4 MB and it contains 143,940 rows and 63 columns. I am just trying to divide two columns and outputting the value in another column. The code I am executing is a very simple code.

```<code>DF['Col3'] = DF['Col1'] / DF['Col2']
</code>```

Every time I execute this piece of code on my spyder3 or Jupyter Notebook the kernel dies I used to execute this code before but I dint have any problem. Now I get the error message

Kernel died, restarting

I am running python 2.7 and anaconda version 4.3.14 pandas version 0.19.2 on my laptop which has a 8 GB RAM. of which only 1 GB is utilized prior to running this code and utilizes 100% when I am running this code.

If there are any suggestions please guide. Thank you

答:
I found a solution here: https://www.coursera.org/learn/python-data-analysis/discussions/weeks/4/threads/VrKtIe-TEeahuQ5PjaKRFg

Apparently the kernel has issues with division between two series when there are NaNs involved. I solved the issue by replacing the "/" operator with the div() method as suggested.

Instead of doing df.col1 / df.col2, you can do df.col1.div(df.col2)

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.div.html

Body:
I have a csv the size is about 94.4 MB and it contains 143,940 rows and 63 columns. I am just trying to divide two columns and outputting the value in another column. The code I am executing is a very simple code.

DF['Col3'] = DF['Col1'] / DF['Col2']

Every time I execute this piece of code on my spyder3 or Jupyter Notebook the kernel dies I used to execute this code before but I dint have any problem. Now I get the error message

Kernel died, restarting

I am running python 2.7 and anaconda version 4.3.14 pandas version 0.19.2 on my laptop which has a 8 GB RAM. of which only 1 GB is utilized prior to running this code and utilizes 100% when I am running this code.

If there are any suggestions please guide. Thank you


问:
Mulesoft: How can dataweave read data from a Mule Subquery?
I am trying to pull data from SFDC & my query looks something like this:

```<code>   Select X,Y,(Select Z from OpportunityLine) from Opportunity;
</code>```

Post this I am trying to use dataweave to map it to values.

```<code>      <dw:transform-message doc:name="Salesforce Opportunity Selection">
      <dw:set-payload><![CDATA[%dw 1.0
      %output application/json
      ---
      payload map {
      id                  : $.X,
      name                : $.Y,

      }]]></dw:set-payload>
      </dw:transform-message>
</code>```

How can I grab values from my subquery into the map?

答:
specify a alias in your sql like this:

```<code>Select X,Y,(Select Z from OpportunityLine) FOO from Opportunity;
</code>```

then you can access FOO in your dataweave:

```<code><dw:transform-message doc:name="Salesforce Opportunity Selection">
<dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload map {
    id: $.X,
    name: $.Y,
    foo: $.FOO
}]]></dw:set-payload>
</dw:transform-message>
</code>```

you can read more about aliases in sql here.

Body:
I am trying to pull data from SFDC & my query looks something like this:

   Select X,Y,(Select Z from OpportunityLine) from Opportunity;

Post this I am trying to use dataweave to map it to values.

      <dw:transform-message doc:name="Salesforce Opportunity Selection">
      <dw:set-payload><![CDATA[%dw 1.0
      %output application/json
      ---
      payload map {
      id                  : $.X,
      name                : $.Y,

      }]]></dw:set-payload>
      </dw:transform-message>

How can I grab values from my subquery into the map?

Body:
specify a alias in your sql like this:

Select X,Y,(Select Z from OpportunityLine) FOO from Opportunity;

then you can access FOO in your dataweave:

<dw:transform-message doc:name="Salesforce Opportunity Selection">
<dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload map {
    id: $.X,
    name: $.Y,
    foo: $.FOO
}]]></dw:set-payload>
</dw:transform-message>

you can read more about aliases in sql here.


问:
Need help creating a program to read in entries and replace existing entry if there is one for that date
I am very new to coding and learning java, I can picture what the program needs to do however implementing to code has proven tough for me. I am trying to create a constructor. The constructor needs to do the following-
Constructor: When reading in and storing the individual quiz data, you will need to watch out for repeated quizzes. If a quiz is read in with a date that already has an entry stored, you will need to replace the earlier entry with the new one. I have been provided a java doc for this, however I will need to create the code. I have attached an image of the javadoc as well as the code that I currently have.

Javadoc for Constructor

```<code>public QuizList(String filename)
{
    this.quizzesList = 0;
    this.quizList = new ArrayList<Quiz>();

    try {
        Scanner infile = new Scanner(new File(filename));

        while (infile.hasNextLine()){
            String quizDate = infile.next();
            String pointsEarned = infile.next();
            String possiblePoints = infile.nextLine().trim();
            Quiz quiz = new Quiz(quizDate, points, possible);
            this.quizzes.add(quiz);
        }
        infile.close();
    }
    catch (java.io.FileNotFoundException e) {
        System.out.println("No such file: " + filename);
    }
</code>```

答:
File has lastModified method: https://docs.oracle.com/javase/8/docs/api/java/io/File.html.

I recommend you to iterate the files on the directory and check their last modified date.

Body:
I am very new to coding and learning java, I can picture what the program needs to do however implementing to code has proven tough for me. I am trying to create a constructor. The constructor needs to do the following-
Constructor: When reading in and storing the individual quiz data, you will need to watch out for repeated quizzes. If a quiz is read in with a date that already has an entry stored, you will need to replace the earlier entry with the new one. I have been provided a java doc for this, however I will need to create the code. I have attached an image of the javadoc as well as the code that I currently have.

Javadoc for Constructor

public QuizList(String filename)
{
    this.quizzesList = 0;
    this.quizList = new ArrayList<Quiz>();

    try {
        Scanner infile = new Scanner(new File(filename));

        while (infile.hasNextLine()){
            String quizDate = infile.next();
            String pointsEarned = infile.next();
            String possiblePoints = infile.nextLine().trim();
            Quiz quiz = new Quiz(quizDate, points, possible);
            this.quizzes.add(quiz);
        }
        infile.close();
    }
    catch (java.io.FileNotFoundException e) {
        System.out.println("No such file: " + filename);
    }


问:
swift XCTAssertEquals succeeded with Optional
I have this succeeded test:

```<code>func testProfileFieldValue() {
   let realm = try! Realm()
   let vs = ["name":"n"]
   createOrUpdate(realm: realm, value: vs)
   let profile = realm.objects(Profile.self).first
   XCTAssertEqual("n", profile?.name)
}
private func createOrUpdate(realm:Realm, value: Any = [:]) {
    try! realm.write() {
      realm.create(Profile.self,value:value,update: true)
    }
}
</code>```

Why did this test succeed? "n" is not an optional. If i try to assert:

```<code> XCTAssertEqual("nf", profile?.name)
</code>```

I get this failure message from Xcode:

XCTAssertEqual failed: ("Optional("nf")") is not equal to
  ("Optional("n")")

Why "nf" is and Optional?

thx

答:
please try this way apple suggest

```<code>if let profilename= profile?.name {
    XCTAssertEqual("n", profilename)
}
else {
    XCTFail("Value isn't set")
}
</code>```

UPDATE:
@MartinR comment good point out :

The non-optional on the left side "nf" gets automatically promoted to an optional.because  profile?.name is an optiona

More check this
Swift comparing Strings optionals vs non-optional

Body:
I have this succeeded test:

func testProfileFieldValue() {
   let realm = try! Realm()
   let vs = ["name":"n"]
   createOrUpdate(realm: realm, value: vs)
   let profile = realm.objects(Profile.self).first
   XCTAssertEqual("n", profile?.name)
}
private func createOrUpdate(realm:Realm, value: Any = [:]) {
    try! realm.write() {
      realm.create(Profile.self,value:value,update: true)
    }
}

Why did this test succeed? "n" is not an optional. If i try to assert:

 XCTAssertEqual("nf", profile?.name)

I get this failure message from Xcode:

XCTAssertEqual failed: ("Optional("nf")") is not equal to
  ("Optional("n")")

Why "nf" is and Optional?

thx

Body:
please try this way apple suggest

if let profilename= profile?.name {
    XCTAssertEqual("n", profilename)
}
else {
    XCTFail("Value isn't set")
}

UPDATE:
@MartinR comment good point out :

The non-optional on the left side "nf" gets automatically promoted to an optional.because  profile?.name is an optiona

More check this
Swift comparing Strings optionals vs non-optional


问:
Fail to add a new npm module to Angular2 application that is using SystemJS : "Error: (SystemJS) ToPrimitive is not defined"
I am trying to add an npm module to my Angular2 application that uses systemjs for loading modules. It is based on an online tutorial Angular 2 User Registration and Login Example & Tutorial that states it was based on  Angular 2 quickstart project.

The module that I am trying to add is ng2-completer. It is not the first module that I failed to integrate to my applcation; apparently I am missing something at configuring it properly although I follow and double check the installation & usage steps described at the module's page.

Before trying to add the module, I have a runing application with no problem.

The steps I follow are;

installing the npm package with npm install ng2-completer --save

updating systemjs.config.js file i.e., adding

'ng2-completer': 'node_modules/ng2-completer/ng2-completer.umd.js' line to the map field

updating app.module.ts file i.e., adding the

import { Ng2CompleterModule } from "ng2-completer";

directive and including Ng2CompleterModule in imports array of @NgModule configuration.

Up until I apply the third step my application continues to work properly. Following the third step, the browser Console displays the stack trace below:

which appears odd to me as if there is a problem in reflect-metadata/Reflect.js itself. I am more than willing to provide more information if it would help identifying the problem.

systemjs.config.js:

```<code>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'ng2-completer': 'node_modules/ng2-completer/ng2-completer.umd.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            "jwt-decode": {
                defaultExtension: "js"
            },
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);
</code>```

app.module.ts file:

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule } from '@angular/http';

import { fakeBackendProvider } from './_helpers/index';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions } from '@angular/http';

import { AppComponent }  from './app.component';
import { routing }        from './app.routing';
import { AppConfig } from './app.config';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, RoleService, MunicipalityService, UnitService, CommService } from './_services/index';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { MunicipalityComponent } from './municipality/index';
import { UnitComponent } from './unit/index';
import { UserComponent } from './user/index';
import { ManagementComponent } from './management/index';

import { Ng2CompleterModule } from "ng2-completer";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        Ng2CompleterModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        MunicipalityComponent,
        UserComponent,
        UnitComponent,
        ManagementComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        MunicipalityService,
        UnitService,
        RoleService,
        CommService
        // providers used to create fake backend
        //fakeBackendProvider,
        //MockBackend,
        //BaseRequestOptions
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }
</code>```

答:
If you check the package.json for ng2-complete you can see that it defines dependency with reflect-metadata as "reflect-metadata": "^0.1.3".

This means the minimal version is 0.1.3 but the ToPrimitive doesn't exist in reflect-metadata until v0.1.9. See https://github.com/rbuckton/reflect-metadata/blob/v0.1.9/Reflect.js#L712.

So try to specify reflect-metadata dependency in your app package.json as "reflect-metadata": "^0.1.9" which should force install 0.1.9 version.

Body:
I am trying to add an npm module to my Angular2 application that uses systemjs for loading modules. It is based on an online tutorial Angular 2 User Registration and Login Example & Tutorial that states it was based on  Angular 2 quickstart project.

The module that I am trying to add is ng2-completer. It is not the first module that I failed to integrate to my applcation; apparently I am missing something at configuring it properly although I follow and double check the installation & usage steps described at the module's page.

Before trying to add the module, I have a runing application with no problem.

The steps I follow are;

installing the npm package with npm install ng2-completer --save

updating systemjs.config.js file i.e., adding

'ng2-completer': 'node_modules/ng2-completer/ng2-completer.umd.js' line to the map field

updating app.module.ts file i.e., adding the

import { Ng2CompleterModule } from "ng2-completer";

directive and including Ng2CompleterModule in imports array of @NgModule configuration.

Up until I apply the third step my application continues to work properly. Following the third step, the browser Console displays the stack trace below:

which appears odd to me as if there is a problem in reflect-metadata/Reflect.js itself. I am more than willing to provide more information if it would help identifying the problem.

systemjs.config.js:

(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            app: 'app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs': 'npm:rxjs',
            'ng2-completer': 'node_modules/ng2-completer/ng2-completer.umd.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            "jwt-decode": {
                defaultExtension: "js"
            },
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            }
        }
    });
})(this);

app.module.ts file:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { HttpModule } from '@angular/http';

import { fakeBackendProvider } from './_helpers/index';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions } from '@angular/http';

import { AppComponent }  from './app.component';
import { routing }        from './app.routing';
import { AppConfig } from './app.config';

import { AlertComponent } from './_directives/index';
import { AuthGuard } from './_guards/index';
import { AlertService, AuthenticationService, UserService, RoleService, MunicipalityService, UnitService, CommService } from './_services/index';
import { HomeComponent } from './home/index';
import { LoginComponent } from './login/index';
import { RegisterComponent } from './register/index';
import { MunicipalityComponent } from './municipality/index';
import { UnitComponent } from './unit/index';
import { UserComponent } from './user/index';
import { ManagementComponent } from './management/index';

import { Ng2CompleterModule } from "ng2-completer";

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        Ng2CompleterModule,
        HttpModule,
        routing
    ],
    declarations: [
        AppComponent,
        AlertComponent,
        HomeComponent,
        LoginComponent,
        RegisterComponent,
        MunicipalityComponent,
        UserComponent,
        UnitComponent,
        ManagementComponent
    ],
    providers: [
        AppConfig,
        AuthGuard,
        AlertService,
        AuthenticationService,
        UserService,
        MunicipalityService,
        UnitService,
        RoleService,
        CommService
        // providers used to create fake backend
        //fakeBackendProvider,
        //MockBackend,
        //BaseRequestOptions
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }


问:
React Native Unhandled JS Exception: TypeError on new iOS project

I started getting this error when running an existing project withreact-native run-ios. To try to see if there was something wrong with my project I ran react-native init EmptyProject to create a blank project that should work perfectly. I still get this error even with that.

I've looked at this question on stack overflow and ran ./node_modules/react-native/packager/packager.sh start --resetCache on both my existing project and the empty project to no avail. Any clues as to what might be going on?

答:
After several hours of trial and error I managed to fix the problem. At this point, I don't know which specific thing fixed it, but here's all the main things I did.

Updated node to the latest version

brew update && brew upgrade

brew install watchman

Fixed all issues that came up with brew doctor

rm -rf ./node_modules ios android

yarn

react-native upgrade

Added babel-preset-react-native-stage-0 as a dev dependency in my package.json

Added "react-native-stage-0" as a preset to my babel.rc

./node_modules/react-native/packager/packager.sh start --resetCache

After all of that my projects have been running smoothly again without any problems.