问:
Python: how to make a pie chart based on a confusion matrix, and export it into HTML file
As per title, my confusion matrix is created like this:

```<code>#!/home/pdc-labor/anaconda/bin/python

import csv
import argparse
import pandas as pd

parser = argparse.ArgumentParser(description='Creating confusion matrix.')
parser.add_argument('-i', '--input', help='Input path/to/file.csv', required=True)
parser.add_argument('-oh', '--output-html', help='Output path/to/confusion_matrix.html', required=True)
parser.add_argument('-oc', '--output-csv', help='Output path/to/confusion_matrix.csv', required=True)
args = parser.parse_args()

data = csv.reader(open(args.input, 'r'), delimiter=";", quotechar='|')
next(data)

true_data = []
pred_data = []

for row in data:
    if len(row) >= 2:
        true_data.append(row[0])
        pred_data.append(row[1])

true_data = [s.strip().split('_')[0] for s in true_data]
pred_data = [s.strip().split('=')[0] for s in pred_data]

y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")
df_confusion = pd.crosstab(y_true, y_pred)
df_confusion.to_html(args.output_html)
df_confusion.to_csv(args.output_csv)
</code>```

So at the end, it will create a file.html which will contain a table with the confusion matrix. In the same file.html I want to add a pie chart, with the values inside the confusion matrix. As far as I've seen, this can be done, with Series.plot.pie. The problem is that I don't understand how... The guys put some random data in their tutorial, but I don't understand what that data means.

P.S. it is not mandatory to use pandas. My ultimate goal is to have the same file.html to contain a confusion matrix, and a pie chart with the data from confusion matrix.

Thanks in advance!

答:
This is not the most elegant way and also I am not sure as to what extent I am right or wrong but this is what I will be doing

```<code>import sklearn
y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")

cm = sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None)
</code>```

after this I would convert this array cm to list

```<code>list_1 = cm.tolist()
</code>```

and then store it in dataframe

```<code>df = pd.DataFrame(list_1, column = 'Confusion_Matrix', index=False)
</code>```

and plot it to pie

```<code> DataFrame.plot.pie(y='Confusion_Matrix')
</code>```

Hope this solves your problems

Cheers!

Body:
As per title, my confusion matrix is created like this:

#!/home/pdc-labor/anaconda/bin/python

import csv
import argparse
import pandas as pd

parser = argparse.ArgumentParser(description='Creating confusion matrix.')
parser.add_argument('-i', '--input', help='Input path/to/file.csv', required=True)
parser.add_argument('-oh', '--output-html', help='Output path/to/confusion_matrix.html', required=True)
parser.add_argument('-oc', '--output-csv', help='Output path/to/confusion_matrix.csv', required=True)
args = parser.parse_args()

data = csv.reader(open(args.input, 'r'), delimiter=";", quotechar='|')
next(data)

true_data = []
pred_data = []

for row in data:
    if len(row) >= 2:
        true_data.append(row[0])
        pred_data.append(row[1])

true_data = [s.strip().split('_')[0] for s in true_data]
pred_data = [s.strip().split('=')[0] for s in pred_data]

y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")
df_confusion = pd.crosstab(y_true, y_pred)
df_confusion.to_html(args.output_html)
df_confusion.to_csv(args.output_csv)

So at the end, it will create a file.html which will contain a table with the confusion matrix. In the same file.html I want to add a pie chart, with the values inside the confusion matrix. As far as I've seen, this can be done, with Series.plot.pie. The problem is that I don't understand how... The guys put some random data in their tutorial, but I don't understand what that data means.

P.S. it is not mandatory to use pandas. My ultimate goal is to have the same file.html to contain a confusion matrix, and a pie chart with the data from confusion matrix.

Thanks in advance!

Body:
This is not the most elegant way and also I am not sure as to what extent I am right or wrong but this is what I will be doing

import sklearn
y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")

cm = sklearn.metrics.confusion_matrix(y_true, y_pred, labels=None, sample_weight=None)

after this I would convert this array cm to list

list_1 = cm.tolist()

and then store it in dataframe

df = pd.DataFrame(list_1, column = 'Confusion_Matrix', index=False)

and plot it to pie

 DataFrame.plot.pie(y='Confusion_Matrix')

Hope this solves your problems

Cheers!


来源: stackexchange

问:
Python: summing elements in a sequence in increasing order and vice versa
I have the following sequence: (4, 6, 5, 11)
I want to have the outcome: (4, 10, 15, 26)

Can someone help me?

```<code>q = list()
for i in enumerate(seq):
    q = [x[i] + x[i-1] for x in seq]
</code>```

What if I would like to do the reverse? from (4, 10, 15, 26) to (4, 6, 5, 11)

答:
Try this:-</p>

```<code>i = [4, 6, 5, 11]
j = [sum(i[:k+1]) for k in range(len(i))]
print(j)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following sequence: (4, 6, 5, 11)
I want to have the outcome: (4, 10, 15, 26)

Can someone help me?

q = list()
for i in enumerate(seq):
    q = [x[i] + x[i-1] for x in seq]

What if I would like to do the reverse? from (4, 10, 15, 26) to (4, 6, 5, 11)

Body:
Try this:-

i = [4, 6, 5, 11]
j = [sum(i[:k+1]) for k in range(len(i))]
print(j)


问:
PHP Uncaught exception 'ImagickException' with message 'FailedToExecuteCommand'
I've installed the ImageMagick PHP extension on a MAC via pecl. it's showing up under phpinfo(), and lists PDF as a supported format.

I'm trying to read in a PDF and convert it to an image. However the constructor throws an exception when the source is a PDF. Image files work successfully.

```<code>$im = new imagick('TestDoc.pdf[0]'); // Throws Exception when PDF specified.
//$im = new imagick('TestImage.png'); // Succeeds.
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;

Fatal error: Uncaught exception 'ImagickException' with message 'FailedToExecuteCommand
`"gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -
dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4
"-r72x72" -dFirstPage=1 -dLastPage=1 "-sOutputFile=/var/tmp/magick-43594XlaRxeGWg1ps%d" "-
f/var/tmp/magick-43594O_WVqnAJTgzr" "-f/var/tmp/magick-43594ivJ_pKBcF3s7"' (-1) @
error/utility.c/SystemCommand/2029' in
/Users/garys/Documents/Projects/accrivia/code/test/test.php:8 Stack trace: #0
/Users/garys/Documents/Projects/accrivia/code/test/test.php(8): Imagick-
>__construct('../TestDoc.pdf[...') #1 {main} thrown in
/Users/garys/Documents/Projects/accrivia/code/test/test.php on line 8
</code>```

The tmp file mentioned in the output is created, but is 0 bytes. If I execute the full 'gs' command in the message (using actual files) on the command line, it works successfully.

ImageMagick and GhostScript were installed with brew.

In PHP, system('echo $PATH'); gives /usr/bin:/bin:/usr/sbin:/sbin
'gs' is in /usr/bin/

Does anyone have a suggestion. A web search for the exception message turns up nothing specific.

Many thanks
Gary.

答:
I had the same problem on MacOS High Sierra, PHP 7.0 installed from Homebrew. The problem is that FPM $PATH contains (as echoed by <php echo getenv('PATH'); ?>) /usr/bin:/bin:/usr/sbin:/sbin, which doesn't include Brew's /usr/local/bin/ install path.

To solve I added

env[PATH] = /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

to /usr/local/etc/php/7.0/php-fpm.d/www.conf, restarted php70 and worked! On Homebrew's forums @comes suggested to add the same to .env file

Body:
I've installed the ImageMagick PHP extension on a MAC via pecl. it's showing up under phpinfo(), and lists PDF as a supported format.

I'm trying to read in a PDF and convert it to an image. However the constructor throws an exception when the source is a PDF. Image files work successfully.

$im = new imagick('TestDoc.pdf[0]'); // Throws Exception when PDF specified.
//$im = new imagick('TestImage.png'); // Succeeds.
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;

Fatal error: Uncaught exception 'ImagickException' with message 'FailedToExecuteCommand
`"gs" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -
dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=pngalpha" -dTextAlphaBits=4 -dGraphicsAlphaBits=4
"-r72x72" -dFirstPage=1 -dLastPage=1 "-sOutputFile=/var/tmp/magick-43594XlaRxeGWg1ps%d" "-
f/var/tmp/magick-43594O_WVqnAJTgzr" "-f/var/tmp/magick-43594ivJ_pKBcF3s7"' (-1) @
error/utility.c/SystemCommand/2029' in
/Users/garys/Documents/Projects/accrivia/code/test/test.php:8 Stack trace: #0
/Users/garys/Documents/Projects/accrivia/code/test/test.php(8): Imagick-
>__construct('../TestDoc.pdf[...') #1 {main} thrown in
/Users/garys/Documents/Projects/accrivia/code/test/test.php on line 8

The tmp file mentioned in the output is created, but is 0 bytes. If I execute the full 'gs' command in the message (using actual files) on the command line, it works successfully.

ImageMagick and GhostScript were installed with brew.

In PHP, system('echo $PATH'); gives /usr/bin:/bin:/usr/sbin:/sbin
'gs' is in /usr/bin/

Does anyone have a suggestion. A web search for the exception message turns up nothing specific.

Many thanks
Gary.


答:
For Python3, use itertools.accumulate:

```<code>import itertools
s = (4, 6, 5, 11)
final_list = list(itertools.accumulate(s))
</code>```

Output:

```<code>[4, 10, 15, 26]
</code>```

For Python2, you can use a generator:

```<code>def accumulate(s):
   val = 0
   for i in s:
      val += i
      yield val

print(list(accumulate((4, 6, 5, 11))))
</code>```

Output:

```<code>[4, 10, 15, 26]
</code>```

Inverse:

```<code>def inverse(s):
   first = s[0]
   second = 0
   yield first
   for i in s[1:]:
      yield i-first
      first = i

print(list(inverse([4, 10, 15, 26])))
</code>```

Output:

```<code>[4, 6, 5, 11]
</code>```

Title: Python: summing elements in a sequence in increasing order and vice versa

Body:
For Python3, use itertools.accumulate:

import itertools
s = (4, 6, 5, 11)
final_list = list(itertools.accumulate(s))

Output:

[4, 10, 15, 26]

For Python2, you can use a generator:

def accumulate(s):
   val = 0
   for i in s:
      val += i
      yield val

print(list(accumulate((4, 6, 5, 11))))

Output:

[4, 10, 15, 26]

Inverse:

def inverse(s):
   first = s[0]
   second = 0
   yield first
   for i in s[1:]:
      yield i-first
      first = i

print(list(inverse([4, 10, 15, 26])))

Output:

[4, 6, 5, 11]


问:
Select a child of a child
Why can't I select a child of a child in jQuery? I want to add a class to a child of a child using .children() method and the > selector. See code below:

```<code>$(function(){
        // main expansion element
        $(".expander").click(function() {
            var subShown = $(this).children("ul > li").hasClass("show");
            if (!subShown) {
                $(this).children(".indented").slideDown('100').addClass("show");
                $(this).children(".caret").addClass("reversedCaret");
            } else {
                $(this).children(".indented").slideUp('100').removeClass("show");
                $(this).children(".caret").removeClass("reversedCaret");
            }
        });
    });
</code>```

HTML:

```<code><div class="expander">
                  <span class="caret downCaret right visibleCaret">+</span>
                  <ul>
                  <li class="category">Item 1<a href="http://www.google.com"></a></li>
                  <li class="indented"><a href="http://www.google.com">Item 2</a></li>
                  <li class="indented"><a href="http://www.google.com">Item 3</a></li>
                  </ul>
                </div>
</code>```

When I click on expander it will not add the class to my li elements. Why?

答:
.querySelector

document.querySelector("section > div").classList.add("my-gray");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.my-gray{
  background: gray;
}</code>```

Foo

Bar

```

Title: Select a child of a child

Body:
Why can't I select a child of a child in jQuery? I want to add a class to a child of a child using .children() method and the > selector. See code below:

$(function(){
        // main expansion element
        $(".expander").click(function() {
            var subShown = $(this).children("ul > li").hasClass("show");
            if (!subShown) {
                $(this).children(".indented").slideDown('100').addClass("show");
                $(this).children(".caret").addClass("reversedCaret");
            } else {
                $(this).children(".indented").slideUp('100').removeClass("show");
                $(this).children(".caret").removeClass("reversedCaret");
            }
        });
    });

HTML:

                  +

Item 1

Item 2

Item 3

When I click on expander it will not add the class to my li elements. Why?

Body:
.querySelector

document.querySelector("section > div").classList.add("my-gray");

.my-gray{
  background: gray;
}

<section>
Foo
<div>
Bar
</div>
</section>


问:
Fix Github commits which are not counted
I made some commits to github in different times from different clients. Now I see, in my profile some of them don't show up. When I go and check the commit, I can see it there but without my profile picture. From it I understand, this is because of my local configs of clients.

Is there a way I can edit past commits or make the ones with wrong configs show up in my profile ?

EDIT: I can view my commits at github. But ones i made from my mac with profile picture and ones i made from my windows pc, without profile picture. Now i know, when i fix it, my future commits will be counted. What i am asking is what about the past ones ?

答: Github identifies your commits according to your email address. Add your second email address to your account and everything should be counted.</p>


问:
How to differentiate the action when a user hit CANCEL button or OK button under a Inputbox.
How to differentiate the action when a user hit CANCEL button or OK button under a Inputbox.

There are two scenarios:

1. To end (Exit Sub) the operation when user hit Cancel/Close button

2. If user hit OK without any value ask him to enter some value.

The code i use satisfy 2nd scenario, is it possible to accommodate 1st scenario as well?

```<code>Sub INPUT_BOX()

Re_Enter_Username:
cUsername = INPUTBOX("Username", "Please provide Login Name")
    If cUsername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If

End Sub
</code>```

I am not sure whether this is possible, may be my exception was more than what VBA can help provide. :) Sorry if so.

And thanks if you have a solution for this.

答:
You can test using StrPtr like this:

```<code>cusername = InputBox("Username", "Please provide Login Name")
    If StrPtr(cusername) = 0 Then
        ' user pressed Cancel
        Exit Sub
    ElseIf cusername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If
</code>```

Body:
How to differentiate the action when a user hit CANCEL button or OK button under a Inputbox.

There are two scenarios:

1. To end (Exit Sub) the operation when user hit Cancel/Close button

2. If user hit OK without any value ask him to enter some value.

The code i use satisfy 2nd scenario, is it possible to accommodate 1st scenario as well?

Sub INPUT_BOX()

Re_Enter_Username:
cUsername = INPUTBOX("Username", "Please provide Login Name")
    If cUsername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If

End Sub

I am not sure whether this is possible, may be my exception was more than what VBA can help provide. :) Sorry if so.

And thanks if you have a solution for this.

Body:
You can test using StrPtr like this:

cusername = InputBox("Username", "Please provide Login Name")
    If StrPtr(cusername) = 0 Then
        ' user pressed Cancel
        Exit Sub
    ElseIf cusername = "" Then
        MsgBox "Please provide a Username"
        GoTo Re_Enter_Username:
    Else 'Code if not empty
    End If


问:
SQLite Not Saving JSON Token
I have a DBHelper class and I have saved info from user. I also want to save the user's token from server but errors are showing in logcat. Please look at my code and point out my mistake.

My DBHelper class:

```<code>public class DBHelper {

private static final String DATABASE_NAME = "tingUser.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String IMAGES_TABLE = "userImage";

private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
public static final String COL_TOKEN = "JWT Token";

private static final String COL_PROFILE_PHOTO = "profilePhoto";

private Context mCtx;

private DatabaseManager databaseManager;
private SQLiteDatabase db;

public DBHelper(Context context){
    this.mCtx = context;
    databaseManager = new DatabaseManager(mCtx);
}

public DBHelper open() throws SQLException{
    db = databaseManager.getWritableDatabase();
    return this;
}

public void close(){
    databaseManager.close();
}

public boolean saveInputField(TingTingUser user){
    SQLiteDatabase userDb = databaseManager.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(COL_FULL_NAME, user.getDisplayName());
    values.put(COL_USER_ID, user.getUserId());
    values.put(COL_GENDER, user.getGender());
    values.put(COL_DOB, user.getDob());
    values.put(COL_MOBILE_NUM, user.getMobileNumber());
    values.put(COL_ORGANIZATION, user.getOrganization());
    values.put(COL_OCCUPATION, user.getOccupation());
    values.put(COL_TOKEN, user.getJWT_token());
    Log.d("database",values.toString());
    //values.put(COL_TOKEN, (user.getJWT_token() != null) ? user.getJWT_token() : null);

    long result = userDb.insert(TABLE_NAME, null, values); // error occurs here
    userDb.close();

    if (result == -1){
        return false;
    } else {
        return true;
    }

}

public TingTingUser getCurrentUser(int id){
    SQLiteDatabase currDB = databaseManager.getWritableDatabase();
    Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()){
        TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7) );
        return user;
    }

    return null;

}

public void saveCameraImage(byte[] imageBytes){
    SQLiteDatabase camDb = databaseManager.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_PROFILE_PHOTO, imageBytes);
    camDb.insert(IMAGES_TABLE, null, contentValues);
}

public void saveGalleryImage(byte[] imageBytes){
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_PROFILE_PHOTO, imageBytes);
    db.insert(IMAGES_TABLE, null, contentValues);
}

public byte[] getImage(){
    Cursor cursor = db.query(true, IMAGES_TABLE, new String[]{COL_PROFILE_PHOTO,}, null, null, null, null, COL_ID + " DESC", "1");
    if (cursor.moveToFirst()){
        byte[] blob = cursor.getBlob(cursor.getColumnIndex(COL_PROFILE_PHOTO));
        cursor.close();
        return blob;
    }
    cursor.close();
    Toast.makeText(mCtx, "No Image Found", Toast.LENGTH_SHORT).show();
    return null;
}

public class DatabaseManager extends SQLiteOpenHelper {

    public DatabaseManager(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String db_create = " Create Table " + TABLE_NAME + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL_USER_ID + " TEXT, "
                + COL_FULL_NAME + " TEXT, "
                + COL_GENDER + " TEXT, "
                + COL_DOB + " TEXT, "
                + COL_MOBILE_NUM + " TEXT, "
                + COL_OCCUPATION + " TEXT, "
                + COL_ORGANIZATION + " TEXT "
                + COL_TOKEN + " TEXT VARCHAR 1024) ";
        sqLiteDatabase.execSQL(db_create);

        String img_create = "Create table " + IMAGES_TABLE + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL_PROFILE_PHOTO + " BLOB NOT NULL )";
        sqLiteDatabase.execSQL(img_create);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + IMAGES_TABLE);
        onCreate(sqLiteDatabase);
    }

}

}
</code>```

In my activity, other fields are saving except the token. I have called helper method to save token like this:

```<code>JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
                Log.d("OTPDialogFragment", "OTP Verified Successfully");

                try {
                    JSONObject verifyObject = new JSONObject(response.toString());
                    JSONObject userObject = verifyObject.getJSONObject("user");

                    userId = userObject.getString("_id");
                    Log.d(TAG, "Retrieved user id is:\t" + userId);

                    userToken = verifyObject.getString("token");  // getting user token from server correctly
                    Log.d("jwt token", userToken);

                    TingTingUser user = new TingTingUser();
                    user.setDisplayName(fullName);
                    user.setMobileNumber(num);
                    user.setGender(genderVal);
                    user.setDob(dob);
                    user.setOccupation("default");
                    user.setOrganization("default");
                    user.setUserId(userId);
                    user.setJWT_token(userToken);  // saving in model class

                    if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId) && !userToken.isEmpty()){

                        if (dbHelper.saveInputField(user) == true){  // saving model object in db and error occurs here
                            Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show();
                        }
</code>```

Error in logcat:

```<code>Error inserting JWT Token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YTA5YTM3NDJhODE1YjIyNzhkMzBmYWUiLCJpYXQiOjE1MTA1ODExMTh9.0SpOuVkxAKQew539dif2Gjd2DRKgiR-A0IpU9mgs_zA fullName=the link userId=5a09a3742a815b2278d30fae occupation=default gender=Male DOB=1578335820 mobileNum=1234566789 organization=default
                                                                       android.database.sqlite.SQLiteException: near "Token": syntax error (code 1): , while compiling: INSERT INTO profileInfo(JWT Token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)
                                                                           at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                           at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                           at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                           at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                           at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                           at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                           at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                           at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                           at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:71)
                                                                           at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:480)
                                                                           at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:452)
                                                                           at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                                                                           at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                           at android.os.Handler.handleCallback(Handler.java:742)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5529)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
</code>```

It shows a syntax error in my create table statement, but everything seems fine by me. Please point out my mistake. Thanks.

答:
It should be:

```<code>INSERT INTO profileInfo(JWT_token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)
</code>```

You cannot have spaces in variables.

Title: SQLite Not Saving JSON Token

Body:
I have a DBHelper class and I have saved info from user. I also want to save the user's token from server but errors are showing in logcat. Please look at my code and point out my mistake.

My DBHelper class:

public class DBHelper {

private static final String DATABASE_NAME = "tingUser.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "profileInfo";
private static final String IMAGES_TABLE = "userImage";

private static final String COL_ID = "databaseId";
public static final String COL_USER_ID = "userId";
public static final String COL_FULL_NAME = "fullName";
public static final String COL_GENDER = "gender";
public static final String COL_DOB = "DOB";
public static final String COL_MOBILE_NUM = "mobileNum";
public static final String COL_OCCUPATION = "occupation";
public static final String COL_ORGANIZATION = "organization";
public static final String COL_TOKEN = "JWT Token";

private static final String COL_PROFILE_PHOTO = "profilePhoto";

private Context mCtx;

private DatabaseManager databaseManager;
private SQLiteDatabase db;

public DBHelper(Context context){
    this.mCtx = context;
    databaseManager = new DatabaseManager(mCtx);
}

public DBHelper open() throws SQLException{
    db = databaseManager.getWritableDatabase();
    return this;
}

public void close(){
    databaseManager.close();
}

public boolean saveInputField(TingTingUser user){
    SQLiteDatabase userDb = databaseManager.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(COL_FULL_NAME, user.getDisplayName());
    values.put(COL_USER_ID, user.getUserId());
    values.put(COL_GENDER, user.getGender());
    values.put(COL_DOB, user.getDob());
    values.put(COL_MOBILE_NUM, user.getMobileNumber());
    values.put(COL_ORGANIZATION, user.getOrganization());
    values.put(COL_OCCUPATION, user.getOccupation());
    values.put(COL_TOKEN, user.getJWT_token());
    Log.d("database",values.toString());
    //values.put(COL_TOKEN, (user.getJWT_token() != null) ? user.getJWT_token() : null);

    long result = userDb.insert(TABLE_NAME, null, values); // error occurs here
    userDb.close();

    if (result == -1){
        return false;
    } else {
        return true;
    }

}

public TingTingUser getCurrentUser(int id){
    SQLiteDatabase currDB = databaseManager.getWritableDatabase();
    Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()){
        TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7) );
        return user;
    }

    return null;

}

public void saveCameraImage(byte[] imageBytes){
    SQLiteDatabase camDb = databaseManager.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_PROFILE_PHOTO, imageBytes);
    camDb.insert(IMAGES_TABLE, null, contentValues);
}

public void saveGalleryImage(byte[] imageBytes){
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_PROFILE_PHOTO, imageBytes);
    db.insert(IMAGES_TABLE, null, contentValues);
}

public byte[] getImage(){
    Cursor cursor = db.query(true, IMAGES_TABLE, new String[]{COL_PROFILE_PHOTO,}, null, null, null, null, COL_ID + " DESC", "1");
    if (cursor.moveToFirst()){
        byte[] blob = cursor.getBlob(cursor.getColumnIndex(COL_PROFILE_PHOTO));
        cursor.close();
        return blob;
    }
    cursor.close();
    Toast.makeText(mCtx, "No Image Found", Toast.LENGTH_SHORT).show();
    return null;
}

public class DatabaseManager extends SQLiteOpenHelper {

    public DatabaseManager(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String db_create = " Create Table " + TABLE_NAME + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL_USER_ID + " TEXT, "
                + COL_FULL_NAME + " TEXT, "
                + COL_GENDER + " TEXT, "
                + COL_DOB + " TEXT, "
                + COL_MOBILE_NUM + " TEXT, "
                + COL_OCCUPATION + " TEXT, "
                + COL_ORGANIZATION + " TEXT "
                + COL_TOKEN + " TEXT VARCHAR 1024) ";
        sqLiteDatabase.execSQL(db_create);

        String img_create = "Create table " + IMAGES_TABLE + " ("
                + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COL_PROFILE_PHOTO + " BLOB NOT NULL )";
        sqLiteDatabase.execSQL(img_create);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + IMAGES_TABLE);
        onCreate(sqLiteDatabase);
    }

}

}

In my activity, other fields are saving except the token. I have called helper method to save token like this:

JsonObjectRequest otpObjectRequest = new JsonObjectRequest(Request.Method.POST, Constants.TING_VERIFY_OTP_ENDPOINT, verifyOTPObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d("OTPDialogFragment", "OTP Verification Response is: \t" + response.toString());
                Log.d("OTPDialogFragment", "OTP Verified Successfully");

                try {
                    JSONObject verifyObject = new JSONObject(response.toString());
                    JSONObject userObject = verifyObject.getJSONObject("user");

                    userId = userObject.getString("_id");
                    Log.d(TAG, "Retrieved user id is:\t" + userId);

                    userToken = verifyObject.getString("token");  // getting user token from server correctly
                    Log.d("jwt token", userToken);

                    TingTingUser user = new TingTingUser();
                    user.setDisplayName(fullName);
                    user.setMobileNumber(num);
                    user.setGender(genderVal);
                    user.setDob(dob);
                    user.setOccupation("default");
                    user.setOrganization("default");
                    user.setUserId(userId);
                    user.setJWT_token(userToken);  // saving in model class

                    if (!TextUtils.isEmpty(fullName) && !TextUtils.isEmpty(genderVal) && !TextUtils.isEmpty(dob) && !TextUtils.isEmpty(userId) && !userToken.isEmpty()){

                        if (dbHelper.saveInputField(user) == true){  // saving model object in db and error occurs here
                            Toast.makeText(getContext(), "Saved User", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(), "Save Failed", Toast.LENGTH_SHORT).show();
                        }

Error in logcat:

Error inserting JWT Token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1YTA5YTM3NDJhODE1YjIyNzhkMzBmYWUiLCJpYXQiOjE1MTA1ODExMTh9.0SpOuVkxAKQew539dif2Gjd2DRKgiR-A0IpU9mgs_zA fullName=the link userId=5a09a3742a815b2278d30fae occupation=default gender=Male DOB=1578335820 mobileNum=1234566789 organization=default
                                                                       android.database.sqlite.SQLiteException: near "Token": syntax error (code 1): , while compiling: INSERT INTO profileInfo(JWT Token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)
                                                                           at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                           at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                           at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                           at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                           at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                           at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                           at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                                           at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                                           at com.billionusers.tingting.db.DBHelper.saveInputField(DBHelper.java:71)
                                                                           at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:480)
                                                                           at com.billionusers.tingting.activities.SignUpActivity$OTPDialogFragment$6.onResponse(SignUpActivity.java:452)
                                                                           at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                                                                           at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                           at android.os.Handler.handleCallback(Handler.java:742)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                           at android.os.Looper.loop(Looper.java:154)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5529)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)

It shows a syntax error in my create table statement, but everything seems fine by me. Please point out my mistake. Thanks.

Body:
It should be:

INSERT INTO profileInfo(JWT_token,fullName,userId,occupation,gender,DOB,mobileNum,organization) VALUES (?,?,?,?,?,?,?,?)

You cannot have spaces in variables.


问:
Reloading SolrCloud configuration (stored on Zookeeper) - schema.xml
I have setup a SolrCloud replication using standalone zookeeper. But now I wish to make some changes to my Schema.xml and reload the core. The problem is that when I run a single server Solr (no solrcloud) the new schema is loaded, but I do not know how to reload schema on all the replication server. I tried reloading the schema on one of the server with no desired impact. Is there a way in which I can reload my schema.xml in Solr in distributed replication setup which uses zookeeper. </p>

答:
This worked for me :

```<code>    bin/solr zk -upconfig -n collectionName -d pathto/Conf_directory -z localhost:2181/solr
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This worked for me :

    bin/solr zk -upconfig -n collectionName -d pathto/Conf_directory -z localhost:2181/solr


问:
Check if a rule already exists
When creating a rule for a user defined data type, how do I check if the rule already exists?</p>

```<code>-- does rule exist?
CREATE RULE MyRule
AS @MyVar IN ('foo1', 'foo2')
</code>```

答:
```<code>if not  exists(Select 1 from sys.all_objects where type='r')
begin

create rule syntax

end
</code>```

You could also use sys.objects

```<code> if not  exists(Select 1 from sys.objects where type='r')
    begin

    create rule syntax

    end
</code>```

References:

https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-all-objects-transact-sql

Title: Check if a rule already exists

Body:
When creating a rule for a user defined data type, how do I check if the rule already exists?

-- does rule exist?
CREATE RULE MyRule
AS @MyVar IN ('foo1', 'foo2')

Body:
if not  exists(Select 1 from sys.all_objects where type='r')
begin

create rule syntax

end

You could also use sys.objects

 if not  exists(Select 1 from sys.objects where type='r')
    begin

    create rule syntax

    end

References:

https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-all-objects-transact-sql


问:
GROUP_BY WITH DISTINCT QUERY
Am using Oracle 12c, below is the column:

```<code>CENTER_ID     UNIT      EMPLOYEEID    LESSON  MINS_STUDIED  SECTION
I234          4         G01234         4.1        5            EX
I234          4         G01234         4.1        5            LN
I234          4         G01234         4.1        5            VO

I234          4         G0123          4.2        5            EX
I234          4         G0123          4.2        5            LN
I234          4         G0123          4.2        5            VO

I2345         5         G023           5.2       12            EX
I2345         5         G023           5.2       12            LN
I2345         5         G023           5.2       12            VO
</code>```

From record 1 to 6, it contains 2 distinct employee_id who studied unit 4. In this case, I need total minutes spent per unit (center_id wise).

But I want to add only distinct MINS_STUDIED based on EMPLOYEE_ID.

So, total minutes spent for center_id I234 for unit 4 is (5+5)=10 and for center_id I2345 for unit 5 is 12.

I used the below query

```<code>    SELECT
         COUNT(DISTINCT EMPLOYEE_ID),CENTER_ID,UNIT,
         SUM(DISTINCT MINS_STUDIED)
    FROM
         TEST_DATA
    GROUP BY
          CENTER_ID,DBD.UNIT;
</code>```

The above query returns

```<code>center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       5
I2345         5      1                       12
</code>```

But, I need the output like below:

```<code>center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       10
I2345         5      1                       12
</code>```

答:
If we assume you only have two employeeID's and the last entry is a typo..

Simply get a distinct list before you calculate totals.

```<code>SELECT center_ID, unit, count(EmployeeID) cnt, sum(hours_Studied) sumHrs
FROM (SELECT distinct Center_ID, Unit, EmployeeID, hours_Studied
      FROM test_data) TD
GROUP BY CENTER_ID, unit
</code>```

Giving us: I234, 4, 2, 10

or using an analytic:  though I'm not sure how to handle what hours_studied to sum if they very by employeeID... so the ordering may be incorrect.

```<code>SELECT Center_ID, Unit, count(Distinct EmployeeID) cnt_Dist_Emp , sum(Hours_Studied) sum_hrs
FROM (Select row_number() over (PARTITION BY center_ID, unit, employeeID, Hours_Studied order by center_ID, unit, employeeID, Hours_Studied ) rn, TD.*
      FROM Test_data td)
WHERE RN = 1
GROUP BY Center_ID, Unit
</code>```

Title: GROUP_BY WITH DISTINCT QUERY

Body:
Am using Oracle 12c, below is the column:

CENTER_ID     UNIT      EMPLOYEEID    LESSON  MINS_STUDIED  SECTION
I234          4         G01234         4.1        5            EX
I234          4         G01234         4.1        5            LN
I234          4         G01234         4.1        5            VO

I234          4         G0123          4.2        5            EX
I234          4         G0123          4.2        5            LN
I234          4         G0123          4.2        5            VO

I2345         5         G023           5.2       12            EX
I2345         5         G023           5.2       12            LN
I2345         5         G023           5.2       12            VO

From record 1 to 6, it contains 2 distinct employee_id who studied unit 4. In this case, I need total minutes spent per unit (center_id wise).

But I want to add only distinct MINS_STUDIED based on EMPLOYEE_ID.

So, total minutes spent for center_id I234 for unit 4 is (5+5)=10 and for center_id I2345 for unit 5 is 12.

I used the below query

    SELECT
         COUNT(DISTINCT EMPLOYEE_ID),CENTER_ID,UNIT,
         SUM(DISTINCT MINS_STUDIED)
    FROM
         TEST_DATA
    GROUP BY
          CENTER_ID,DBD.UNIT;

The above query returns

center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       5
I2345         5      1                       12

But, I need the output like below:

center_id    UNIT  DISTINCT(EMPLOYEE_ID) TOTAL_MINS_STUDIED
I234          4      2                       10
I2345         5      1                       12

Body:
If we assume you only have two employeeID's and the last entry is a typo..

Simply get a distinct list before you calculate totals.

SELECT center_ID, unit, count(EmployeeID) cnt, sum(hours_Studied) sumHrs
FROM (SELECT distinct Center_ID, Unit, EmployeeID, hours_Studied
      FROM test_data) TD
GROUP BY CENTER_ID, unit

Giving us: I234, 4, 2, 10

or using an analytic:  though I'm not sure how to handle what hours_studied to sum if they very by employeeID... so the ordering may be incorrect.

SELECT Center_ID, Unit, count(Distinct EmployeeID) cnt_Dist_Emp , sum(Hours_Studied) sum_hrs
FROM (Select row_number() over (PARTITION BY center_ID, unit, employeeID, Hours_Studied order by center_ID, unit, employeeID, Hours_Studied ) rn, TD.*
      FROM Test_data td)
WHERE RN = 1
GROUP BY Center_ID, Unit


问:
Get just the integer from wc in bash
Is there a way to get the integer that wc returns in bash?

Basically I want to write the line numbers and word counts to the screen after the file name.

output: filename linecount wordcount
Here is what I have so far:

```<code>files=\`ls`
for f in $files;
do
        if [ ! -d $f ] #only print out information about files !directories
        then
                # some way of getting the wc integers into shell variables and then printing them
                echo "$f $lines $words"
        fi
done
```

答:
```<code>files=`ls`
echo "$files" | wc -l | perl -pe "s#^\s+##"
</code>```

Title: Get just the integer from wc in bash

Body:
Is there a way to get the integer that wc returns in bash?

Basically I want to write the line numbers and word counts to the screen after the file name.

output: filename linecount wordcount
Here is what I have so far:

files=\`ls`
for f in $files;
do
        if [ ! -d $f ] #only print out information about files !directories
        then
                # some way of getting the wc integers into shell variables and then printing them
                echo "$f $lines $words"
        fi
done


问:
Abort Trap: 6 error in the new Swift 3.1/Xcode 8.3
I have a finished project with about 30vcs, Firebase, Googlemaps integration, etc - ie a really big complicated project, it is a geolocation based game that I've finally finished after several months of work.

Worked and compiled just fine, until I tried to compile it in the new Swift 3.1/ Xcode 8.3.

After changing the recommended syntax on a few lines to clear the new XCODE 8.3 errors, compiling fails with "Abort Trap: 6" error.

This is the last few lines of the debugger (prior to that theres about 100 lines of incomprehensible file names/numbers etc).

0  swift                    0x00000001089f1eb7
  PrintStackTraceSignalHandler(void*) + 39 1  swift

  0x00000001089f1366 SignalHandler(int) + 646 2
  libsystem_platform.dylib 0x00007fffc602eb3a _sigtramp + 26 3
  libsystem_platform.dylib 0x0000000100000001 _sigtramp + 972887265 4
  libsystem_c.dylib        0x00007fffc5eb3420 abort + 129 5  swift

  0x0000000106454644
  swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 38404 6  swift

  0x00000001064564fa
  swift::ModuleFile::getType(llvm::PointerEmbeddedInt)
  + 2106 7  swift                    0x000000010644f373 swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 17203 8  swift

  0x0000000106459f24
  swift::ModuleFile::maybeReadPattern(swift::DeclContext*) + 740 9
  swift                    0x000000010644f605
  swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 17861 10 swift

  0x00000001064607c8 swift::ModuleFile::loadAllMembers(swift::Decl*,
  unsigned long long) + 600 11 swift

  0x0000000106840f0d swift::NominalTypeDecl::getMembers() const + 125 12
  swift                    0x0000000106828c75 (anonymous
  namespace)::Traversal::visitNominalTypeDecl(swift::NominalTypeDecl*) +
  869 13 swift                    0x0000000106826645 (anonymous
  namespace)::Traversal::doIt(swift::Decl*) + 277 14 swift

  0x000000010619a75f
  swift::SILPassManager::SILPassManager(swift::SILModule*,
  llvm::StringRef) + 1471 15 swift                    0x00000001061a135f
  swift::runSILDiagnosticPasses(swift::SILModule&) + 159 16 swift

  0x0000000105811282 swift::performFrontend(llvm::ArrayRef,
  char const*, void*, swift::FrontendObserver*) + 42866 17 swift

  0x00000001057c088c main + 9052 18 libdyld.dylib

  0x00007fffc5e1f235 start + 1 Stack dump:

(here is about 150 lines of incomprehensible debugging numbers/files/alphanumericals - followed by this in the end):

While loading members for 'homePage' in module 'googleMapsPractice'

While deserializing PatternBindingDecl #295in 'googleMapsPractice'

While deserializing 'gameDBRef' (VarDecl #296)in 'googleMapsPractice'

While deserializing decl #1009 (XREF)in 'googleMapsPractice'

Cross-reference to module 'FirebaseDatabase'    ... FIRDatabaseReference

I am really stuck as I don't know where to look to debug this.

'homePage.swift' is the set-up page VC of the game, and is the only VC referenced in the debugger, is there any common solutions to Abort Trap 6 errors that I could try weed out on this VC? It is probably 2000 lines of code and i'm not even sure the problem lies in that VC as the debugger is so vague.

Any help would be greatly appreciated

答: This happened to me because I had a private enum in both the main class, and an extension of that class. Both of these were in the same file. Tricky one!


答:
Not very efficient but you can do:</p>

```<code>x= [4, 6, 5, 11]
y = [sum(x[0:i+1] for i in range(len(x))]
</code>```

Body:
Not very efficient but you can do:

x= [4, 6, 5, 11]
y = [sum(x[0:i+1] for i in range(len(x))]


问:
ember-drag-sort: implementing a sortable list based on an HTML table?
Originally asked by @livfwd on GitHub.

It seems like the :before :after pseudo-elements break the table layout and put the placeholder in unexpected places when dragging rows within a table.

Are there any known workarounds for this?

答:
ember-drag-sort uses a simple CSS technique to render the placeholder: :before and :after pseudoelements.

Unfortunately, this doesn't work with HTML tables because table semantics are very restrictive. To work around this problem, top/bottom padding on table cells can be used instead of selectors.

This is not a great solution because padding appears inside table cells. If you want your cells to have borders, you'll have to apply them to inner elements instead.

Tables are now part of the demo, please have a look.

Here are the CSS overrides used in the demo:

```<code>    table {
      width: 100%;
    }

    table.dragSortList.-isExpanded {
      padding: 15px;
      background-color: #f6f6f6;
    }

    table.dragSortList.-isExpanded.-isDraggingOver {
      background-color: #eee;
    }

    table.dragSortList.-isExpanded.-isDraggingOver:before {
      content: none;
    }

    tr.dragSortItem.-placeholderAbove:before,
    tr.dragSortItem.-placeholderBelow:before {
      content: none;
    }

    tr.dragSortItem.-placeholderAbove td {
      padding-top: 25px;
    }

    tr.dragSortItem.-placeholderBelow td {
      padding-bottom: 25px;
    }

    table .the-item {
      margin: 0;
    }
</code>```

If this approach does not suit you, unfortunately, this addon currently cannot offer anything else. You'll have to either revert to divs or use another drag-sorting addon.

Body:
ember-drag-sort uses a simple CSS technique to render the placeholder: :before and :after pseudoelements.

Unfortunately, this doesn't work with HTML tables because table semantics are very restrictive. To work around this problem, top/bottom padding on table cells can be used instead of selectors.

This is not a great solution because padding appears inside table cells. If you want your cells to have borders, you'll have to apply them to inner elements instead.

Tables are now part of the demo, please have a look.

Here are the CSS overrides used in the demo:

    table {
      width: 100%;
    }

    table.dragSortList.-isExpanded {
      padding: 15px;
      background-color: #f6f6f6;
    }

    table.dragSortList.-isExpanded.-isDraggingOver {
      background-color: #eee;
    }

    table.dragSortList.-isExpanded.-isDraggingOver:before {
      content: none;
    }

    tr.dragSortItem.-placeholderAbove:before,
    tr.dragSortItem.-placeholderBelow:before {
      content: none;
    }

    tr.dragSortItem.-placeholderAbove td {
      padding-top: 25px;
    }

    tr.dragSortItem.-placeholderBelow td {
      padding-bottom: 25px;
    }

    table .the-item {
      margin: 0;
    }

If this approach does not suit you, unfortunately, this addon currently cannot offer anything else. You'll have to either revert to divs or use another drag-sorting addon.


问:
Confusion about realloc function
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

```<code>int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

```<code>int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}
</code>```

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?

答:
The only authorative reference is the standard document. n1570 (the latest C11 standard) has the following to say:

§7.22.3.5 The realloc function, p3:

If ptr is a null pointer, the realloc function behaves like the malloc function for the
  specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory
  management function, or if the space has been deallocated by a call to the free or
  realloc function, the behavior is undefined.  [...]

So, your second example is well-defined.

Title: Confusion about realloc function

Body:
I read about dynamic memory allocation in C using this reference.

That document Say's :

realloc() should only be used for dynamically allocated memory. If the
  memory is not dynamically allocated, then behavior is undefined.

If we use realloc() something like this:

int main()
{
    int *ptr;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

According to that reference, this program is undefined because pointer ptr not allocated dynamically.

But, If I use something like:

int main()
{
    int *ptr = NULL;
    int *ptr_new = (int *)realloc(ptr, sizeof(int));

    return 0;
}

Is it also undefined behavior according to that reference?

I thing second case does not invoked undefined behaviour. Am I right?


问:
Query parameters for root component in Angular IO
I have a very simple Angular 4+ application that fetches data from API and displays the data. I believe this should be possible by using just the root component:{path: 'main', component: MainComponent}
and QueryParams like ?id=1.

I am able to fetch the query param, but for some reason my router repeats the route+params part of the URL after the already existing route+params part. For example my local address malforms from localhost:4200/main?id=1 into localhost:4200/main?id=1/main?id=1.

The ActivatedRoute does pick the correct query parameter from the URL but I would like to keep the URL as sanitized as possible. How do I prevent this duplication from happening? I have set <base href='/'> as per routing requirements in my index.html.

Module:

```<code>@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    RouterModule.forRoot(
      [
        { path: 'main', component: MainComponent},
      ]),
    CommonModule,
    HttpModule,
    FormsModule,
    NgbModule.forRoot()
  ],
  declarations: [MainComponent],
  providers: [
    {provide: APP_BASE_HREF, useValue: window.document.location.href},
    DataService,
    WindowService,
    HttpUtil
  ],
  bootstrap: [MainComponent]
})
export class MainModule{}
</code>```

Component:

```<code>@Component({
  selector: 'main-component',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  constructor(private dataService: DataService,
              private activatedRoute: ActivatedRoute) {
  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      if (!(Object.keys(params).length === 0 && params.constructor === Object)) {
        console.log(params);
      }
    });
  }
}
</code>```

答:
This is caused by your APP_BASE_HREF

```<code>{provide: APP_BASE_HREF, useValue: window.document.location.href}
</code>```

You are telling the app to use window.document.location.href main?id=1 as your basehref. Angular then appends its own routes to the end of the basehref. This is why you are getting the duplication

```<code> localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE)
</code>```

Here are the docs on the functionality of APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)

Body:
I have a very simple Angular 4+ application that fetches data from API and displays the data. I believe this should be possible by using just the root component:{path: 'main', component: MainComponent}
and QueryParams like ?id=1.

I am able to fetch the query param, but for some reason my router repeats the route+params part of the URL after the already existing route+params part. For example my local address malforms from localhost:4200/main?id=1 into localhost:4200/main?id=1/main?id=1.

The ActivatedRoute does pick the correct query parameter from the URL but I would like to keep the URL as sanitized as possible. How do I prevent this duplication from happening? I have set <base href='/'> as per routing requirements in my index.html.

Module:

@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    RouterModule.forRoot(
      [
        { path: 'main', component: MainComponent},
      ]),
    CommonModule,
    HttpModule,
    FormsModule,
    NgbModule.forRoot()
  ],
  declarations: [MainComponent],
  providers: [
    {provide: APP_BASE_HREF, useValue: window.document.location.href},
    DataService,
    WindowService,
    HttpUtil
  ],
  bootstrap: [MainComponent]
})
export class MainModule{}

Component:

@Component({
  selector: 'main-component',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  constructor(private dataService: DataService,
              private activatedRoute: ActivatedRoute) {
  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      if (!(Object.keys(params).length === 0 && params.constructor === Object)) {
        console.log(params);
      }
    });
  }
}

Body:
This is caused by your APP_BASE_HREF

{provide: APP_BASE_HREF, useValue: window.document.location.href}

You are telling the app to use window.document.location.href main?id=1 as your basehref. Angular then appends its own routes to the end of the basehref. This is why you are getting the duplication

 localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE)

Here are the docs on the functionality of APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)


问:
Moving applications between desktops in Windows
I am trying to figure out how can I send a running application do a new Windows desktop created with CreateDesktop.

I can create a new Desktop, and then launch an application in it, bug I can't find the way to do it with a running application. All functions related to Desktop management (i.ec, SetThreadDesktop) always apply only to current thread

Any hints ?

Thank you for your answer.

Well, in fact, what I need to do is moving applications not developed by me (i.e, notepad.exe)

If look at Virtual Desktop Manager from Powertoys (http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx), it creates several virtual desktops in the same WindowStation.
I know there are similar applications that can move running apps (notepad.exe, calc.exe..) from one virtual desktop to another, without the need of closing it and reopening it again (and then passing the new desktop handle [HDESK] on the call to CreateProcess), but even after reading all the related msdn documentation, I still can not figure how to do it :|

I thought on SetProcessWindowStation too, but as far as I now, all new virtual desktops created with CreateDesktop function are on the same WindowStation, so...

Maybe I missed something ?

答:
I have not implemented any code, but just thinking aloud...
Quoting from the following MSDN Link

A process automatically establishes a connection to a window station and desktop when it first calls a USER32 or GDI32 function.
  If the process did not call SetProcessWindowStation, it connects to the window station inherited from the parent process

This implies that the 'running application' already has the value of "lpDesktop member of the STARTUPINFO structure" set to the current window station. I think you may need to change this value to send the application to another desktop.
As this link mentions SetProcessWindowStation Function, this could be done using

BOOL WINAPI SetProcessWindowStation(
    __in  HWINSTA hWinSta
  );

Also, as SetThreadDesktop Function mentions

Assigns the specified desktop to the calling thread.

So I guess, for this to work, you 'running application' will need to call SetThreadDesktop.
It will be helpful if you could post in some code...

OwnerDisplayName: Codex

ContentLicense: CC BY-SA 2.5


问:
Tips and tricks to increase productivity / efficiency with Team Foundation Server
I have to use Team Foundation Server 2010 at my company and I'm not very happy with it.
There are so many features or just default behavior I'd expect from a CVS that TFS seems to lack (compared to svn, git or perforce, which I have experience with), so my question is: which tricks do you know, which hidden features are out there to make TFS easier to use / more convenient?

Perhaps I should elaborate a bit and list what I think could be better:

The default check-in action when associated with a task is "resolve", though in 99% of all check-ins, I only want to "associate" my commit with the task. There's only 1 commit (the last) that "resolves" the task, so why is that the default? Can I change that?

In the check-in dialog, when double-clicking a file, Notepad is launched and shows the contents of the file. Notepad. Seriously? What about the Visual Studio editor? Anyway, I'd like to see the differences to review the changes I've made, not the contents of the file. The diff tool is hidden in a submenu. This might seem trivial, but when I have to check 10+ files it's just annoying to always right-click, open submenu, click to diff.

The diff tool. Merging with it isn't really straightforward, also the conflict detection mechanism is somewhat lacking. The (Tortoise-)SVN / Git merge tools or that of Perforce are way better here.

Speed. Creating a new file, opening a file for the first time, comparing a file with a previous version etc takes forever (that is, 3-10+ seconds). Our TFS server is in-house and has absolutely no load - also why does Visual Studio have to contact the TFS server when I just create a new file (which I might not even check in)? Is there perhaps an option to turn that off?

Readonly files. All files are read-only when checked-in and become writeable when edited for the first time. This is really annyoing when the application crashes because of that. Windows Azure for example modifies a web.config file and fails whenever I check out because the file is read-only then.

These are just the most prominent things that I think are really annoying and unnecessary.
I didn't have the pleasure to branch and merge yet, but from what I've heard so far it won't be very enjoyable as well...

So again: If you know some tricks, settings, featuers that make working with TFS less inconvenient, please share them.

答:
1, Bash head against wall

2, Say outloud - it's better than SourceSafe

3, Repeat

4, Install git, or mercurial, or just about anything else.


问:
ReactiveUI - The type 'IScheduler' is defined in an assembly that is not referenced
I'm trying to subclass ReactiveList so it responds to changes in a ReactiveDictionary I have written, rather than a parent List.

This is the class and constructor signature for the ReactiveList subclass.

```<code>public class ReactiveDictionaryDerivedList<TKey, TValue, TDerived> : ReactiveList<TDerived>, IReactiveDerivedList<TDerived>
{
    public ReactiveDictionaryDerivedList(
        IReadOnlyReactiveDictionary<TKey, TValue> dict,
        Func<TValue, TDerived> selector,
        Func<TValue, TDerived, bool> derivedValueFinder,
        IScheduler scheduler)
    {
    }
</code>```

Here are the dependencies I have in the project. Notice that I'm using the 4.0.0 preview release of System.Reactive, since this is installed by the ReactiveUI 8.0.0 alpha. (I'm using the ReactiveUI alpha as this seems to be what is recommended these days)

```<code><packages>
  <package id="ReactiveUI" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="ReactiveUI.WPF" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="Splat" version="2.0.0" targetFramework="net452" />
  <package id="System.Reactive" version="4.0.0-preview00001" targetFramework="net452" />
</packages>
</code>```

The problem is that the class doesn't compile because of the error:

```<code>error CS0012: The type 'IScheduler' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Reactive.Interfaces, Version=3.0.1000.0,
Culture=neutral, PublicKeyToken=94bc3704cddfc263'.
</code>```

Any ideas how to resolve would be appreciated. Advice on the recommended versions for ReactiveUI and System.Reactive would also be nice.

答:
Unfortunately something fishy is going on with dependencies at the moment. But for the current 8.0 version it's recommended to install System.Reactive 3.1. That's the only version 8.0 is tested against.

If you start using PackageReference for your projects, you won't need to define the System.Reactive dependency yourself, but it's picked up by the package manager. But that might not work (yet?) with WPF.

See: https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files

Body:
I'm trying to subclass ReactiveList so it responds to changes in a ReactiveDictionary I have written, rather than a parent List.

This is the class and constructor signature for the ReactiveList subclass.

public class ReactiveDictionaryDerivedList<TKey, TValue, TDerived> : ReactiveList<TDerived>, IReactiveDerivedList<TDerived>
{
    public ReactiveDictionaryDerivedList(
        IReadOnlyReactiveDictionary<TKey, TValue> dict,
        Func<TValue, TDerived> selector,
        Func<TValue, TDerived, bool> derivedValueFinder,
        IScheduler scheduler)
    {
    }

Here are the dependencies I have in the project. Notice that I'm using the 4.0.0 preview release of System.Reactive, since this is installed by the ReactiveUI 8.0.0 alpha. (I'm using the ReactiveUI alpha as this seems to be what is recommended these days)

<packages>
  <package id="ReactiveUI" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="ReactiveUI.WPF" version="8.0.0-alpha0113" targetFramework="net452" />
  <package id="Splat" version="2.0.0" targetFramework="net452" />
  <package id="System.Reactive" version="4.0.0-preview00001" targetFramework="net452" />
</packages>

The problem is that the class doesn't compile because of the error:

error CS0012: The type 'IScheduler' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Reactive.Interfaces, Version=3.0.1000.0,
Culture=neutral, PublicKeyToken=94bc3704cddfc263'.

Any ideas how to resolve would be appreciated. Advice on the recommended versions for ReactiveUI and System.Reactive would also be nice.


问:
Unmelt Pandas DataFrame
I have a pandas dataframe with two id variables:

```<code>df = pd.DataFrame({'id': [1,1,1,2,2,3],
               'num': [10,10,12,13,14,15],
               'q': ['a', 'b', 'd', 'a', 'b', 'z'],
               'v': [2,4,6,8,10,12]})

   id  num  q   v
0   1   10  a   2
1   1   10  b   4
2   1   12  d   6
3   2   13  a   8
4   2   14  b  10
5   3   15  z  12
</code>```

I can pivot the table with:

```<code>df.pivot('id','q','v')
</code>```

And end up with something close:

```<code>q    a   b   d   z
id
1    2   4   6 NaN
2    8  10 NaN NaN
3  NaN NaN NaN  12
</code>```

However, what I really want is (the original unmelted form):

```<code>id   num   a   b   d   z
1    10   2   4 NaN NaN
1    12 NaN NaN   6 NaN
2    13   8 NaN NaN NaN
2    14 NaN  10 NaN NaN
3    15 NaN NaN NaN  12
</code>```

In other words:

'id' and 'num' my indices (normally, I've only seen either 'id' or 'num' being the index but I need both since I'm trying to retrieve the original unmelted form)

'q' are my columns

'v' are my values in the table

Update

I found a close solution from Wes McKinney's blog:

```<code>df.pivot_table(index=['id','num'], columns='q')

         v
q        a   b   d   z
id num
1  10    2   4 NaN NaN
   12  NaN NaN   6 NaN
2  13    8 NaN NaN NaN
   14  NaN  10 NaN NaN
3  15  NaN NaN NaN  12
</code>```

However, the format is not quite the same as what I want above.

答:
you can remove name q.

```<code>df1.columns=df1.columns.tolist()
</code>```

Zero's answer + remove q =

```<code>df1 = df.set_index(['id', 'num', 'q'])['v'].unstack().reset_index()
df1.columns=df1.columns.tolist()

   id  num    a     b    d     z
0   1   10  2.0   4.0  NaN   NaN
1   1   12  NaN   NaN  6.0   NaN
2   2   13  8.0   NaN  NaN   NaN
3   2   14  NaN  10.0  NaN   NaN
4   3   15  NaN   NaN  NaN  12.0
</code>```

Title: Unmelt Pandas DataFrame

Body:
I have a pandas dataframe with two id variables:

df = pd.DataFrame({'id': [1,1,1,2,2,3],
               'num': [10,10,12,13,14,15],
               'q': ['a', 'b', 'd', 'a', 'b', 'z'],
               'v': [2,4,6,8,10,12]})

   id  num  q   v
0   1   10  a   2
1   1   10  b   4
2   1   12  d   6
3   2   13  a   8
4   2   14  b  10
5   3   15  z  12

I can pivot the table with:

df.pivot('id','q','v')

And end up with something close:

q    a   b   d   z
id
1    2   4   6 NaN
2    8  10 NaN NaN
3  NaN NaN NaN  12

However, what I really want is (the original unmelted form):

id   num   a   b   d   z
1    10   2   4 NaN NaN
1    12 NaN NaN   6 NaN
2    13   8 NaN NaN NaN
2    14 NaN  10 NaN NaN
3    15 NaN NaN NaN  12

In other words:

'id' and 'num' my indices (normally, I've only seen either 'id' or 'num' being the index but I need both since I'm trying to retrieve the original unmelted form)

'q' are my columns

'v' are my values in the table

Update

I found a close solution from Wes McKinney's blog:

df.pivot_table(index=['id','num'], columns='q')

         v
q        a   b   d   z
id num
1  10    2   4 NaN NaN
   12  NaN NaN   6 NaN
2  13    8 NaN NaN NaN
   14  NaN  10 NaN NaN
3  15  NaN NaN NaN  12

However, the format is not quite the same as what I want above.

Body:
you can remove name q.

df1.columns=df1.columns.tolist()

Zero's answer + remove q =

df1 = df.set_index(['id', 'num', 'q'])['v'].unstack().reset_index()
df1.columns=df1.columns.tolist()

   id  num    a     b    d     z
0   1   10  2.0   4.0  NaN   NaN
1   1   12  NaN   NaN  6.0   NaN
2   2   13  8.0   NaN  NaN   NaN
3   2   14  NaN  10.0  NaN   NaN
4   3   15  NaN   NaN  NaN  12.0


问:
NIghtwatch: I need to search for a word in a table without using document
I'm a beginner in using Nightwatch and I'm stuck with the following:

I've got a table that has a
 and multiple
s in it. I need to check if a specific word is in one of the cells in the first column.

First, I tried getting the whole table using document.GetElements... but it appears this is not supported by Nightwatch. Currently, I'm looking for a solution without using Nightwatch custom command.

P.S. I can't create tags yet, so it'd be awesome if someone could create one, like table-to-array or something like that.

答:
You can execute javascript code into the browser using execute command (Documentation here). So you can do something like this:

```<code>client.execute(function(){
    /*your js to get the DOM element and check if the element has the text you want*/
    return true //or false if didnt find it
},[],function(response){
    console.log(response.value)//this will contain your returned value
    client.assert.equal(response.value, true, "Text not found on table")
})
</code>```

Body:
You can execute javascript code into the browser using execute command (Documentation here). So you can do something like this:

client.execute(function(){
    /*your js to get the DOM element and check if the element has the text you want*/
    return true //or false if didnt find it
},[],function(response){
    console.log(response.value)//this will contain your returned value
    client.assert.equal(response.value, true, "Text not found on table")
})


问:
Spring Data JPA (Hibernate) is not creating column as autoincrement
Why is this mapping unable to create the column id as autoincrement?

```<code>@Entity(name = "user_role")
public class UserRole {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, unique = true)
    private Long id;

    @OneToOne(cascade = CascadeType.MERGE, targetEntity = Role.class)
    @JoinColumn(name = "role_id")
    private Role role;

    @OneToOne(cascade = CascadeType.MERGE, targetEntity = User.class)
    @JoinColumn(name = "user_id")
    private User user;
}
</code>```

Thanks in advance!

答:
Well, just to help people.

The problem was the name of my entity "user_role", I don't know why but after changing the entity name to "userrole" everything worked and the id column was created as AUTOINCREMENT.

Hope this helps!

Body:
Why is this mapping unable to create the column id as autoincrement?

@Entity(name = "user_role")
public class UserRole {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, unique = true)
    private Long id;

    @OneToOne(cascade = CascadeType.MERGE, targetEntity = Role.class)
    @JoinColumn(name = "role_id")
    private Role role;

    @OneToOne(cascade = CascadeType.MERGE, targetEntity = User.class)
    @JoinColumn(name = "user_id")
    private User user;
}

Thanks in advance!


问:
Hand over variable from a function inside node.js + twit package
I am using the package twitinsite a node.js app to get some JSON data from Twitter.

I tried for hours to manage how I can hand over a variable from inside a function to the outside.

```<code>var tweets;
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  tweets = data;
})
console.log(tweets); // -> undefiend

//data is the JSON I get from the Twitter Server. Console.log(data) shows it.
</code>```

I know its because of the asynchronous thing, but I dont know how to manage this.

I hope you can help me

答:
Probably the easiest way to tackle your issue is to use Promises with Twit's promised package (https://www.npmjs.com/package/promised-twit)

In your code it would look something like this:

```<code>var Twit = require('promised-twit');

var T = new Twit({
  consumer_key: '...',
  consumer_secret: '...',
  access_token: '...',
  access_token_secret: '...'
})

T.getFollowersIds({ screen_name: 'tolga_tezel' })
  .then(function(data) {
    console.log(data);
  });
})
</code>```

Of course first install the package by running npm install --save promised-twit

The reason your current code doesn't return anything when you log it out because console.log runs before the twitter API returns any response from T.get()

Body:
I am using the package twitinsite a node.js app to get some JSON data from Twitter.

I tried for hours to manage how I can hand over a variable from inside a function to the outside.

var tweets;
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  tweets = data;
})
console.log(tweets); // -> undefiend

//data is the JSON I get from the Twitter Server. Console.log(data) shows it.

I know its because of the asynchronous thing, but I dont know how to manage this.

I hope you can help me

Body:
Probably the easiest way to tackle your issue is to use Promises with Twit's promised package (https://www.npmjs.com/package/promised-twit)

In your code it would look something like this:

var Twit = require('promised-twit');

var T = new Twit({
  consumer_key: '...',
  consumer_secret: '...',
  access_token: '...',
  access_token_secret: '...'
})

T.getFollowersIds({ screen_name: 'tolga_tezel' })
  .then(function(data) {
    console.log(data);
  });
})

Of course first install the package by running npm install --save promised-twit

The reason your current code doesn't return anything when you log it out because console.log runs before the twitter API returns any response from T.get()


问:
How do I write an object to a file and read it back?
I will need your help because I want to write an object in a file and read it back.

I have a problem with this line of code: Vehicule result = (Vehicule) read.readObject ();

```<code>try {
       List<Vehicule> voiture = new ArrayList<Vehicule>();

       //Write object to file
       FileOutputStream fos = new FileOutputStream("Garage.ser");
       ObjectOutputStream ecriture = new ObjectOutputStream(fos);
       System.out.println("\nIci - Ecriture de mon fichier\n");
       ecriture.writeObject(voiture);
       ecriture.close();
       //read object from file
       FileInputStream fis = new FileInputStream("Garage.ser");
       ObjectInputStream lecture = new ObjectInputStream(fis);
        System.out.println("\nIci - Lecture du fichier\n");
        Vehicule result = (Vehicule) lecture.readObject();
        lecture.close();

   }catch (FileNotFoundException e){
       System.out.println("Aucune voitures sauvegardé !");
   }catch (IOException e) {
       e.printStackTrace();
   }catch (ClassNotFoundException e) {
       e.printStackTrace();
   }
</code>```

Thank you for your help.

答: It seems you're writing a List<Vehicule> but read a Vehicule.

Body:
I will need your help because I want to write an object in a file and read it back.

I have a problem with this line of code: Vehicule result = (Vehicule) read.readObject ();

try {
       List<Vehicule> voiture = new ArrayList<Vehicule>();

       //Write object to file
       FileOutputStream fos = new FileOutputStream("Garage.ser");
       ObjectOutputStream ecriture = new ObjectOutputStream(fos);
       System.out.println("\nIci - Ecriture de mon fichier\n");
       ecriture.writeObject(voiture);
       ecriture.close();
       //read object from file
       FileInputStream fis = new FileInputStream("Garage.ser");
       ObjectInputStream lecture = new ObjectInputStream(fis);
        System.out.println("\nIci - Lecture du fichier\n");
        Vehicule result = (Vehicule) lecture.readObject();
        lecture.close();

   }catch (FileNotFoundException e){
       System.out.println("Aucune voitures sauvegardé !");
   }catch (IOException e) {
       e.printStackTrace();
   }catch (ClassNotFoundException e) {
       e.printStackTrace();
   }

Thank you for your help.


问:
Loading XML into a browser with jQuery
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?</p>

```<code>function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('<li class="w">'+$(this).text()+'</li>');
                            }
                        });
                    });
        }
    });
}
</code>```

答: My guess is because you have ActiveX installed in IE on the server and not on firefox and vice versa on your machine.  Though it's difficult to say from just the code.  At what line does the code fail both on the server and on the client machine?</p>

Title: Loading XML into a browser with jQuery

Body:
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?

function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('
'+$(this).text()+'
');
                            }
                        });
                    });
        }
    });
}


问:
Maximum sum of non consecutive elements
Given an array of positive integers, what's the most efficient algorithm to find non-consecutive elements from this array which, when added together, produce the maximum sum?</p>

答:
```<code>int nonContigousSum(vector<int> a, int n) {
    if (n < 0) {
        return 0;
    }
    return std::max(nonContigousSum(a, n - 1), nonContigousSum(a, n - 2) + a[n]);
}
</code>```

this is the recursive approach with the help of which we can solve this question
(OPTIMAL SUB-STRUCTURE HALLMARK OF DYNAMIC PROGRAMMING.
Here we are considering two cases, in first we exclude a[n] and in the second we include a[n] and return the max of those sub cases found.
We are basically finding all the subsets of the array and returning the length of the non-contiguous array with max sum.
Use tabulation or memoization for avoiding same sub-problems.

Title: Maximum sum of non consecutive elements

Body:
int nonContigousSum(vector<int> a, int n) {
    if (n < 0) {
        return 0;
    }
    return std::max(nonContigousSum(a, n - 1), nonContigousSum(a, n - 2) + a[n]);
}

this is the recursive approach with the help of which we can solve this question
(OPTIMAL SUB-STRUCTURE HALLMARK OF DYNAMIC PROGRAMMING.
Here we are considering two cases, in first we exclude a[n] and in the second we include a[n] and return the max of those sub cases found.
We are basically finding all the subsets of the array and returning the length of the non-contiguous array with max sum.
Use tabulation or memoization for avoiding same sub-problems.


问:
Parsing XML - string captured is front truncated. Swift
My parsing of xml documents works well, but what I have noticed is that randomly the text in between certain tags ("AbstractText") becomes truncated and I have no idea what.  Again, this appears only here and there and is not always the case for this tag.  My code for the parsing is below and also an example of a truncated text.

```<code> var abstractBool = false
 var abstract = ""

 func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
       if abstractBool{
          abstract = string
       }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
      switch elementName {
           case "AbstractText":
           abstractBool = false
      }
 }
</code>```

Raw XML from remote server:

```<code> <Abstract>
 <AbstractText>
 Protein kinase C (PKC) has been shown to activate the mammalian target of
 rapamycin complex 1 (mTORC1) signaling pathway, a central hub in the
 regulation of cell metabolism, growth and proliferation. However, the
 mechanisms by which PKCs activate mTORC1 are still ambiguous. Our previous
 study revealed that activation of classical PKCs (cPKC) results in the
 perinuclear accumulation of cPKC and phospholipase D2 (PLD2) in recycling
 endosomes in a PLD2-dependent manner. Here, we report that mTORC1 activation
 by phorbol 12,13-myristate acetate (PMA) requires both classic, cPKC, and
 novel PKC (nPKC) isoforms, specifically PKCη, acting through distinct
 pathways. The translocation of mTOR to perinuclear lysosomes was detected
 after treatment of PKC activators, which was not colocalized with PKCα- or
 RAB11-positive endosomes and was not inhibited by PLD inhibitors. We found
 that PKCη inhibition by siRNA or bisindolylmaleimide I effectively decreased
 mTOR accumulation in lysosomes and its activity. Also, we identified that
 PKCη plays a role upstream of the v-ATPase/Ragulator/Rag pathway in response
 to PMA. These data provides a spatial aspect to the regulation of mTORC1 by
 sustained activation of PKC, requiring co-ordinated activation of two
 distinct elements, the perinuclear accumulation of cPKC- and PLD-containing
 endosomes and the nPKC-dependent translation of of mTOR in the perinuclear
 lysosomes. The close proximity of these two distinct compartments shown in
 this study suggests the possibility that transcompartment signaling may be a
 factor in the regulation of mTORC1 activity and also underscores the
 importance of PKCη as a potential therapeutic target of mTORC-related
 disorders.
 </AbstractText>
 </Abstract>
</code>```

What i am able to extract is the following front-end-truncated portion of the string:

```<code> scompartment signaling may be a factor in the regulation of mTORC1 activity
 and also underscores the importance of PKCη as a potential therapeutic target
 of mTORC-related disorders.
</code>```

答:
That's the normal behavior. You are given partial strings, and you have to concatenate them and the final result is given by the concatenation of all the strings obtained in the lapse between didStartElement and didEndElement are called. Be sure to save the current element in a variable so in foundCharacters you know where the partial string belongs to.

```<code>var abstractBool = false
var abstract = ""

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
             abstract = "" // if you read an XML document with multiple
                           // AbstractText elements, you need to reset
                           // the variable
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
     if abstractBool{
        abstract.append(string)
     }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
     switch elementName {
         case "AbstractText":
         abstractBool = false
         // Here the variable 'abstract' contains the full text
     }
 }
</code>```

Body:
My parsing of xml documents works well, but what I have noticed is that randomly the text in between certain tags ("AbstractText") becomes truncated and I have no idea what.  Again, this appears only here and there and is not always the case for this tag.  My code for the parsing is below and also an example of a truncated text.

 var abstractBool = false
 var abstract = ""

 func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
       if abstractBool{
          abstract = string
       }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
      switch elementName {
           case "AbstractText":
           abstractBool = false
      }
 }

Raw XML from remote server:

 <Abstract>
 <AbstractText>
 Protein kinase C (PKC) has been shown to activate the mammalian target of
 rapamycin complex 1 (mTORC1) signaling pathway, a central hub in the
 regulation of cell metabolism, growth and proliferation. However, the
 mechanisms by which PKCs activate mTORC1 are still ambiguous. Our previous
 study revealed that activation of classical PKCs (cPKC) results in the
 perinuclear accumulation of cPKC and phospholipase D2 (PLD2) in recycling
 endosomes in a PLD2-dependent manner. Here, we report that mTORC1 activation
 by phorbol 12,13-myristate acetate (PMA) requires both classic, cPKC, and
 novel PKC (nPKC) isoforms, specifically PKCη, acting through distinct
 pathways. The translocation of mTOR to perinuclear lysosomes was detected
 after treatment of PKC activators, which was not colocalized with PKCα- or
 RAB11-positive endosomes and was not inhibited by PLD inhibitors. We found
 that PKCη inhibition by siRNA or bisindolylmaleimide I effectively decreased
 mTOR accumulation in lysosomes and its activity. Also, we identified that
 PKCη plays a role upstream of the v-ATPase/Ragulator/Rag pathway in response
 to PMA. These data provides a spatial aspect to the regulation of mTORC1 by
 sustained activation of PKC, requiring co-ordinated activation of two
 distinct elements, the perinuclear accumulation of cPKC- and PLD-containing
 endosomes and the nPKC-dependent translation of of mTOR in the perinuclear
 lysosomes. The close proximity of these two distinct compartments shown in
 this study suggests the possibility that transcompartment signaling may be a
 factor in the regulation of mTORC1 activity and also underscores the
 importance of PKCη as a potential therapeutic target of mTORC-related
 disorders.
 </AbstractText>
 </Abstract>

What i am able to extract is the following front-end-truncated portion of the string:

 scompartment signaling may be a factor in the regulation of mTORC1 activity
 and also underscores the importance of PKCη as a potential therapeutic target
 of mTORC-related disorders.

Body:
That's the normal behavior. You are given partial strings, and you have to concatenate them and the final result is given by the concatenation of all the strings obtained in the lapse between didStartElement and didEndElement are called. Be sure to save the current element in a variable so in foundCharacters you know where the partial string belongs to.

var abstractBool = false
var abstract = ""

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
      switch elementName {
       case "AbstractText":
             abstractBool = true
             abstract = "" // if you read an XML document with multiple
                           // AbstractText elements, you need to reset
                           // the variable
      }
}

 func parser(_ parser: XMLParser, foundCharacters string: String) {
     if abstractBool{
        abstract.append(string)
     }
 }

 func parser(_ parser: XMLParser, didEndElement elementName: String,
 namespaceURI: String?, qualifiedName qName: String?) {
     switch elementName {
         case "AbstractText":
         abstractBool = false
         // Here the variable 'abstract' contains the full text
     }
 }


问:
What happens if a library I use in my project is discontinued, will my app crash?
I currently use a number of different gradle libraries in my android project, but what if in the future one of these library is discontinued?

How to plan for these kind of situations?

答:
No.  Your app actually contains every library you use, compiled into the APK.  Gradle downloads them at compile time.  As long as they don't require a server component, an installed version will last forever.  (If it requires a server, and they stop running the server, then of course it won't work).

Now if they were to go and scrub all versions of their artifacts from whatever repository you use, and you didn't have a local copy, then you wouldn't be able to compile a new version.  That would be extremely rare.  You can protect against that by keeping a copy of the libraries checked into source control with your app.