问:
I am not able to do any operation when clicked on any item in my listview
This is my main file . Here I am setting a onClickListener on Listview, which results in any operation
public class Attendance extends AppCompatActivity {

```<code>private ArrayList<attendance_pojo> arrayList = new ArrayList<>();
private Attendance_adaptwr adapter;
private  int present,absent,datecntr,presents,absents;
private  String year,month,date;
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance);
    init();
    fetchData();
    adapter = new Attendance_adaptwr(this, R.layout.card_attendance, arrayList);
    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(Attendance.this, "Hello from ROy "+position, Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

And Arrayadapter file is here

```<code>public class Attendance_adaptwr  extends ArrayAdapter{

    private Context context;
    private int layres;
    private ArrayList<attendance_pojo> arrayList;
    private LayoutInflater inflater;

    public Attendance_adaptwr(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<attendance_pojo> objects) {
        super(context, resource, objects);
        this.context = context;
        this.layres = resource;

        this.arrayList = objects;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = inflater.inflate(layres, null);
        TextView month, workdays;
        Button present,absent;
        month= view.findViewById(R.id.tv_month);
        workdays= view.findViewById(R.id.work_Days);
        present = view.findViewById(R.id.tv_present);
        absent= view.findViewById(R.id.tv_absent);

        attendance_pojo pojo= arrayList.get(position);
        String months= pojo.getMonth();
        Log.d("months",months);
        months= checkmonth(months);
        Log.d("datess",""+pojo.getDate());
        month.setText(months+" "+pojo.getYear());
        workdays.setText(""+pojo.getDatecounter());
        present.setText("Present "+pojo.getPresent());
        absent.setText("Absent "+pojo.getAbsent());
        return  view;
    }

    private String checkmonth(String month) {
        String monthString;
        switch (month) {
            case "1":  monthString = "January";       break;
            case "2":  monthString = "February";      break;
            case "3":  monthString = "March";         break;
            case "4":  monthString = "April";         break;
            case "5":  monthString = "May";           break;
            case "6":  monthString = "June";          break;
            case "7":  monthString = "July";          break;
            case "8":  monthString = "August";        break;
            case "9":  monthString = "September";     break;
            case "10": monthString = "October";       break;
            case "11": monthString = "November";      break;
            case "12": monthString = "December";      break;
            default: monthString = "Invalid month"; break;
        }
        return  monthString;

    }

    }
</code>```

I just cant get any toast when clicked and any Intent is also not fired. I want to make sure that, it should return me position also.

Here is my Layout Code which I have inflated

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="wrap_content"

    android:layout_margin="10dp">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_marginBottom="15dp"
        android:background="#000"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#9714b3cf"
            android:orientation="vertical">
        <TextView
            android:id="@+id/tv_month"
            android:background="#b51992b7"
            android:text="January 2017"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:layout_marginTop="40dp"
            android:layout_height="wrap_content"
            android:text="WORK DAYS"
            android:gravity="center"
            android:textSize="25sp"
            />
        <TextView
            android:id="@+id/work_Days"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:text="18"
            android:gravity="center"
            android:textSize="45sp"

            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2">
            <Button
                android:id="@+id/tv_present"
                android:layout_width="wrap_content"
                android:background="#d3edfd07"
                android:text="PRESENT 18"
                android:textSize="12sp"
                android:layout_marginEnd="5dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/tv_absent"
                android:text="ABSENT 0"
                android:background="#90e775d2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

答:
Because you are using buttons in list item, that's why OnItemClick not working

you need to do 2 steps in your listview_item.xml

set the root layout with: android:descendantFocusability="blocksDescendants"

set any focusable or clickable view in this item with:

android:clickable="false"

android:focusable="false"

android:focusableInTouchMode="false"

try to add this three line in your button

```<code><Button
    android:id="@+id/button1"
    android:layout_width=""
    android:layout_height=""
   //...........Add this three line in your every button................
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    />
</code>```

Body:
This is my main file . Here I am setting a onClickListener on Listview, which results in any operation
public class Attendance extends AppCompatActivity {

private ArrayList<attendance_pojo> arrayList = new ArrayList<>();
private Attendance_adaptwr adapter;
private  int present,absent,datecntr,presents,absents;
private  String year,month,date;
ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance);
    init();
    fetchData();
    adapter = new Attendance_adaptwr(this, R.layout.card_attendance, arrayList);
    listview.setAdapter(adapter);
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(Attendance.this, "Hello from ROy "+position, Toast.LENGTH_SHORT).show();
        }
    });

}

And Arrayadapter file is here

public class Attendance_adaptwr  extends ArrayAdapter{

    private Context context;
    private int layres;
    private ArrayList<attendance_pojo> arrayList;
    private LayoutInflater inflater;

    public Attendance_adaptwr(@NonNull Context context, @LayoutRes int resource, @NonNull ArrayList<attendance_pojo> objects) {
        super(context, resource, objects);
        this.context = context;
        this.layres = resource;

        this.arrayList = objects;

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view = inflater.inflate(layres, null);
        TextView month, workdays;
        Button present,absent;
        month= view.findViewById(R.id.tv_month);
        workdays= view.findViewById(R.id.work_Days);
        present = view.findViewById(R.id.tv_present);
        absent= view.findViewById(R.id.tv_absent);

        attendance_pojo pojo= arrayList.get(position);
        String months= pojo.getMonth();
        Log.d("months",months);
        months= checkmonth(months);
        Log.d("datess",""+pojo.getDate());
        month.setText(months+" "+pojo.getYear());
        workdays.setText(""+pojo.getDatecounter());
        present.setText("Present "+pojo.getPresent());
        absent.setText("Absent "+pojo.getAbsent());
        return  view;
    }

    private String checkmonth(String month) {
        String monthString;
        switch (month) {
            case "1":  monthString = "January";       break;
            case "2":  monthString = "February";      break;
            case "3":  monthString = "March";         break;
            case "4":  monthString = "April";         break;
            case "5":  monthString = "May";           break;
            case "6":  monthString = "June";          break;
            case "7":  monthString = "July";          break;
            case "8":  monthString = "August";        break;
            case "9":  monthString = "September";     break;
            case "10": monthString = "October";       break;
            case "11": monthString = "November";      break;
            case "12": monthString = "December";      break;
            default: monthString = "Invalid month"; break;
        }
        return  monthString;

    }

    }

I just cant get any toast when clicked and any Intent is also not fired. I want to make sure that, it should return me position also.

Here is my Layout Code which I have inflated

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="wrap_content"

    android:layout_margin="10dp">
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_marginBottom="15dp"
        android:background="#000"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#9714b3cf"
            android:orientation="vertical">
        <TextView
            android:id="@+id/tv_month"
            android:background="#b51992b7"
            android:text="January 2017"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="match_parent"
            android:layout_marginTop="40dp"
            android:layout_height="wrap_content"
            android:text="WORK DAYS"
            android:gravity="center"
            android:textSize="25sp"
            />
        <TextView
            android:id="@+id/work_Days"
            android:layout_width="match_parent"
            android:layout_marginTop="20dp"
            android:layout_height="wrap_content"
            android:text="18"
            android:gravity="center"
            android:textSize="45sp"

            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2">
            <Button
                android:id="@+id/tv_present"
                android:layout_width="wrap_content"
                android:background="#d3edfd07"
                android:text="PRESENT 18"
                android:textSize="12sp"
                android:layout_marginEnd="5dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
            <Button
                android:id="@+id/tv_absent"
                android:text="ABSENT 0"
                android:background="#90e775d2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"/>
        </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Body:
Because you are using buttons in list item, that's why OnItemClick not working

you need to do 2 steps in your listview_item.xml

set the root layout with: android:descendantFocusability="blocksDescendants"

set any focusable or clickable view in this item with:

android:clickable="false"

android:focusable="false"

android:focusableInTouchMode="false"

try to add this three line in your button

<Button
    android:id="@+id/button1"
    android:layout_width=""
    android:layout_height=""
   //...........Add this three line in your every button................
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    />


来源: stackexchange

问:
java regex help
I can have one string with the following two formats:

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";
</code>```

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

```<code>"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";
</code>```

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.

答:
Are you using "[MatchString] between" as your pattern without escaping the [] brackets? The characters [, ], ., (, and ) are all special characters in RegEx. If you want to refer to those as literal characters, you need to escape them in the pattern.

Your question is a little unclear. Maybe if you provided specific examples of a real input string you're using, and what you want the matches to look like?

I'd also check out regular-expressions.info for more information and tutorials, including info about and syntax for Java's implementation of RegEx.

ContentLicense: CC BY-SA 2.5

Title: java regex help

Body:
I can have one string with the following two formats:

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between changeValue1 and changeValue2";
"[MatchString] between changeValue1 and changeValue2";

I would like to match if the string have "[MatchString] between" expression.
ANd depending upon which string I match, The changed value format should be one of the following:
The changed format should be :

"[HardCOdeText1 (HardCodeText2)].[HardCodeText3].[MatchString] between chamged1 and changed2"; or
"[MatchString] between changed1 and changed2";

I started to match "[MatchString] between" expression and I got stuck over there:
ANy help is appreciated.


问:
How to accept SOH character from TextField in JAVAFx
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

```<code>8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP
</code>```

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

```<code>8=FIX.4.29=9135=A34=149=TTDS68AP
</code>```

How can I get the SOH character too from the Text Field?

答:
I think the problem is that you want to enter by keyboard and see the control character in the text field:

Ctrl-A (SOH) is a known shortcut, and selects the previous character.

The control character will not be displayed in a normal font.

So I came to the following solution:

```<code>    String SOH_REPR = "°"; // We show SOH as this string.
    someTextField.setOnKeyPressed((ke) -> {
                if (ke.getCode().getName().equals("A")
                        && ke.isControlDown()
                        && !ke.isAltDown()
                        && !ke.isMetaDown()
                        && !ke.isShiftDown()) {
                    TextField textField = (TextField) ke.getSource();
                    ke.consume();
                    int pos = textField.getCaretPosition();
                    textField.insertText(pos, SOH_REPR);
                }
            });
    someTextField.setOnKeyReleased((ke) -> {
                if (ke.getCode().getName().equals("A")
                        && ke.isControlDown()
                        && !ke.isAltDown()
                        && !ke.isMetaDown()
                        && !ke.isShiftDown()) {
                    ke.consume();
                }
            });

// Convert it back.
String text = someTextField.getText().replace(SOH_REPR, "\u0001");
</code>```

Pasting text with SOHs would still needed to be done for completeness sake.

ContentLicense: CC BY-SA 3.0

Body:
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

8=FIX.4.29=9135=A34=149=TTDS68AP

How can I get the SOH character too from the Text Field?

Body:
I think the problem is that you want to enter by keyboard and see the control character in the text field:

Ctrl-A (SOH) is a known shortcut, and selects the previous character.

The control character will not be displayed in a normal font.

So I came to the following solution:

    String SOH_REPR = "°"; // We show SOH as this string.
    someTextField.setOnKeyPressed((ke) -> {
                if (ke.getCode().getName().equals("A")
                        && ke.isControlDown()
                        && !ke.isAltDown()
                        && !ke.isMetaDown()
                        && !ke.isShiftDown()) {
                    TextField textField = (TextField) ke.getSource();
                    ke.consume();
                    int pos = textField.getCaretPosition();
                    textField.insertText(pos, SOH_REPR);
                }
            });
    someTextField.setOnKeyReleased((ke) -> {
                if (ke.getCode().getName().equals("A")
                        && ke.isControlDown()
                        && !ke.isAltDown()
                        && !ke.isMetaDown()
                        && !ke.isShiftDown()) {
                    ke.consume();
                }
            });

// Convert it back.
String text = someTextField.getText().replace(SOH_REPR, "\u0001");

Pasting text with SOHs would still needed to be done for completeness sake.


问:
Can't compile SCSS inside of WebStorm
I'm using node-sass for compiling scss files to css inside of WebStorm.

These are my settings inside my directory.

Program:

```<code>/usr/local/bin/node-sass
</code>```

Arguments:

```<code>--output $ProjectFileDir$/css/ --compile --map $FileName$
</code>```

Output Paths to refresh:

```<code>$ProjectFileDir$/css/$FileNameWithoutExtension$.css:$ProjectFileDir$/css/$FileNameWithoutExtension$.map
</code>```

I want the css file to be written in a css directory under root.
However this is the compilation error I get of the WebStorm

```<code>/usr/local/bin/node-sass --output /Users/melissa/Dropbox/codepen/sample/core-fe/css/ --compile --map styles.scss
path.js:28
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.extname (path.js:1471:5)
    at getOptions (/usr/local/lib/node_modules/node-sass/bin/node-sass:186:40)
    at Object.<anonymous> (/usr/local/lib/node_modules/node-sass/bin/node-sass:368:15)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

Process finished with exit code 1
</code>```

答:
Neither --compile nor --map are listed among available options at https://github.com/sass/node-sass#command-line-interface.

The following settings work fine for me when using the most recent node-sass version (4.7.2):

```<code>Arguments: $FileName$ --source-map=true -o $ProjectFileDir$/css
Output Paths to refresh: $ProjectFileDir$/css/$FileNameWithoutExtension$.css:$ProjectFileDir$/css/$FileNameWithoutExtension$.css.map
Working directory: $FileDir$
</code>```

Title: Can't compile SCSS inside of WebStorm

Body:
I'm using node-sass for compiling scss files to css inside of WebStorm.

These are my settings inside my directory.

Program:

/usr/local/bin/node-sass

Arguments:

--output $ProjectFileDir$/css/ --compile --map $FileName$

Output Paths to refresh:

$ProjectFileDir$/css/$FileNameWithoutExtension$.css:$ProjectFileDir$/css/$FileNameWithoutExtension$.map

I want the css file to be written in a css directory under root.
However this is the compilation error I get of the WebStorm

/usr/local/bin/node-sass --output /Users/melissa/Dropbox/codepen/sample/core-fe/css/ --compile --map styles.scss
path.js:28
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.extname (path.js:1471:5)
    at getOptions (/usr/local/lib/node_modules/node-sass/bin/node-sass:186:40)
    at Object.<anonymous> (/usr/local/lib/node_modules/node-sass/bin/node-sass:368:15)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

Process finished with exit code 1

Body:
Neither --compile nor --map are listed among available options at https://github.com/sass/node-sass#command-line-interface.

The following settings work fine for me when using the most recent node-sass version (4.7.2):

Arguments: $FileName$ --source-map=true -o $ProjectFileDir$/css
Output Paths to refresh: $ProjectFileDir$/css/$FileNameWithoutExtension$.css:$ProjectFileDir$/css/$FileNameWithoutExtension$.css.map
Working directory: $FileDir$


问:
inconsistent behaviour in jQuery selector
```<code>$('#a.b') // doesn't work

document.getElementById('a.b') // works

$('[id="a.b"]') // works
</code>```

Can anyone explain why $('#a.b') doesn't work.

答:
jQuery thinks it is a class. So, you write it using escape sequence as -</p>

```<code>$('#a\\.b')
</code>```

Body:
$('#a.b') // doesn't work

document.getElementById('a.b') // works

$('[id="a.b"]') // works

Can anyone explain why $('#a.b') doesn't work.

Body:
jQuery thinks it is a class. So, you write it using escape sequence as -

$('#a\\.b')


问:
How to pass USER ID from template to function to get values in angular 5
i want to pass my user id to service when i click on edit.

```<code> <tr *ngFor="let visit of visits" style="border-top: 1px solid black">
          <td>{{ visit?.ID }}</td>
          <td>{{ visit?.username }}</td>
            <td>{{ visit?.height }}</td>
            <td>{{ visit?.weight }}</td>
            <td>{{ visit?.patientnote }}</td>
            <td>{{ visit?.doctornote }}</td>
            <td>{{ visit?.nursenote }}</td>
            <td><button mat-raised-button color="accent" (click)="edit()">EDIT</button></td>
            <td><button mat-raised-button color="warn" (click)="delete()">DEL</button></td>
</code>```

答:
you have to use Angular Routing if you want to pass value in url, something as below

```<code>import {Component} from '@angular/core';
import {Component} from '../Module/Component';
import {ListComponent} from "../Module/ListComponent";

export const ApplicationRoutes = [
{ path: 'Rpt/:id', component: Component },//allows to pass id in route
{ path: 'RptList', component: ListComponent },
{ path: '', component:ListComponent }
];
</code>```

if not aware about routing you can check rounting : https://angular.io/guide/router

below will work

```<code><button mat-raised-button color="accent"
     (click)="edit(visit?.ID)">EDIT</button>
</code>```

in ts file function needs to take argument, you can make arugment optional also

```<code>edit(id?:any)
{}
</code>```

Body:
i want to pass my user id to service when i click on edit.

          {{ visit?.ID }}
          {{ visit?.username }}
            {{ visit?.height }}
            {{ visit?.weight }}
            {{ visit?.patientnote }}
            {{ visit?.doctornote }}
            {{ visit?.nursenote }}
            <button mat-raised-button color="accent" (click)="edit()">EDIT</button>
            <button mat-raised-button color="warn" (click)="delete()">DEL</button>

Body:
you have to use Angular Routing if you want to pass value in url, something as below

import {Component} from '@angular/core';
import {Component} from '../Module/Component';
import {ListComponent} from "../Module/ListComponent";

export const ApplicationRoutes = [
{ path: 'Rpt/:id', component: Component },//allows to pass id in route
{ path: 'RptList', component: ListComponent },
{ path: '', component:ListComponent }
];

if not aware about routing you can check rounting : https://angular.io/guide/router

below will work

<button mat-raised-button color="accent"
     (click)="edit(visit?.ID)">EDIT</button>

in ts file function needs to take argument, you can make arugment optional also

edit(id?:any)
{}


问:
How to find a string in char Array without using string functions?(c++)
I have following code:

```<code>char x[30]="computer";
char y[30]="put";
</code>```

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

答:
In C++ you have the find method on string :

```<code> std::string str ("computer"); std::string str2 ("put");

 std::size_t found = str.find(str2);
</code>```

if found = -1, 2nd string isn't in first.

http://www.cplusplus.com/reference/string/string/find/

Body:
I have following code:

char x[30]="computer";
char y[30]="put";

I want to find whether "put" is present in "computer" and print its position.No string functions allowed.

Body:
In C++ you have the find method on string :

 std::string str ("computer"); std::string str2 ("put");

 std::size_t found = str.find(str2);

if found = -1, 2nd string isn't in first.

http://www.cplusplus.com/reference/string/string/find/


答:
Do not use meta characters in your Id's while using Jquery.

. is a meta character and selector see them as regex. You need to escape to make it work. For ex \\.

In this case -

```<code>$('#a\\.b')
</code>```

Javascript getElementById also works because, for it, it's just a String.

When you giving as id="a.b" it checks for a value and won't get treated as meta character.

Title: inconsistent behaviour in jQuery selector

Body:
Do not use meta characters in your Id's while using Jquery.

. is a meta character and selector see them as regex. You need to escape to make it work. For ex \\.

In this case -

$('#a\\.b')

Javascript getElementById also works because, for it, it's just a String.

When you giving as id="a.b" it checks for a value and won't get treated as meta character.


问:
Is using a cached "this" faster than "this" when accessing methods of the same object?
if I access this.something multiple times from another method, would it be faster to cache "this" and access something() or should I just use this.something() over and over?</p>

```<code><script type="text/javascript">
var Foo = (function() {
    return {
        something: function() {
            // Do something
        },
        stuff: function(obj) {
            this.something(obj);
            // ...
            this.something(obj);

            /* OR should I cache this? */
            var $that = this;
            $that.something(obj);
            // ...
            $that.something(obj);
        }
    };
}());
</script>
</code>```

答: You'll just be pointing at a copy of a reference to an object, rather than directly to the reference to the object. I can't imagine how caching it would be faster - but hey, fire up a test framework, execute it inside a loop 10000 times and see if it makes any difference.</p>


问:
Creating undirected weighted graph from adjancency matrix from a csv
I want to create undirected weighted graph of a given adjacency matrix by reading it from a csv. I can read it from a csv but I don't know how to draw its in graph. This is code for reading file.

```<code>int main(){

    ifstream ip("map.csv");

    if(!ip.is_open()) std::cout << "ERROR: File Open" << '\n';

    string first;
    string weight;

    while(ip.good()){
        getline(ip,first);

        getline(ip,weight);

        std::cout << "First: "<<first <<'\n';

        std::cout << "Weight: "<<weight<< '\n';
        std::cout << "-------------------" << '\n';
     }

    ip.close();
}
</code>```

This is code for implementing it in graph.

```<code>class Graph {

     private:

      bool** adjacencyMatrix;

      int vertexCount;

      public:

      Graph(int vertexCount) {

            ip->vertexCount = vertexCount;

            adjacencyMatrix = new bool*[vertexCount];

            for (int i = 0; i < vertexCount; i++) {

                  adjacencyMatrix[i] = new bool[vertexCount];

                  for (int j = 0; j < vertexCount; j++)

                        adjacencyMatrix[i][j] = false;

            }

      }

      void addEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {

                  adjacencyMatrix[i][j] = true;

                  adjacencyMatrix[j][i] = true;

            }

      }

      void removeEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {

                  adjacencyMatrix[i][j] = false;

                  adjacencyMatrix[j][i] = false;

            }

      }

      bool isEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount)

                  return adjacencyMatrix[i][j];

            else

                  return false;

      }

      ~Graph() {

            for (int i = 0; i < vertexCount; i++)

                  delete[] adjacencyMatrix[i];

            delete[] adjacencyMatrix;

      }

};
</code>```

This is how my file looks like.

```<code>C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11
C1,-1,20,-1,40,-1,-1,-1,-1,-1,-1,-1
C2,20,-1,-1,-1,80,-1,-1,-1,-1,-1,-1
C3,-1,-1,-1,-1,60,-1,-1,-1,-1,-1,-1
C4,40,-1,-1,-1,-1,200,-1,-1,-1,-1,-1
C5,-1,80,60,-1,-1,-1,100,-1,43,-1,-1
C6,-1,-1,-1,200,-1,-1,33,-1,-1,-1,-1
C7,-1,-1,-1,-1,100,33,-1,-1,-1,-1,-1
C8,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,55
C9,-1,-1,-1,-1,43,-1,-1,4,-1,-1,-1
C10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32
C11,-1,-1,-1,-1,-1,-1,-1,55,-1,32,-1
</code>```

I don't know how to use my output from reading file into implementing the graph.

答:
Here is my proposal.

First, i've decide to apply @Scheff modification (more or less), with a vector of vector as adjacency matrix. I think makes code cleaner than use row * vertexCount + column type access.

Graph class

```<code>#include <unordered_map>
#include <vector>
#include <string>

class Graph {
private:
    typedef std::vector < std::vector<int> > tAdjacencyMatrix;
private:

    tAdjacencyMatrix adj;

    int vertexCount;

public:

    Graph(int vertexCount) {
        this->vertexCount = vertexCount;
        for (int i = 0; i < vertexCount; i++) {
            std::vector<int> v;
            for (int j = 0; j < vertexCount; j++)
                v.push_back(0);

            adj.push_back(v);
        }
    }

    void addEdge(int i, int j, int value) {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {
            adj[i][j] = value;
            adj[j][i] = value;
        }
    }

    void removeEdge(int i, int j) {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {
            adj[i][j] = 0;
            adj[j][i] = 0;
        }
    }

    bool isEdge(int i, int j) const {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount)
            return adj[i][j];   // 0 interpreted as false
    }

    std::string toString() const{
        std::string ret = "";
        for (int i = 0; i < vertexCount; i++) {
            ret += "V1: ";
            for (int j = 0; j < vertexCount; j++){
                ret += std::to_string(adj[i][j]);
                if (j != vertexCount - 1) ret += ", ";
            }
            ret += "\n";
        }
        return ret;
    }
};
</code>```

I added a toString method to probe that it works fine.

Note: you can use adj.size() instead of vertexCount.

With this, my main look like:

Main

```<code>int main(){

    ifstream ip("map.csv");

    if (!ip.is_open()) std::cout << "ERROR: File Open" << '\n';
    string line;
    getline(ip, line);
    vector<string> tokens = splitString(line, ',');
    int vertexCount = tokens.size();

    Graph g(vertexCount);
    int v = 1;
    while (ip.good()){
        getline(ip, line);
        tokens = splitString(line, ',');
        for (int i = 1; i < tokens.size(); ++i){    // Note that starts in 1, avoiding "Cx" first element
            if (tokens[i].compare("-1") != 0){
                g.addEdge(v, i, atoi(tokens[i].c_str()));
            }
        }
        ++v;
    }

    ip.close();

    cout << g.toString() << endl;
    return 0;
}
</code>```

Split string function:

SplitString

```<code>std::vector<string> splitString(const string &s, char delimiter){
    istringstream iis(s);

    vector<string> tokens;
    string aux = "";
    char c;

    while (iis.good()){
        c = iis.get();
        if (c == delimiter){
            tokens.push_back(aux);
            aux.clear();
        }
        else{
            aux.insert(aux.end(), c);
        }
    }
    tokens.push_back(aux); // Insert the last one (it has no ',' at the end)

    return tokens;
}
</code>```

Note2: splitting function can surely be better, but i think this one is easier to understand

ContentLicense: CC BY-SA 4.0

Body:
I want to create undirected weighted graph of a given adjacency matrix by reading it from a csv. I can read it from a csv but I don't know how to draw its in graph. This is code for reading file.

int main(){

    ifstream ip("map.csv");

    if(!ip.is_open()) std::cout << "ERROR: File Open" << '\n';

    string first;
    string weight;

    while(ip.good()){
        getline(ip,first);

        getline(ip,weight);

        std::cout << "First: "<<first <<'\n';

        std::cout << "Weight: "<<weight<< '\n';
        std::cout << "-------------------" << '\n';
     }

    ip.close();
}

This is code for implementing it in graph.

class Graph {

     private:

      bool** adjacencyMatrix;

      int vertexCount;

      public:

      Graph(int vertexCount) {

            ip->vertexCount = vertexCount;

            adjacencyMatrix = new bool*[vertexCount];

            for (int i = 0; i < vertexCount; i++) {

                  adjacencyMatrix[i] = new bool[vertexCount];

                  for (int j = 0; j < vertexCount; j++)

                        adjacencyMatrix[i][j] = false;

            }

      }

      void addEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {

                  adjacencyMatrix[i][j] = true;

                  adjacencyMatrix[j][i] = true;

            }

      }

      void removeEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {

                  adjacencyMatrix[i][j] = false;

                  adjacencyMatrix[j][i] = false;

            }

      }

      bool isEdge(int i, int j) {

            if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount)

                  return adjacencyMatrix[i][j];

            else

                  return false;

      }

      ~Graph() {

            for (int i = 0; i < vertexCount; i++)

                  delete[] adjacencyMatrix[i];

            delete[] adjacencyMatrix;

      }

};

This is how my file looks like.

C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11
C1,-1,20,-1,40,-1,-1,-1,-1,-1,-1,-1
C2,20,-1,-1,-1,80,-1,-1,-1,-1,-1,-1
C3,-1,-1,-1,-1,60,-1,-1,-1,-1,-1,-1
C4,40,-1,-1,-1,-1,200,-1,-1,-1,-1,-1
C5,-1,80,60,-1,-1,-1,100,-1,43,-1,-1
C6,-1,-1,-1,200,-1,-1,33,-1,-1,-1,-1
C7,-1,-1,-1,-1,100,33,-1,-1,-1,-1,-1
C8,-1,-1,-1,-1,-1,-1,-1,-1,4,-1,55
C9,-1,-1,-1,-1,43,-1,-1,4,-1,-1,-1
C10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32
C11,-1,-1,-1,-1,-1,-1,-1,55,-1,32,-1

I don't know how to use my output from reading file into implementing the graph.

Body:
Here is my proposal.

First, i've decide to apply @Scheff modification (more or less), with a vector of vector as adjacency matrix. I think makes code cleaner than use row * vertexCount + column type access.

Graph class

#include <unordered_map>
#include <vector>
#include <string>

class Graph {
private:
    typedef std::vector < std::vector<int> > tAdjacencyMatrix;
private:

    tAdjacencyMatrix adj;

    int vertexCount;

public:

    Graph(int vertexCount) {
        this->vertexCount = vertexCount;
        for (int i = 0; i < vertexCount; i++) {
            std::vector<int> v;
            for (int j = 0; j < vertexCount; j++)
                v.push_back(0);

            adj.push_back(v);
        }
    }

    void addEdge(int i, int j, int value) {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {
            adj[i][j] = value;
            adj[j][i] = value;
        }
    }

    void removeEdge(int i, int j) {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount) {
            adj[i][j] = 0;
            adj[j][i] = 0;
        }
    }

    bool isEdge(int i, int j) const {
        if (i >= 0 && i < vertexCount && j > 0 && j < vertexCount)
            return adj[i][j];   // 0 interpreted as false
    }

    std::string toString() const{
        std::string ret = "";
        for (int i = 0; i < vertexCount; i++) {
            ret += "V1: ";
            for (int j = 0; j < vertexCount; j++){
                ret += std::to_string(adj[i][j]);
                if (j != vertexCount - 1) ret += ", ";
            }
            ret += "\n";
        }
        return ret;
    }
};

I added a toString method to probe that it works fine.

Note: you can use adj.size() instead of vertexCount.

With this, my main look like:

Main

int main(){

    ifstream ip("map.csv");

    if (!ip.is_open()) std::cout << "ERROR: File Open" << '\n';
    string line;
    getline(ip, line);
    vector<string> tokens = splitString(line, ',');
    int vertexCount = tokens.size();

    Graph g(vertexCount);
    int v = 1;
    while (ip.good()){
        getline(ip, line);
        tokens = splitString(line, ',');
        for (int i = 1; i < tokens.size(); ++i){    // Note that starts in 1, avoiding "Cx" first element
            if (tokens[i].compare("-1") != 0){
                g.addEdge(v, i, atoi(tokens[i].c_str()));
            }
        }
        ++v;
    }

    ip.close();

    cout << g.toString() << endl;
    return 0;
}

Split string function:

SplitString

std::vector<string> splitString(const string &s, char delimiter){
    istringstream iis(s);

    vector<string> tokens;
    string aux = "";
    char c;

    while (iis.good()){
        c = iis.get();
        if (c == delimiter){
            tokens.push_back(aux);
            aux.clear();
        }
        else{
            aux.insert(aux.end(), c);
        }
    }
    tokens.push_back(aux); // Insert the last one (it has no ',' at the end)

    return tokens;
}

Note2: splitting function can surely be better, but i think this one is easier to understand


问:
Array value overwrites instead of retaining old value - Javascript
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

答:
Check below link

JsFiddle

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var loopThroughAllNames = [];
var NextList = document.querySelector("#NextList");

addValue();

function addValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name " + (i + 1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  document.write(JSON.stringify(loopThroughAllNames));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

Body:
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});

<button id="NextList">Next list</button>

Body:
Check below link

JsFiddle

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var loopThroughAllNames = [];
var NextList = document.querySelector("#NextList");

addValue();

function addValue() {
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name " + (i + 1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();
  document.write(JSON.stringify(loopThroughAllNames));
});

<button id="NextList">Next list</button>


答:
1) When adding a node Cassandra will start by choosing good ranges for the new node to take over. It will then create 256 new token ranges that are just portions of the already existing ones. This means the new node takes tokens from many nodes (instead of only one per RF when not using vnodes) in the cluster which makes streaming alot faster.

2 and 3) Does this answer your questions? determine node of a partition in Cassandra

Title: Data Re-Partitioning in Cassandra

Body:
As a follow up of this Data Partition in Cassandra, I got the idea of the vNodes. Thanks to 'Simon Fontana Oscarsson'

When I try to explore the data partitioning using vNodes, I have few questions,

I try to observe the partition distribution in 2 node (./nodetool ring)

Two seed nodes (2 node)

172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9207297847862311651
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9185516104965672922
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9135483708655236026
172.30.56.60  rack1       Up     Normal  102.77 KiB      100.00%             -9106737079237505681
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9078521344187921602
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9051897156173923903
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9049800264451581717
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -9039572936575206977
172.30.56.60  rack1       Up     Normal  102.77 KiB      100.00%             -9019927187583981555
172.30.56.60  rack1       Up     Normal  102.77 KiB      100.00%             -9006071175095726599
172.30.56.60  rack1       Up     Normal  102.77 KiB      100.00%             -8995415525773810853
172.30.56.60  rack1       Up     Normal  102.77 KiB      100.00%             -8949342263103866059
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -8880432529087253108
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -8859265089807316498
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -8844286905987198633
172.30.56.61  rack1       Up     Normal  105.19 KiB      100.00%             -8832739468389117376

So as per my observation in two nodes, The Node 61 has the values from -9207297847862311651 to -9185516104965672922 as one range goes on...

NOTE : Partition range from '-9039572936575206977' to '-9019927187583981554' is currently handled by Node 61.

Now I am adding one more node to the cluster (not the seed node) and I ran ./nodetool ring,

Two seed nodes with one new node (3 node)

172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9207297847862311651
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9185516104965672922
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9135483708655236026
172.30.56.60  rack1       Up     Normal  102.77 KiB      63.57%              -9106737079237505681
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9078521344187921602
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9051897156173923903
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9049800264451581717
172.30.56.61  rack1       Up     Normal  104.12 KiB      64.73%              -9039572936575206977
172.30.56.62  rack1       Up     Normal  103.7 KiB       71.70%              -9031848008695747480
172.30.56.62  rack1       Up     Normal  103.7 KiB       71.70%              -9028974600706382491
172.30.56.60  rack1       Up     Normal  102.77 KiB      63.57%              -9019927187583981555

Now I observed that same partition range is given to the new node Node 62,
i.e, range from -9039572936575206977 to -9031848008695747480 is handled by Node 61 but -9031848008695747480 to -9019927187583981555 is handled by Node 62 (New node),

1) So does this mean that, adding a new node in the cluster will distribute the existing partition range?

2) Is there a way to observe the replicated partitions in Cassandra using any utility like nodetool?

3) I have 3 nodes with RF as 2, How to see the data's available in a node 62 alone?


问:
Build Job from Jenkins Pipeline with variable
I'm not able to build a job from jenkins pipeline passing a variable for job name. Please find below the code snippet. If I replace ${service} with 'microservice' it will trigger the job

```<code>service = 'microservice'
echo "TESSSSSSSSTTT ${service}"
build(job: "'${service}'", parameters: [string(name: 'ENVNAME', value: 'uat')])
</code>```

The error faced is:

```<code>[Pipeline] echo
TESSSSSSSSTTT microservice
[Pipeline] build
[Pipeline] End of Pipeline
ERROR: No item named 'microservice' found
Finished: FAILURE
</code>```

I'm using this method because I want to hit a build command for all the microservices passing the names with multi-line string parameter, finally I want to set this build into a loop.

答:
I assume your job is not called 'microservice' in Jenkins but microservice (without the ticks).

So change your build line to not include single quotes after the double quote:

```<code>build(job: "${service}", parameters: [string(name: 'ENVNAME', value: 'uat')])
</code>```

Did some simple test with my jenkins instance and was able to call a job by setting the service variable to an existing job name.

Body:
I'm not able to build a job from jenkins pipeline passing a variable for job name. Please find below the code snippet. If I replace ${service} with 'microservice' it will trigger the job

service = 'microservice'
echo "TESSSSSSSSTTT ${service}"
build(job: "'${service}'", parameters: [string(name: 'ENVNAME', value: 'uat')])

The error faced is:

[Pipeline] echo
TESSSSSSSSTTT microservice
[Pipeline] build
[Pipeline] End of Pipeline
ERROR: No item named 'microservice' found
Finished: FAILURE

I'm using this method because I want to hit a build command for all the microservices passing the names with multi-line string parameter, finally I want to set this build into a loop.

Body:
I assume your job is not called 'microservice' in Jenkins but microservice (without the ticks).

So change your build line to not include single quotes after the double quote:

build(job: "${service}", parameters: [string(name: 'ENVNAME', value: 'uat')])

Did some simple test with my jenkins instance and was able to call a job by setting the service variable to an existing job name.


问:
How to close Objectbox Store and delete data files
I'v got an exception after I call put() with my data list.

I know that I closed the box before with a reason (deleteAllFiles() must be closed).

How should I open it again? As I see, dataBoxStore is not null after I closed it.

My code:

```<code>dataBoxStore = MyObjectBox.builder().androidContext(this).name("DB").build();

dataBoxStore.close();
dataBoxStore.deleteAllFiles();

final Box<Data> areaLocationBox = dataBoxStore.boxFor(Data.class);
areaLocationBox.put(myList);
</code>```

Exception:

```<code> Caused by: java.lang.IllegalStateException: Store is closed
    at io.objectbox.BoxStore.checkOpen(BoxStore.java:261)
    at io.objectbox.BoxStore.beginTx(BoxStore.java:310)
    at io.objectbox.Box.getWriter(Box.java:107)
    at io.objectbox.Box.put(Box.java:389)
</code>```

答:
With ObjectBox 1.3 this got simpler. You can use one of the static BoxStore.deleteAllFiles methods without initiating a BoxStore:</p>

```<code>BoxStore.deleteAllFiles(context, "DB");
</code>```

Body:
I'v got an exception after I call put() with my data list.

I know that I closed the box before with a reason (deleteAllFiles() must be closed).

How should I open it again? As I see, dataBoxStore is not null after I closed it.

My code:

dataBoxStore = MyObjectBox.builder().androidContext(this).name("DB").build();

dataBoxStore.close();
dataBoxStore.deleteAllFiles();

final Box<Data> areaLocationBox = dataBoxStore.boxFor(Data.class);
areaLocationBox.put(myList);

Exception:

 Caused by: java.lang.IllegalStateException: Store is closed
    at io.objectbox.BoxStore.checkOpen(BoxStore.java:261)
    at io.objectbox.BoxStore.beginTx(BoxStore.java:310)
    at io.objectbox.Box.getWriter(Box.java:107)
    at io.objectbox.Box.put(Box.java:389)

Body:
With ObjectBox 1.3 this got simpler. You can use one of the static BoxStore.deleteAllFiles methods without initiating a BoxStore:

BoxStore.deleteAllFiles(context, "DB");


问:
Set text color and font for UIDatePicker in iOS8/Swift
I've been having trouble trying to set the UIDatePicker font and color. Everything else in my app was fairly straightforward to adjust except this. Does anybody know how to do this? I'm using Swift for iOS8.

答:
You can use extensions to get and set textColor like bellow

```<code>extension UIDatePicker {

    var textColor: UIColor? {
        set {
            setValue(newValue, forKeyPath: "textColor")
        }
        get {
            return value(forKeyPath: "textColor") as? UIColor
        }
    }

}
</code>```

And then set the color:

```<code>datePicker.textColor = .red
</code>```

Body:
You can use extensions to get and set textColor like bellow

extension UIDatePicker {

    var textColor: UIColor? {
        set {
            setValue(newValue, forKeyPath: "textColor")
        }
        get {
            return value(forKeyPath: "textColor") as? UIColor
        }
    }

}

And then set the color:

datePicker.textColor = .red


问:
Node.js Event Loop Phases
I am new to node.js, I have gone through the event loop documentation given on node.org.

There it is stated that : When Node.js starts, it initializes the event loop, processes the provided input script (or drops into the REPL, which is not covered in this document) which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.

I have read the documentation for every phase, but could not understand completely.

Lets say I have following code in index.js:

```<code>console.log('started...');
setTimeout(function(){
    console.log('timeout callback...');
},1000);
console.log('Finishes...');
</code>```

I want to know in which phase my entire code first be loaded, and how event loop will be used for above code when I run command

```<code>node index.js
</code>```

Thanks.

答:
Ok, you should see started..then Finishes statements followed by the timeout callback.

As the doc stated above the eventLoop make async API calls i.e. not waiting for next phase to call while executing the setTimeout function (using Node Timers). Nodejs waits for 1000 milliseconds for the callback to be completed with another THREAD and finishes runs earlier.

Title: Node.js Event Loop Phases

Body:
I am new to node.js, I have gone through the event loop documentation given on node.org.

There it is stated that : When Node.js starts, it initializes the event loop, processes the provided input script (or drops into the REPL, which is not covered in this document) which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.

I have read the documentation for every phase, but could not understand completely.

Lets say I have following code in index.js:

console.log('started...');
setTimeout(function(){
    console.log('timeout callback...');
},1000);
console.log('Finishes...');

I want to know in which phase my entire code first be loaded, and how event loop will be used for above code when I run command

node index.js

Thanks.


问:
Checkbox check repeats in listview
I have the following implementation of a custom ListView populated using a CursorAdapter:

```<code>private class CurAdapter extends CursorAdapter{

        public CurAdapter(Context context, Cursor c, int flags) {

            super(context, c, flags);

        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            final ViewHolder holder = (ViewHolder) view.getTag();

            String name = (cursor.getString(cursor.getColumnIndexOrThrow("NotificationDateFor")));
            String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));

            holder.nametext.setText(name);
            setImage(image, holder.iv);
            holder.chk.setOnClickListener(onchk);

        }
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View view = LayoutInflater.from(context).inflate(R.layout.group_list, null);

            ViewHolder holder = new ViewHolder(view);
            view.setTag(holder);
            return view;

        }

        private View.OnClickListener onchk = new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        };

        public class ViewHolder {
            TextView nametext;
            RoundedImageView iv;
            CheckBox chk;

            public ViewHolder(View view){

                iv = (RoundedImageView)view.findViewById(R.id.imageView2);
                nametext = (TextView) view.findViewById(R.id.textView1);
                chk = (CheckBox) view.findViewById(R.id.checkBox1);

            }

        }

    }
</code>```

I am using a Holder pattern to avoid repetition, but I get check-boxes checked at random while scrolling my list, what do I miss here?

Also I want to know how to store the values of clicked checkboxes in my onClick of the checkbox.

答:
I know this question is old but this may be helpful to somebody.
If you're extending SimpleCursorAdapter, you will notice that the textviews inside the items of your ListView don't repeat themselves. Only the checkboxes do. Inside your adapter's class, you need:

```<code>private ArrayList<Boolean> checkBoxStates = new ArrayList<>();
</code>```

Inside the constructor, put:

```<code>for(int i = 0; i < getCount(); i++) {
    checkBoxStates.add(i, false);
}
</code>```

and override the getView() method as follows:

```<code>public View getView(final int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        CheckBox checkBox = view.findViewById(R.id.checkbox);
        checkBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(((CheckBox)v).isChecked()){
                    checkBoxStates.set(position, true);
                }else{
                    checkBoxStates.set(position, false);
                }
            }
        });
        checkBox.setChecked(checkBoxStates.get(position));
        return view;
}
</code>```

Title: Checkbox check repeats in listview

Body:
I have the following implementation of a custom ListView populated using a CursorAdapter:

private class CurAdapter extends CursorAdapter{

        public CurAdapter(Context context, Cursor c, int flags) {

            super(context, c, flags);

        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            final ViewHolder holder = (ViewHolder) view.getTag();

            String name = (cursor.getString(cursor.getColumnIndexOrThrow("NotificationDateFor")));
            String image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));

            holder.nametext.setText(name);
            setImage(image, holder.iv);
            holder.chk.setOnClickListener(onchk);

        }
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {

            View view = LayoutInflater.from(context).inflate(R.layout.group_list, null);

            ViewHolder holder = new ViewHolder(view);
            view.setTag(holder);
            return view;

        }

        private View.OnClickListener onchk = new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        };

        public class ViewHolder {
            TextView nametext;
            RoundedImageView iv;
            CheckBox chk;

            public ViewHolder(View view){

                iv = (RoundedImageView)view.findViewById(R.id.imageView2);
                nametext = (TextView) view.findViewById(R.id.textView1);
                chk = (CheckBox) view.findViewById(R.id.checkBox1);

            }

        }

    }

I am using a Holder pattern to avoid repetition, but I get check-boxes checked at random while scrolling my list, what do I miss here?

Also I want to know how to store the values of clicked checkboxes in my onClick of the checkbox.

Body:
I know this question is old but this may be helpful to somebody.
If you're extending SimpleCursorAdapter, you will notice that the textviews inside the items of your ListView don't repeat themselves. Only the checkboxes do. Inside your adapter's class, you need:

private ArrayList<Boolean> checkBoxStates = new ArrayList<>();

Inside the constructor, put:

for(int i = 0; i < getCount(); i++) {
    checkBoxStates.add(i, false);
}

and override the getView() method as follows:

public View getView(final int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        CheckBox checkBox = view.findViewById(R.id.checkbox);
        checkBox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(((CheckBox)v).isChecked()){
                    checkBoxStates.set(position, true);
                }else{
                    checkBoxStates.set(position, false);
                }
            }
        });
        checkBox.setChecked(checkBoxStates.get(position));
        return view;
}


问:
Fetching and Posting data to a rest microservice
I am trying to implement HTTP services GET and POST with my Rest micro service created.

I am able to fetch data from my Rest micro service.

But I am unable make a POST request.

Below shown is my code for Rest micro service

WebController.java

```<code>package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class WebController {
    private static final String NULL = null;
    @Autowired
    UsersRepository userRepo;

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return (mapper.writeValueAsString(useObj));
    }

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
    public String checkLoginByName(@RequestBody Users user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Users useObj1 = userRepo.findByUsernameAndPassword(user.username, user.password);
        return (mapper.writeValueAsString(useObj1));
    }
}
</code>```

app.module.ts

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

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';

@NgModule({
  declarations  : [ AppComponent],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [AppComponent]
})

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

app.component.ts

```<code>import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `<h1>{{ title }}</h1>
                <div style="margin-left:50px; height: 200px; overflow: auto;">
                 <table>
                     <tr><td>Username</td>  <td>Password</td></tr>
                     <tr *ngFor= " let item of data">
                 <td>{{ item.username }}</td>  <td>{{ item.password }}</td>
                 </tr>
                 </table>
                </div>

      <h2>Login</h2>
        <form role="form">
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>

            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button (click)="checkByCredential(username,password)">Login</button>
        </form>`
})

export class AppComponent {
  title: string;
  data: any;

  constructor(private MyService: BasicService) {
    this.title = "Angular Service";

    this.MyService.GetUsers()
      .subscribe(users => { this.data = users });
  }

  checkByCredential(username: string, password: string) {
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
  }
}
</code>```

basic.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {
  constructor(private http: Http) { }

  GetUsers() {
    return this.http.get('http://localhost:8080/checkUsers')
      .map(result => result.json());
  }

  checkByCredential(username: string, password: string) {
    const user = { username: username, password: password };
    return this.http
      .post('http://localhost:8080/checkByCredential', user)
      .map(result => result.json());
  }
}
</code>```

And when I am submitting data via my form I am getting this error in my console as shown below in the images

But with my Postman when I am trying to make Post request with username and password ,I am able to get back the data as shown below in the images

can any body please help me out to resolve the Post request in angular 2

updated screen shots after updation in my framework

答:
I had the same problem. The problem is caused by Cross-origin resource sharing (CORS). I created a proxy file to redirect traffic from localhost:4200 to my spring localhost (in your case it's localhost:8080).

In your case I recommend to create a proxy.conf.json file like this:

```<code>{
  "/": {
    "target": "http://localhost:8080",
    "secure": false
  }
}
</code>```

.. and change the absolute paths in your code to relative paths e.g.

```<code>return this.http
   .post('http://localhost:8080/checkByCredential', user)
   .map(result => result.json()
)}
</code>```

to:

```<code>return this.http
   .post('/checkByCredential', user)
   .map(result => result.json()
)}
</code>```

You can run your angular application (proxy enabled) with the following command:

```<code>ng serve --proxy-config proxy.conf.json
</code>```

Your project structure lookes like:

Your WebController is also too complicated; you are serializing to JSON, but that is not necessary.

```<code>package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    @RestController
    public class WebController {
        private static final String NULL = null;
        @Autowired
        UsersRepository userRepo;

        @CrossOrigin(origins = "http://localhost:4200")
        @GetMapping("/checkUsers")
        public List<Users> checkLogin() {
            return userRepo.findAll();
        }

        @CrossOrigin(origins = "http://localhost:4200")
        @PostMapping(value = "/checkByCredential")
        public Users checkLoginByName(@RequestBody Users user) throws Exception {
            return userRepo.findByUsernameAndPassword(user.username, user.password);
        }
    }
</code>```

I think something goes wrong with parsing from/to JSON.

Don't forget to remove the mapping methods! For example, change this

```<code>return this.http
   .post('http://localhost:8080/checkByCredential', user)
   .map(result => result.json()
)}
</code>```

to:

```<code>return this.http.post('http://localhost:8080/checkByCredential', user)
</code>```

Body:
I am trying to implement HTTP services GET and POST with my Rest micro service created.

I am able to fetch data from my Rest micro service.

But I am unable make a POST request.

Below shown is my code for Rest micro service

WebController.java

package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class WebController {
    private static final String NULL = null;
    @Autowired
    UsersRepository userRepo;

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return (mapper.writeValueAsString(useObj));
    }

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
    public String checkLoginByName(@RequestBody Users user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Users useObj1 = userRepo.findByUsernameAndPassword(user.username, user.password);
        return (mapper.writeValueAsString(useObj1));
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';

@NgModule({
  declarations  : [ AppComponent],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [AppComponent]
})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `
{{ title }}

Username	  Password

                 {{ item.username }}	  {{ item.password }}

Login

        <form role="form">

            Username
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>

            Password
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>

          <button (click)="checkByCredential(username,password)">Login</button>
        </form>`
})

export class AppComponent {
  title: string;
  data: any;

  constructor(private MyService: BasicService) {
    this.title = "Angular Service";

    this.MyService.GetUsers()
      .subscribe(users => { this.data = users });
  }

  checkByCredential(username: string, password: string) {
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
  }
}

basic.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {
  constructor(private http: Http) { }

  GetUsers() {
    return this.http.get('http://localhost:8080/checkUsers')
      .map(result => result.json());
  }

  checkByCredential(username: string, password: string) {
    const user = { username: username, password: password };
    return this.http
      .post('http://localhost:8080/checkByCredential', user)
      .map(result => result.json());
  }
}

And when I am submitting data via my form I am getting this error in my console as shown below in the images

But with my Postman when I am trying to make Post request with username and password ,I am able to get back the data as shown below in the images

can any body please help me out to resolve the Post request in angular 2

updated screen shots after updation in my framework

Body:
I had the same problem. The problem is caused by Cross-origin resource sharing (CORS). I created a proxy file to redirect traffic from localhost:4200 to my spring localhost (in your case it's localhost:8080).

In your case I recommend to create a proxy.conf.json file like this:

{
  "/": {
    "target": "http://localhost:8080",
    "secure": false
  }
}

.. and change the absolute paths in your code to relative paths e.g.

return this.http
   .post('http://localhost:8080/checkByCredential', user)
   .map(result => result.json()
)}

to:

return this.http
   .post('/checkByCredential', user)
   .map(result => result.json()
)}

You can run your angular application (proxy enabled) with the following command:

ng serve --proxy-config proxy.conf.json

Your project structure lookes like:

Your WebController is also too complicated; you are serializing to JSON, but that is not necessary.

package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    @RestController
    public class WebController {
        private static final String NULL = null;
        @Autowired
        UsersRepository userRepo;

        @CrossOrigin(origins = "http://localhost:4200")
        @GetMapping("/checkUsers")
        public List<Users> checkLogin() {
            return userRepo.findAll();
        }

        @CrossOrigin(origins = "http://localhost:4200")
        @PostMapping(value = "/checkByCredential")
        public Users checkLoginByName(@RequestBody Users user) throws Exception {
            return userRepo.findByUsernameAndPassword(user.username, user.password);
        }
    }

I think something goes wrong with parsing from/to JSON.

Don't forget to remove the mapping methods! For example, change this

return this.http
   .post('http://localhost:8080/checkByCredential', user)
   .map(result => result.json()
)}

to:

return this.http.post('http://localhost:8080/checkByCredential', user)


问:
Replace multiple occurrences in string
I want to replace all occurrences of double quotes with single quotes.
But only in the img tag! I have a html text

```<code><p>First p</p><img class="image" src="one.jpg" />
<p>Second p</p><img class="image" src="two.jpg" />
</code>```

How can I replace this "in place".
I tried something like this:

```<code>re.sub('"', "'", re.findall(r'<img.*/>', html))
</code>```

The expected result is this:

```<code><p>First p</p><img class='image' src='one.jpg' />
<p>Second p</p><img class='image' src='two.jpg' />
</code>```

答:
re.findall() returns a list, while re.sub() expects a string as the input

```<code>r=re.findall(r'<img.*>', html)
b=[re.sub('"', "'",a) for a in r]
for i in range(len(b)):
    html=str.replace(html,r[i],b[i])
print html
</code>```

Output

```<code><p>First p</p><img class='image' src='one.jpg' />
<p>Second p</p><img class='image' src='two.jpg' />
</code>```

Title: Replace multiple occurrences in string

Body:
I want to replace all occurrences of double quotes with single quotes.
But only in the img tag! I have a html text

First p

Second p

How can I replace this "in place".
I tried something like this:

re.sub('"', "'", re.findall(r'', html))

The expected result is this:

First p

Second p

Body:
re.findall() returns a list, while re.sub() expects a string as the input

r=re.findall(r'<img.*>', html)
b=[re.sub('"', "'",a) for a in r]
for i in range(len(b)):
    html=str.replace(html,r[i],b[i])
print html

Output

<p>First p</p><img class='image' src='one.jpg' />
<p>Second p</p><img class='image' src='two.jpg' />


问:
Does Pandas use Numpy as a random number generator?
I want to get reproducible samples of data. A quick experiment suggests, that numpy.random.seed does influence pandas.DataFrame.sample, but it is not documented.

Does anybody know

What I tried

I ran the following a couple of times and always got the same results back

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

import pandas as pd
import numpy as np

df = pd.DataFrame([(1, 2, 1),
                   (1, 2, 2),
                   (1, 2, 3),
                   (4, 1, 612),
                   (4, 1, 612),
                   (4, 1, 1),
                   (3, 2, 1),
                   ],
                  columns=['groupid', 'a', 'b'],
                  index=['India', 'France', 'England', 'Germany', 'UK', 'USA',
                         'Indonesia'])
np.random.seed(0)
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))
</code>```

Which gives:

Indonesia

France

Indonesia

USA

England

答:
pandas use _random_state function for return np.random.RandomState link:

```<code>def _random_state(state=None):
    """
    Helper function for processing random_state arguments.
    Parameters
    ----------
    state : int, np.random.RandomState, None.
        If receives an int, passes to np.random.RandomState() as seed.
        If receives an np.random.RandomState object, just returns object.
        If receives `None`, returns np.random.
        If receives anything else, raises an informative ValueError.
        Default None.
    Returns
    -------
    np.random.RandomState
    """

    if types.is_integer(state):
        return np.random.RandomState(state)
    elif isinstance(state, np.random.RandomState):
        return state
    elif state is None:
        return np.random
    else:
        raise ValueError("random_state must be an integer, a numpy "
                         "RandomState, or None")
</code>```

and in sample is called this function:

```<code>    # Process random_state argument
    rs = com._random_state(random_state)
</code>```

Body:
I want to get reproducible samples of data. A quick experiment suggests, that numpy.random.seed does influence pandas.DataFrame.sample, but it is not documented.

Does anybody know

What I tried

I ran the following a couple of times and always got the same results back

#!/usr/bin/env python

import pandas as pd
import numpy as np

df = pd.DataFrame([(1, 2, 1),
                   (1, 2, 2),
                   (1, 2, 3),
                   (4, 1, 612),
                   (4, 1, 612),
                   (4, 1, 1),
                   (3, 2, 1),
                   ],
                  columns=['groupid', 'a', 'b'],
                  index=['India', 'France', 'England', 'Germany', 'UK', 'USA',
                         'Indonesia'])
np.random.seed(0)
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))
print(df.sample(n=1))

Which gives:

Indonesia

France

Indonesia

USA

England

Body:
pandas use _random_state function for return np.random.RandomState link:

def _random_state(state=None):
    """
    Helper function for processing random_state arguments.
    Parameters
    ----------
    state : int, np.random.RandomState, None.
        If receives an int, passes to np.random.RandomState() as seed.
        If receives an np.random.RandomState object, just returns object.
        If receives `None`, returns np.random.
        If receives anything else, raises an informative ValueError.
        Default None.
    Returns
    -------
    np.random.RandomState
    """

    if types.is_integer(state):
        return np.random.RandomState(state)
    elif isinstance(state, np.random.RandomState):
        return state
    elif state is None:
        return np.random
    else:
        raise ValueError("random_state must be an integer, a numpy "
                         "RandomState, or None")

and in sample is called this function:

    # Process random_state argument
    rs = com._random_state(random_state)


问:
Extending a struct with generic array type specification
Is it possible to do something like this at all in swift 4?

```<code>extension MyStruct where T: [Object] { }
</code>```

I thought there has to be a way as this compiles:

```<code>let property = MyStruct<[Object]>()
</code>```

My struct would than look like this:

```<code>struct MyStruct<T> { }
</code>```

答:
You want to restrict T to be equal to some type:

```<code>extension MyStruct where T == [Object] {

}
</code>```

A constraint T: P would be used to restrict T to conform to (or inherit from) P.

Body:
Is it possible to do something like this at all in swift 4?

extension MyStruct where T: [Object] { }

I thought there has to be a way as this compiles:

let property = MyStruct<[Object]>()

My struct would than look like this:

struct MyStruct<T> { }

Body:
You want to restrict T to be equal to some type:

extension MyStruct where T == [Object] {

}

A constraint T: P would be used to restrict T to conform to (or inherit from) P.


问:
Problem: jQuery snaps div left while animating
I have a div that I am trying to swap out for another div with a clip effect.  However, when I do this in Firefox it snaps the content left while the animation is happening and then returns it to the center upon completion.

It works as expected in IE6 (gasp! still the standard at my work, campaigning to update), but not in firefox.

What am I doing wrong?

Javascript:

```<code><script type="text/javascript">
        $(function(){
            $("#editEmpInfo").click(function(){
              $("#selectedEmployee").hide("clip", { direction: "vertical" }, 500, function() {
                $("#editSelectedEmployee").show("clip", { direction: "vertical" }, 500);
              });
            });

            $("#saveEmpInfo").click(function(){
              $("#editSelectedEmployee").hide("clip", { direction: "vertical" }, 500, function() {
                $("#selectedEmployee").show("clip", { direction: "vertical" }, 500);
              });
            });

        });
    </script>
</code>```

HTML:

```<code><div class="container">
<div id="selectedEmployee" class="container400">
    <div class="currentEmp">
        <div class="currentEmpName">
            Last, First <br />
            <span class="empWorkUnit">Work Unit</span>
        </div>

        <div id="editEmpInfo"><a title="Edit" href="#"></a></div>
                <div class="currentEmpInfo">
            <div>Ext: </div>
            <div>Cell: </div>
            <div>Home: </div>
            <div>Pager: </div>
            <div>Other: </div>

            <div>Notes: </div>
        </div>
    </div>
</div>

<div id="editSelectedEmployee" class="container400 hidden">
    <div class="currentEmp">
        <div class="currentEmpName">
            Last, First <br />

            <span class="empWorkUnit">Work Unit</span>
        </div>
        <div id="saveEmpInfo"><a title="Save" href="#"></a></div>
        <div class="currentEmpInfo">
            <div>Ext: </div>
            <div>Cell: </div>
            <div>Home: </div>

            <div>Pager: </div>
            <div>Other: </div>
            <div>Notes: </div>
        </div>
    </div>
</div>
</div>
</code>```

CSS:

```<code>body {
    font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
    font-size: 12px;
}

.container {
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

.container400 {
    width: 400px;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
}

.hidden {
    display: none;
}

.currentEmp {
    border: solid 1px #CCCCCC;
    display: block;
    padding: 10px;
}

#selectedEmployee {
    background: #EEEEEE;
}

#editSelectedEmployee {
    background: #E8EDFF;
}

.currentEmpName {
    font-size: 18px;
    color: #0077D4;
    float: left;
}

.currentEmpName .empWorkUnit {
    font-style: italic;
    font-size: 14px;
    font-weight: normal;
    color: #000000;
}

#editEmpInfo a{
    display: block;
    background: url("../images/Edit.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

#upOneLevel a{
    display: block;
    background: url("../images/Up.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

#saveEmpInfo a{
    display: block;
    background: url("../images/Save.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

.currentEmpInfo {
    clear: both;
}

#callSheet {
    border-collapse: collapse;
    font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
    font-size: 12px;
    margin: 20px;
    text-align: left;
    min-width: 700px;
    margin-left: auto;
    margin-right: auto;
}

#callSheet th {
  background: none repeat scroll 0 0 #B9C9FE;
  color: #003399;
  font-size: 13px;
  font-weight: normal;
  padding: 8px;
  text-align: center;
}

#callSheet td {
  background: none repeat scroll 0 0 #E8EDFF;
  border-top: 1px solid #FFFFFF;
  color: #666699;
  padding: 8px;
}

#callSheet tbody tr:hover td {
  background: none repeat scroll 0 0 #D0DAFD;
}
</code>```

答:
UPDATE:
This problem seems to be caused by using margin-left:auto and margin-right:auto on the elements that you're anmiating. While the animation is happening, you get a snap-left behavior.

To fix, simply move the auto margins to the higher-level container, and set the child elements to width:100%. I used inline styles in my sample but this should work wherever the styles are defined.

Like this:

```<code><div class="container400" >
    <div id="selectedEmployee" style="width:100%;">
        <div class="currentEmp">
            <div class="currentEmpName">
                Last, First <br />
                <span class="empWorkUnit">Work Unit</span>
            </div>

            <div id="editEmpInfo"><a title="Edit" href="#">Edit</a></div>
                    <div class="currentEmpInfo">
                <div>Ext: </div>
                <div>Cell: </div>
                <div>Home: </div>
                <div>Pager: </div>
                <div>Other: </div>

                <div>Notes: </div>
            </div>
        </div>
    </div>

    <div id="editSelectedEmployee" class="hidden" style="width:100%;">
        <div class="currentEmp">
            <div class="currentEmpName">
                Last, First <br />

                <span class="empWorkUnit">Work Unit</span>
            </div>
            <div id="saveEmpInfo"><a title="Save" href="#">Save</a></div>
            <div class="currentEmpInfo">
                <div>Ext: </div>
                <div>Cell: </div>
                <div>Home: </div>

                <div>Pager: </div>
                <div>Other: </div>
                <div>Notes: </div>
            </div>
        </div>
    </div>
</div>
</code>```

OLD ANSWER: (the trick below works true in some cases, although clearly not yours!)

I've run into this problem on various non-IE browsers including Firefox and Chrome. I was able to work around it by adding inline styles (yuck!) to the container element that you're animating.

The inline styles required are: display:block; plus setting all margin widths explicitly. For example:

```<code><div id="badSnappingElement" style="display: block; margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; ">
</code>```

It's the inline styles that makes it work. Using CSS for this won't prevent the problem.

Your setup is a little complicated because there are two different elements being hidden and shown, so you may need to experiment to find the right element(s) to attach the inline styles to.

Body:
I have a div that I am trying to swap out for another div with a clip effect.  However, when I do this in Firefox it snaps the content left while the animation is happening and then returns it to the center upon completion.

It works as expected in IE6 (gasp! still the standard at my work, campaigning to update), but not in firefox.

What am I doing wrong?

Javascript:

HTML:

            Last, First

            Work Unit

Ext:

Cell:

Home:

Pager:

Other:

Notes:

            Last, First

            Work Unit

Ext:

Cell:

Home:

Pager:

Other:

Notes:

CSS:

body {
    font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
    font-size: 12px;
}

.container {
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

.container400 {
    width: 400px;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
}

.hidden {
    display: none;
}

.currentEmp {
    border: solid 1px #CCCCCC;
    display: block;
    padding: 10px;
}

#selectedEmployee {
    background: #EEEEEE;
}

#editSelectedEmployee {
    background: #E8EDFF;
}

.currentEmpName {
    font-size: 18px;
    color: #0077D4;
    float: left;
}

.currentEmpName .empWorkUnit {
    font-style: italic;
    font-size: 14px;
    font-weight: normal;
    color: #000000;
}

#editEmpInfo a{
    display: block;
    background: url("../images/Edit.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

#upOneLevel a{
    display: block;
    background: url("../images/Up.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

#saveEmpInfo a{
    display: block;
    background: url("../images/Save.png") no-repeat;
    width: 32px;
    height: 32px;
    margin: 5px;
    float: right;
}

.currentEmpInfo {
    clear: both;
}

#callSheet {
    border-collapse: collapse;
    font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
    font-size: 12px;
    margin: 20px;
    text-align: left;
    min-width: 700px;
    margin-left: auto;
    margin-right: auto;
}

#callSheet th {
  background: none repeat scroll 0 0 #B9C9FE;
  color: #003399;
  font-size: 13px;
  font-weight: normal;
  padding: 8px;
  text-align: center;
}

#callSheet td {
  background: none repeat scroll 0 0 #E8EDFF;
  border-top: 1px solid #FFFFFF;
  color: #666699;
  padding: 8px;
}

#callSheet tbody tr:hover td {
  background: none repeat scroll 0 0 #D0DAFD;
}

Body:
UPDATE:
This problem seems to be caused by using margin-left:auto and margin-right:auto on the elements that you're anmiating. While the animation is happening, you get a snap-left behavior.

To fix, simply move the auto margins to the higher-level container, and set the child elements to width:100%. I used inline styles in my sample but this should work wherever the styles are defined.

Like this:

<div class="container400" >
    <div id="selectedEmployee" style="width:100%;">
        <div class="currentEmp">
            <div class="currentEmpName">
                Last, First <br />
                <span class="empWorkUnit">Work Unit</span>
            </div>

            <div id="editEmpInfo"><a title="Edit" href="#">Edit</a></div>
                    <div class="currentEmpInfo">
                <div>Ext: </div>
                <div>Cell: </div>
                <div>Home: </div>
                <div>Pager: </div>
                <div>Other: </div>

                <div>Notes: </div>
            </div>
        </div>
    </div>

    <div id="editSelectedEmployee" class="hidden" style="width:100%;">
        <div class="currentEmp">
            <div class="currentEmpName">
                Last, First <br />

                <span class="empWorkUnit">Work Unit</span>
            </div>
            <div id="saveEmpInfo"><a title="Save" href="#">Save</a></div>
            <div class="currentEmpInfo">
                <div>Ext: </div>
                <div>Cell: </div>
                <div>Home: </div>

                <div>Pager: </div>
                <div>Other: </div>
                <div>Notes: </div>
            </div>
        </div>
    </div>
</div>

OLD ANSWER: (the trick below works true in some cases, although clearly not yours!)

I've run into this problem on various non-IE browsers including Firefox and Chrome. I was able to work around it by adding inline styles (yuck!) to the container element that you're animating.

The inline styles required are: display:block; plus setting all margin widths explicitly. For example:

<div id="badSnappingElement" style="display: block; margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; ">

It's the inline styles that makes it work. Using CSS for this won't prevent the problem.

Your setup is a little complicated because there are two different elements being hidden and shown, so you may need to experiment to find the right element(s) to attach the inline styles to.


问:
Truncated Inccorrect date value while calling nested function
I have two function.

fn_validate_date

fn_validation

fn_validate_date code:

```<code> CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validate_date`(
    `dt_date` DATE

 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT 'Returns the associated value of given attribute for given employee                for a particular date.'
 BEGIN
    SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
    RETURN dt_date;
 END
</code>```

fn_validation code:

```<code> CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validation`(
    `dt_date` DATE
 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT ''
 BEGIN
    RETURN fn_validate_date(dt_date);
 END
</code>```

Now when I am calling fn_validate_date as below

```<code> SELECT `fn_validate_date`(null);
</code>```

It's working well but when I calling fn_validation it's giving me an error.

```<code>SELECT `fn_validation`(null);
</code>```

My question is why I didn't get error while calling fn_validate_date?

答:
In fn_validate_date, the dt_date-parameter is type of date and you are comparing it to a string datatype. No need for that. Date datatype cannot contain ''. It either is NULL or has a date value in it.

So instead of:

```<code>SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
</code>```

You can simply use:

```<code>return ifnull( dt_date, current_date() );
</code>```

Body:
I have two function.

fn_validate_date

fn_validation

fn_validate_date code:

 CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validate_date`(
    `dt_date` DATE

 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT 'Returns the associated value of given attribute for given employee                for a particular date.'
 BEGIN
    SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);
    RETURN dt_date;
 END

fn_validation code:

 CREATE DEFINER=`root`@`localhost` FUNCTION `fn_validation`(
    `dt_date` DATE
 )
 RETURNS date
 LANGUAGE SQL
 NOT DETERMINISTIC
 CONTAINS SQL
 SQL SECURITY DEFINER
 COMMENT ''
 BEGIN
    RETURN fn_validate_date(dt_date);
 END

Now when I am calling fn_validate_date as below

 SELECT `fn_validate_date`(null);

It's working well but when I calling fn_validation it's giving me an error.

SELECT `fn_validation`(null);

My question is why I didn't get error while calling fn_validate_date?

Body:
In fn_validate_date, the dt_date-parameter is type of date and you are comparing it to a string datatype. No need for that. Date datatype cannot contain ''. It either is NULL or has a date value in it.

So instead of:

SET dt_date = IF(dt_date IS NULL OR dt_date ='', CURRENT_DATE, dt_date);

You can simply use:

return ifnull( dt_date, current_date() );


问:
stratified sampling with fixed proportions of observation types in R
I have a sample where 50% of the observations are White and 50% African-American.

I would like to obtain a random subsample where such proportion is modified to 80% White and 20% African-American.

I have tried the command stratified but I could not find an option allowing me to allocate shares to the stratifying criterion.

Thank you in advance for your help!

答:
Well I'd filter the data for White and African-American and then select from each subset.

```<code>## 80% of the white sample
  smp_size <- floor(train_ratio * nrow(df_white))

  ## set the seed to make your partition reproductible
  set.seed(42)
  data_ind_w <- sample(seq_len(nrow(df_white)), size = smp_size)
</code>```

and for the African-American

```<code>## 20% of the african sample
  smp_size <- floor(train_ratio * nrow(df_african))

  ## set the seed to make your partition reproductible
  set.seed(42)
  data_ind_a <- sample(seq_len(nrow(df_african)), size = smp_size)
</code>```

thats the new data

```<code>  new_data <- c(white[data_ind_w,],african[data_ind_a,])
</code>```

Body:
Well I'd filter the data for White and African-American and then select from each subset.

## 80% of the white sample
  smp_size <- floor(train_ratio * nrow(df_white))

  ## set the seed to make your partition reproductible
  set.seed(42)
  data_ind_w <- sample(seq_len(nrow(df_white)), size = smp_size)

and for the African-American

## 20% of the african sample
  smp_size <- floor(train_ratio * nrow(df_african))

  ## set the seed to make your partition reproductible
  set.seed(42)
  data_ind_a <- sample(seq_len(nrow(df_african)), size = smp_size)

thats the new data

  new_data <- c(white[data_ind_w,],african[data_ind_a,])