问:
Typescript `enum` from JSON string
Is there any way to have a TypeScript enum compatible with strings from JSON?

For example:

```<code>enum Type { NEW, OLD }

interface Thing { type: Type }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // false
</code>```

I would like thing.type == Type.NEW to be true. Or more specifically, I wish I could specify the enum values to be defined as strings, not numbers.

I am aware that I can use thing.type.toString() == Type[Type.NEW] but this is cumbersome and seems to make the enum type annotation confusing and misleading, which defeats its purpose. The JSON is technically not supplying a valid enum value, so I shouldn't type the property to the enum.

So what I am currently doing instead is using a string type with static constants:

```<code>const Type = { NEW: "NEW", OLD: "OLD" }

interface Thing { type: string }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // true
</code>```

This gets me the usage I want, but the type annotation string is way too broad and error prone.

I'm a bit surprised that a superset of JavaScript doesn't have string based enums. Am I missing something? Is there a different way this can be done?

Update TS 1.8

Using string literal types is another alternative (thanks @basaret), but to get the desired enum-like usage (above) it requires defining your values twice: once in a string literal type, and once as a value (constant or namespace):

```<code>type Type = "NEW" | "OLD";
const Type = {
    NEW: "NEW" as Type,
    OLD: "OLD" as Type
}

interface Thing { type: Type }

let thing:Thing = JSON.parse(`{"type": "NEW"}`);

alert(thing.type === Type.NEW); // true
</code>```

This works but takes a lot of boilerplate, enough that I don't use it most of the time. For now I'm hoping the proposal for string enums will eventually make the roadmap.

Update TS 2.1

The new keyof type lookup allows for the string literal type to be generated from the keys of a const or namespace, which makes the definition a little less redundant:

```<code>namespace Type {
    export const OLD = "OLD";
    export const NEW = "NEW";
}
type Type = keyof typeof Type;

interface Thing { type: Type }

const thing: Thing = JSON.parse('{"type": "NEW"}');
thing.type == Type.NEW // true
</code>```

Update TS 2.4

TypeScript 2.4 added support for string enums! The above example becomes:

```<code>enum Type {
    OLD = "OLD",
    NEW = "NEW"
}

interface Thing { type: Type }
const thing: Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW) // true
</code>```

This looks nearly perfect, but there's still some heartache:

You still have to write the value twice, ie OLD = "OLD", and there's no validation that you don't have a typo, like NEW = "MEW"... this has already bitten me in real code.

There's some oddities (perhaps bugs?) with how the enum is type checked, its not just a string literal type shorthand, which is what would be truly correct. Some issues I've bumped into:

```<code>enum Color { RED = "RED", BLUE = "BLUE", GREEN = "GREEN" }

type ColorMap = { [P in Color]: number; }

declare const color: Color;
declare const map: ColorMap;
map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature.

const red: Color = "RED"; // Type '"RED"' is not assignable to type 'Color'.
const blue: Color = "BLUE" as "RED" | "BLUE" | "GREEN"; // Error: Type '"RED" | "BLUE" | "GREEN"' is not assignable to type 'Color'.
</code>```

The equivalent code with enum Color replaced by string literal types work fine...

Yeah, I think I have OCD about this, I just want my perfect JS enums. :)

答:
If you are using Typescript before the 2.4 release, there is a way to achieve that with enums by casting the values of your enum to any.

An example of your first implementation

```<code>enum Type {
    NEW = <any>"NEW",
    OLD = <any>"OLD",
}

interface Thing { type: Type }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // true
</code>```

Typescript 2.4 has built in support for string enums already, so the cast to any would be no longer necessary and you could achieve it without the use of String Literal Union Type, which is ok for validation and autocomplete, but not so good for readability and refactoring, depending on the usage scenario.

Title: Typescript `enum` from JSON string

Body:
Is there any way to have a TypeScript enum compatible with strings from JSON?

For example:

enum Type { NEW, OLD }

interface Thing { type: Type }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // false

I would like thing.type == Type.NEW to be true. Or more specifically, I wish I could specify the enum values to be defined as strings, not numbers.

I am aware that I can use thing.type.toString() == Type[Type.NEW] but this is cumbersome and seems to make the enum type annotation confusing and misleading, which defeats its purpose. The JSON is technically not supplying a valid enum value, so I shouldn't type the property to the enum.

So what I am currently doing instead is using a string type with static constants:

const Type = { NEW: "NEW", OLD: "OLD" }

interface Thing { type: string }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // true

This gets me the usage I want, but the type annotation string is way too broad and error prone.

I'm a bit surprised that a superset of JavaScript doesn't have string based enums. Am I missing something? Is there a different way this can be done?

Update TS 1.8

Using string literal types is another alternative (thanks @basaret), but to get the desired enum-like usage (above) it requires defining your values twice: once in a string literal type, and once as a value (constant or namespace):

type Type = "NEW" | "OLD";
const Type = {
    NEW: "NEW" as Type,
    OLD: "OLD" as Type
}

interface Thing { type: Type }

let thing:Thing = JSON.parse(`{"type": "NEW"}`);

alert(thing.type === Type.NEW); // true

This works but takes a lot of boilerplate, enough that I don't use it most of the time. For now I'm hoping the proposal for string enums will eventually make the roadmap.

Update TS 2.1

The new keyof type lookup allows for the string literal type to be generated from the keys of a const or namespace, which makes the definition a little less redundant:

namespace Type {
    export const OLD = "OLD";
    export const NEW = "NEW";
}
type Type = keyof typeof Type;

interface Thing { type: Type }

const thing: Thing = JSON.parse('{"type": "NEW"}');
thing.type == Type.NEW // true

Update TS 2.4

TypeScript 2.4 added support for string enums! The above example becomes:

enum Type {
    OLD = "OLD",
    NEW = "NEW"
}

interface Thing { type: Type }
const thing: Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW) // true

This looks nearly perfect, but there's still some heartache:

You still have to write the value twice, ie OLD = "OLD", and there's no validation that you don't have a typo, like NEW = "MEW"... this has already bitten me in real code.

There's some oddities (perhaps bugs?) with how the enum is type checked, its not just a string literal type shorthand, which is what would be truly correct. Some issues I've bumped into:

enum Color { RED = "RED", BLUE = "BLUE", GREEN = "GREEN" }

type ColorMap = { [P in Color]: number; }

declare const color: Color;
declare const map: ColorMap;
map[color] // Error: Element implicitly has an 'any' type because type 'ColorMap' has no index signature.

const red: Color = "RED"; // Type '"RED"' is not assignable to type 'Color'.
const blue: Color = "BLUE" as "RED" | "BLUE" | "GREEN"; // Error: Type '"RED" | "BLUE" | "GREEN"' is not assignable to type 'Color'.

The equivalent code with enum Color replaced by string literal types work fine...

Yeah, I think I have OCD about this, I just want my perfect JS enums. :)

Body:
If you are using Typescript before the 2.4 release, there is a way to achieve that with enums by casting the values of your enum to any.

An <a href="https://www.typescriptlang.org/play/index.html#src=enum%20Type%20%7B%0D%0A%20%20%20%20NEW%20%3D%20%22NEW%22%2C%0D%0A%20%20%20%20OLD%20%3D%20%22OLD%22%2C%0D%0A%7D%0D%0A%0D%0Ainterface%20Thing%20%7B%20type%3A%20Type%20%7D%0D%0A%0D%0Alet%20thing%3AThing%20%3D%20JSON.parse('%7B%22type%22%3A%20%22NEW%22%7D')%3B%0D%0A%0D%0Aalert(thing.type%20%3D%3D%20Type.NEW)%3B%20%2F%2F%20true#src=enum%20Type%20%7B%0D%0A%20%20%20%20NEW%20%3D%20%3Cany%3E%22NEW%22%2C%0D%0A%20%20%20%20OLD%20%3D%20%3Cany%3E%22OLD%22%2C%0D%0A%7D%0D%0A%0D%0Ainterface%20Thing%20%7B%20type%3A%20Type%20%7D%0D%0A%0D%0Alet%20thing%3AThing%20%3D%20JSON.parse('%7B%22type%22%3A%20%22NEW%22%7D')%3B%0D%0A%0D%0Aalert(thing.type%20%3D%3D%20Type.NEW)%3B%20%2F%2F%20true" rel="noreferrer">example of your first implementation

enum Type {
    NEW = <any>"NEW",
    OLD = <any>"OLD",
}

interface Thing { type: Type }

let thing:Thing = JSON.parse('{"type": "NEW"}');

alert(thing.type == Type.NEW); // true

Typescript 2.4 has built in support for string enums already, so the cast to any would be no longer necessary and you could achieve it without the use of String Literal Union Type, which is ok for validation and autocomplete, but not so good for readability and refactoring, depending on the usage scenario.


来源: stackexchange

问:
How to use the instr function regardless of ignoring case sensitvitiy of the string. eg: "PENETRATION, Penetration, penetration"
Problem description

```<code>Sub Update_Click()
  Dim i As Integer
  i = 5
  Do Until i > 100  'repeat function below till row 100'

    If InStr(1, (Cells(i, 5).Value), "Struck") > 0 Then
      Cells(i, 8).Value = "Near miss"
    End If

    If InStr(1, (Cells(i, 5).Value), "Cut") > 0 Then
      Cells(i, 8).Value = "Minor"
    End If

    i = i + 1

  Loop        'close loop formula'
End Sub
</code>```

I would like to search for the words STRUCK, struck, Struck, CUT, Cut, cut

答:
You may change the string to UCase or to LCase. Then compare it, like this:

```<code>Public Sub TestMe()

    Debug.Print "asd" = "aSd"
    Debug.Print UCase("asd") = UCase("ASD")
    Debug.Print LCase("aSd") = LCase("ASD")

End Sub
</code>```

Ucase:

https://www.techonthenet.com/excel/formulas/ucase.php

Using the example of Alex K. in the comments, it would be like this:

```<code>?instr(1, ucase("A BBB C"), ucase("bBb"))
</code>```

if you do not pass optional vbCompareMethod argument, which is specified exactly for this.

ContentLicense: CC BY-SA 3.0

Body:
Problem description

Sub Update_Click()
  Dim i As Integer
  i = 5
  Do Until i > 100  'repeat function below till row 100'

    If InStr(1, (Cells(i, 5).Value), "Struck") > 0 Then
      Cells(i, 8).Value = "Near miss"
    End If

    If InStr(1, (Cells(i, 5).Value), "Cut") > 0 Then
      Cells(i, 8).Value = "Minor"
    End If

    i = i + 1

  Loop        'close loop formula'
End Sub

I would like to search for the words STRUCK, struck, Struck, CUT, Cut, cut

Body:
You may change the string to UCase or to LCase. Then compare it, like this:

Public Sub TestMe()

    Debug.Print "asd" = "aSd"
    Debug.Print UCase("asd") = UCase("ASD")
    Debug.Print LCase("aSd") = LCase("ASD")

End Sub

Ucase:

https://www.techonthenet.com/excel/formulas/ucase.php

Using the example of Alex K. in the comments, it would be like this:

?instr(1, ucase("A BBB C"), ucase("bBb"))

if you do not pass optional vbCompareMethod argument, which is specified exactly for this.


问:
Add and copy row when matching
I am playing around with Macros in Excel 2016. What I want is to add a row under a row containing the text "name" and if that's the case copy the row contents under it. What I tried so far:

```<code>Sub InsertNewRow()
    Dim c As Range
    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.EntireRow.Insert

    End If
    Next dblCounter
End Sub
</code>```

The question is how to add a new row (see above code) and copy the full contents of the row above into it.

答:
Try to allways use Option Explicit at the top, and declare all your variables.

Code

```<code>Option Explicit

Sub InsertNewRow()

    Dim c As Range, Rng As Range
    Dim dblCounter As Long

    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.Offset(1).EntireRow.Insert ' insert a row below
            c.EntireRow.Copy Destination:=Range("A" & c.Row + 1) ' copy the contents from the row above
        End If
    Next dblCounter

End Sub
</code>```

Title: Add and copy row when matching

Body:
I am playing around with Macros in Excel 2016. What I want is to add a row under a row containing the text "name" and if that's the case copy the row contents under it. What I tried so far:

Sub InsertNewRow()
    Dim c As Range
    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.EntireRow.Insert

    End If
    Next dblCounter
End Sub

The question is how to add a new row (see above code) and copy the full contents of the row above into it.

Body:
Try to allways use Option Explicit at the top, and declare all your variables.

Code

Option Explicit

Sub InsertNewRow()

    Dim c As Range, Rng As Range
    Dim dblCounter As Long

    Set Rng = ActiveSheet.Range("A1:H654")
    For dblCounter = Rng.Cells.Count To 1 Step -1
        Set c = Rng(dblCounter)
        If c.Value Like "*Name*" Then
            c.Offset(1).EntireRow.Insert ' insert a row below
            c.EntireRow.Copy Destination:=Range("A" & c.Row + 1) ' copy the contents from the row above
        End If
    Next dblCounter

End Sub


问:
aria-hidden property not working on descendants
Chrome Accessibility Tools complains that certain children of an overlay box do not have the right contrast ratio. It seems like the tool considers the children to be "visible" when the overlay is hidden.

I can see the aria-hidden property of the overlay being correctly set in the inspector as I open/close it, though (using attr("aria-hidden","false");).

Setting aria-hidden="true"; through the inspector on the children individually fixes this problem.

I am confused as aria-hidden is supposed to hide the element and its children.
Does anyone know what I am doing wrong?

答:
Thank you for your comments, it made me realise I was indeed confused by what the audit tool was checking.

I used the advice given on the w3 website regarding putting [aria-hidden="true"] { visibility: hidden; } in my code, which properly hides the overlay when its aria-hidden property is set to true, and results in the audit tool being happy. :)


问:
React Router v4 params
I'm following a React tutorial that is using React Router v3. While I'm using React Router v4. I'm passing a parameter called id from a component called Root to another component called User.

```<code>export class Root extends  React.Component {
    render() {
        return(
            <div className="container">
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <Header />
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-10 col-xs-offset-1">
                        <hr/>
                        <Route exact path="/" component={Home}/>
                        <Route path="/user/:id" component={User}/>
                        <Route path="/home" component={Home}/>
                        {/*{this.props.children}*/}
                    </div>
                </div>
            </div>
        );
    }
}
</code>```

And I'm picking up the parameter with {this.props.match.params.id} like below and works.

```<code>export class User extends React.Component {

    onNavigateHome() {
        this.props.history.push("/home")
    }

    render() {
        return (
            <div>
                <h3>The User Page</h3>
                <p>User ID: {this.props.match.params.id}</p>
                <button onClick={() => this.onNavigateHome()} className="btn btn-primary">Go home!</button>
            </div>
        );
    }
}
</code>```

In the tutorial {this.props.params.id} is used. Am I doing it the right way in with {this.props.match.params.id}? And what does match mean?

答:
Match is property that react router v4 injects when the route’s path matches.

A match object has following properties:

url —the matched part of the current location’s pathname

path — the route’s path

isExact—path === pathname

params — an object containing values from the pathname that were
captured by path-to-regexp

As for following V3 tutorial with V4 - I would not recommend it since there are substantial changes between two versions

Title: React Router v4 params

Body:
I'm following a React tutorial that is using React Router v3. While I'm using React Router v4. I'm passing a parameter called id from a component called Root to another component called User.

export class Root extends  React.Component {
    render() {
        return(

                        <Route exact path="/" component={Home}/>
                        <Route path="/user/:id" component={User}/>
                        <Route path="/home" component={Home}/>
                        {/*{this.props.children}*/}

        );
    }
}

And I'm picking up the parameter with {this.props.match.params.id} like below and works.

export class User extends React.Component {

    onNavigateHome() {
        this.props.history.push("/home")
    }

    render() {
        return (

The User Page

User ID: {this.props.match.params.id}

                <button onClick={() => this.onNavigateHome()} className="btn btn-primary">Go home!</button>

        );
    }
}

In the tutorial {this.props.params.id} is used. Am I doing it the right way in with {this.props.match.params.id}? And what does match mean?


问:
Best way to Continuous deployment for Drupal 7 websites
I tried many modules to deploy the changes from development to staging manually but didn't find the better way to deploy the changes either coding or database to the staging server automatically.

Is there anything for Drupal 7 by which I can push my changes from development to staging without any manual work? I want all database related configuration, codes etc to be pushed automatically on the live server.

Thanks

答:
There are many ways you can automate your deployment. one of which we follow is as below:

Using third party services like platform or pantheon for deployment.

Using hook_update_N along with features and strongram modules for configuration management.

Using shell script for running custom commands after deployment.

Using jenkins for deployment automation.

Some other tools / services can be found here https://www.kelltontech.com/monkey-talk


问:
Setting date with spinner - Android
What I want is, when I choose "Today" or "Tomorrow" on spinner to display it in date format in editText. "Pick a date" is working but I can choose date only once so I need this fixed too. Here is code:

```<code>package com.example.android.myapplication;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

private static final String TAG = "MainActivity";

private EditText editText;
private DatePickerDialog.OnDateSetListener mDateSetListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.editText);

    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = (ArrayAdapter.createFromResource(this, R.array.dates, android.R.layout.simple_spinner_item));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH);
                    int day = cal.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    //set today's date
                case "Tomorrow":
                    //set tomorrow's date
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            Log.d(TAG, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year);

            String date = month + "/" + day + "/" + year;
            editText.setText(date);
        }
    };

}
</code>```

答:
I managed to do if for "Today" but I need help for tomorrow..

```<code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String formattedDate = df.format(cal.getTime());

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);

                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    editText.setText(formattedDate);
                case "Tomorrow":

            }
        }
</code>```

Title: Setting date with spinner - Android

Body:
What I want is, when I choose "Today" or "Tomorrow" on spinner to display it in date format in editText. "Pick a date" is working but I can choose date only once so I need this fixed too. Here is code:

package com.example.android.myapplication;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;

private static final String TAG = "MainActivity";

private EditText editText;
private DatePickerDialog.OnDateSetListener mDateSetListener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.editText);

    spinner = (Spinner) findViewById(R.id.spinner);
    adapter = (ArrayAdapter.createFromResource(this, R.array.dates, android.R.layout.simple_spinner_item));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH);
                    int day = cal.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    //set today's date
                case "Tomorrow":
                    //set tomorrow's date
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month = month + 1;
            Log.d(TAG, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year);

            String date = month + "/" + day + "/" + year;
            editText.setText(date);
        }
    };

}

Body:
I managed to do if for "Today" but I need help for tomorrow..

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String formattedDate = df.format(cal.getTime());

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (spinner.getSelectedItem().toString()) {
                case "Pick a date":

                    DatePickerDialog dialog = new DatePickerDialog(
                            MainActivity.this,
                            android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                            mDateSetListener,
                            year,month,day);

                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.show();

                case "Today":
                    editText.setText(formattedDate);
                case "Tomorrow":

            }
        }


问:
How to deal with array<String> in spark dataframe?
I have a json dataset, and it is formated as:

```<code>val data = spark.read.json("user.json").select("user_id","friends").show()
+--------------------+--------------------+
|             user_id|             friends|
+--------------------+--------------------+
|18kPq7GPye-YQ3LyK...|[rpOyqD_893cqmDAt...|
|rpOyqD_893cqmDAtJ...|[18kPq7GPye-YQ3Ly...|
|4U9kSBLuBDU391x6b...|[18kPq7GPye-YQ3Ly...|
|fHtTaujcyKvXglE33...|[18kPq7GPye-YQ3Ly...|
+--------------------+--------------------+
data: org.apache.spark.sql.DataFrame = [user_id: string, friends: array<string>]
</code>```

How can I transform it to [user_id: String, friend: String], eg:

```<code>+--------------------+--------------------+
|             user_id|             friend|
+--------------------+--------------------+
|18kPq7GPye-YQ3LyK...| rpOyqD_893cqmDAt...|
|18kPq7GPye-YQ3LyK...| 18kPq7GPye-YQ3Ly...|
|4U9kSBLuBDU391x6b...| 18kPq7GPye-YQ3Ly...|
|fHtTaujcyKvXglE33...| 18kPq7GPye-YQ3Ly...|
+--------------------+--------------------+
</code>```

How can I get this dataframe?

答:
You can use concat_ws function to concat the array of string and get only a string

```<code>data.withColumn("friends", concat_ws("",col("friends")))
</code>```

concat_ws(java.lang.String sep, Column... exprs) Concatenates multiple
  input string columns together into a single string column, using the
  given separator.

Or you can use simple udf to convert array to string as below

```<code> import org.apache.spark.sql.functions._

 val value = udf((arr: Seq[String]) => arr.mkString(" "))

 val newDf = data.withColumn("hobbies", value($"friends"))
</code>```

If you are trying to get values of array  for user then you can use explode method as

```<code>data.withColumn("friends", explode($"friends"))
</code>```

explode(Column e) Creates a new row for each element in the given
  array or map column.

If you are trying to get only one data then, as @ramesh suggested you can get first element as

```<code>data.withColumn("friends", $"friends"(0))
</code>```

Hope this helps!

Body:
I have a json dataset, and it is formated as:

val data = spark.read.json("user.json").select("user_id","friends").show()
+--------------------+--------------------+
|             user_id|             friends|
+--------------------+--------------------+
|18kPq7GPye-YQ3LyK...|[rpOyqD_893cqmDAt...|
|rpOyqD_893cqmDAtJ...|[18kPq7GPye-YQ3Ly...|
|4U9kSBLuBDU391x6b...|[18kPq7GPye-YQ3Ly...|
|fHtTaujcyKvXglE33...|[18kPq7GPye-YQ3Ly...|
+--------------------+--------------------+
data: org.apache.spark.sql.DataFrame = [user_id: string, friends: array<string>]

How can I transform it to [user_id: String, friend: String], eg:

+--------------------+--------------------+
|             user_id|             friend|
+--------------------+--------------------+
|18kPq7GPye-YQ3LyK...| rpOyqD_893cqmDAt...|
|18kPq7GPye-YQ3LyK...| 18kPq7GPye-YQ3Ly...|
|4U9kSBLuBDU391x6b...| 18kPq7GPye-YQ3Ly...|
|fHtTaujcyKvXglE33...| 18kPq7GPye-YQ3Ly...|
+--------------------+--------------------+

How can I get this dataframe?

Body:
You can use concat_ws function to concat the array of string and get only a string

data.withColumn("friends", concat_ws("",col("friends")))

concat_ws(java.lang.String sep, Column... exprs) Concatenates multiple
  input string columns together into a single string column, using the
  given separator.

Or you can use simple udf to convert array to string as below

 import org.apache.spark.sql.functions._

 val value = udf((arr: Seq[String]) => arr.mkString(" "))

 val newDf = data.withColumn("hobbies", value($"friends"))

If you are trying to get values of array  for user then you can use explode method as

data.withColumn("friends", explode($"friends"))

explode(Column e) Creates a new row for each element in the given
  array or map column.

If you are trying to get only one data then, as @ramesh suggested you can get first element as

data.withColumn("friends", $"friends"(0))

Hope this helps!


问:
Data is not uploading to mysql
I'm learning how to integrate php scripts into wordpress.

I've created a function:

```<code>function sollicitatie_formulier() {
ob_start();
include 'scripts/solliciteer-form.php';
return ob_get_clean();
}
add_shortcode( 'sollicitatie_formulier', 'sollicitatie_formulier' );
</code>```

The script that I'm calling looks like this:

```<code><?php

global $wpdb;

if(isset($_POST['btn-upload']))
{
$table = sollicitaties;
$file = rand(1000,100000)."-".$_FILES['afile']['name'];
$file_size = $_FILES['afile']['size'];
$file_type = $_FILES['afile']['type'];
$file_loc = $_FILES['afile']['tmp_name'];
$folder="wp-content/themes/jobify-extended/uploads/";
$data = array(
'voornaam' => $_POST['avoornaam'],
'familienaam' => $_POST['afamilienaam'],
'comment' => $_POST['amsg'],
'afile' => rand(1000,100000)."-".$_FILES['afile']['name'],
'size' => $_FILES['afile']['size'],
'type' => $_FILES['afile']['type'],

);

// new file size in KB
$new_size = $file_size/1024;
// new file size in KB

// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case

$final_file=str_replace(' ','-',$new_file_name);

$format = array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
);

if(move_uploaded_file($file_loc,$folder.$final_file))
{
$success=$wpdb->insert( $table, $data, $format,$folder);
if($success){
?>
<script>
alert('successfully uploaded');
window.location.href='sollicitatie-formulier?success';
</script>
<?php

}
}
}

else {
?>

<form action="" method="post" enctype="multipart/form-data">
<label for="voornaam">Voornaam: </label><input type="text" name="avoornaam" required="">
<label for="familienaam">Familienaam: </label><input type="text" name="afamilienaam" required="">
<label for="comment">bericht: </label><textarea type="text" name="amsg"></textarea>
<input type="file" name="afile" accept=".pdf, .doc, .docx" />
<input type="submit" name="btn-upload" value="upload"</input>
</form>

<?php
if(isset($_GET['success']))
{
?>
<label>Kandidaat succesvol toegevoegd... <a href="/bekijk/">click hier om kandidaten te bekijken.</a></label>
<?php
}
else if(isset($_GET['fail']))
{
?>
<label>Oeps...een probleem! Probeer opnieuw</label>
<?php
}
else
{
?>
<label>Try to upload any files(PDF, DOC, DOCX)</label>

<?php } }

?>
</code>```

My file gets uploaded to my folder but no data is being sent to my database.
I'm trying to understand what the issue is but I can't figure it out.
I hope you don't mind explain aswel what I'm doing wrong than just giving the correct answer.

答:
You forgot to add $wpdb->prefix.

Example

```<code>global $wpdb;

$table = $wpdb->prefix.'sollicitaties';
</code>```

Title: Data is not uploading to mysql

Body:
I'm learning how to integrate php scripts into wordpress.

I've created a function:

function sollicitatie_formulier() {
ob_start();
include 'scripts/solliciteer-form.php';
return ob_get_clean();
}
add_shortcode( 'sollicitatie_formulier', 'sollicitatie_formulier' );

The script that I'm calling looks like this:

<?php

global $wpdb;

if(isset($_POST['btn-upload']))
{
$table = sollicitaties;
$file = rand(1000,100000)."-".$_FILES['afile']['name'];
$file_size = $_FILES['afile']['size'];
$file_type = $_FILES['afile']['type'];
$file_loc = $_FILES['afile']['tmp_name'];
$folder="wp-content/themes/jobify-extended/uploads/";
$data = array(
'voornaam' => $_POST['avoornaam'],
'familienaam' => $_POST['afamilienaam'],
'comment' => $_POST['amsg'],
'afile' => rand(1000,100000)."-".$_FILES['afile']['name'],
'size' => $_FILES['afile']['size'],
'type' => $_FILES['afile']['type'],

);

// new file size in KB
$new_size = $file_size/1024;
// new file size in KB

// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case

$final_file=str_replace(' ','-',$new_file_name);

$format = array(
'%s',
'%s',
'%s',
'%s',
'%s',
'%s',
);

if(move_uploaded_file($file_loc,$folder.$final_file))
{
$success=$wpdb->insert( $table, $data, $format,$folder);
if($success){
?>

<?php

}
}
}

else {
?>

<form action="" method="post" enctype="multipart/form-data">
Voornaam: <input type="text" name="avoornaam" required="">
Familienaam: <input type="text" name="afamilienaam" required="">
bericht: <textarea type="text" name="amsg"></textarea>
<input type="file" name="afile" accept=".pdf, .doc, .docx" />
<input type="submit" name="btn-upload" value="upload"</input>
</form>

<?php
if(isset($_GET['success']))
{
?>
Kandidaat succesvol toegevoegd... click hier om kandidaten te bekijken.
<?php
}
else if(isset($_GET['fail']))
{
?>
Oeps...een probleem! Probeer opnieuw
<?php
}
else
{
?>
Try to upload any files(PDF, DOC, DOCX)

<?php } }

?>

My file gets uploaded to my folder but no data is being sent to my database.
I'm trying to understand what the issue is but I can't figure it out.
I hope you don't mind explain aswel what I'm doing wrong than just giving the correct answer.

Body:
You forgot to add $wpdb->prefix.

Example

global $wpdb;

$table = $wpdb->prefix.'sollicitaties';


问:
Finding closest match in collection of numbers
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

```<code>1, 3, 8, 10, 13, ...
</code>```

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

答:
Language: C, Char count: 79

```<code>c(int v,int*a,int A){int n=*a;for(;--A;++a)n=abs(v-*a)<abs(v-n)?*a:n;return n;}
</code>```

Signature:

```<code>int closest(int value, int *array, int array_size);
</code>```

Usage:

```<code>main()
{
    int a[5] = {1, 3, 8, 10, 13};
    printf("%d\n", c(4, a, 5));
}
</code>```

OwnerDisplayName: Slace

ContentLicense: CC BY-SA 2.5

Body:
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

LastEditorDisplayName: Allain Lalonde

Body:
Language: C, Char count: 79

c(int v,int*a,int A){int n=*a;for(;--A;++a)n=abs(v-*a)<abs(v-n)?*a:n;return n;}

Signature:

int closest(int value, int *array, int array_size);

Usage:

main()
{
    int a[5] = {1, 3, 8, 10, 13};
    printf("%d\n", c(4, a, 5));
}

OwnerDisplayName: strager


问:
PostgreSQL: how to format date without using to_char()?
I have this PHP-script which I'd like to keep unchanged:

```<code>$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);
</code>```

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex

答:
A better approach than relying on the database for date formatting would be to rely on PHP for this.

```<code>echo date("Y-m-d", strtotime($row['column']));
</code>```

This both solves your initial problem (of confusing the join statement when building your query), and also gives you a lot more flexibility (eg, maybe later a user can set a preference for preferred date format), and more scalability (the more work you can do in PHP which is unlimitedly horizontally scalable, the better).

Body:
I have this PHP-script which I'd like to keep unchanged:

$display = array(
    'QDATETIME',
    'ID',
    'NAME',
    'CATEGORY',
    'APPSVERSION',
    'OSVERSION',
);

$sql = sprintf("
    select %s from quincytrack
    where qdatetime > (now() - interval '2 day') and
    qdatetime <= now()",
    join(', ', $display));
$sth = $pg->prepare($sql);
$sth->execute($args);

My problem is that QDATETIME is printed as 2010-12-18 15:51:37 while I need it as 2010-12-18. I know I could call to_char(QDATETIME, 'YYYY-MM-DD') as QDATETIME, but would prefer to find some other way to affect the date output format...

Using PostgreSQL 8.4.5 under CentOS 5.5 Linux / 64 bit.

Thank you!
Alex

Body:
A better approach than relying on the database for date formatting would be to rely on PHP for this.

echo date("Y-m-d", strtotime($row['column']));

This both solves your initial problem (of confusing the join statement when building your query), and also gives you a lot more flexibility (eg, maybe later a user can set a preference for preferred date format), and more scalability (the more work you can do in PHP which is unlimitedly horizontally scalable, the better).


问:
Batch operation to all matrices stored in a n-dimensional numpy array
I have a numpy array of size (4, 4, 6890), which basically stores contains 6890 4x4 matrices. I need to invert all of them and I am currently doing in a loop, which I know is a bad practice

```<code>for i in range(0, T.shape[2]):
    T_inv[:,:,i] = np.linalg.inv(T[:,:,i])
</code>```

How can I do it with a single call?

答:
np.linalg.inv will do it, but you need to rearrange your axes:

```<code> T_inv = np.moveaxis(np.linalg.inv(np.moveaxis(T, -1, 0)), 0, -1)
</code>```

Might be better to just construct T so that T.shape = (68690, 4, 4).  It will help with broadcasting as well.

Body:
I have a numpy array of size (4, 4, 6890), which basically stores contains 6890 4x4 matrices. I need to invert all of them and I am currently doing in a loop, which I know is a bad practice

for i in range(0, T.shape[2]):
    T_inv[:,:,i] = np.linalg.inv(T[:,:,i])

How can I do it with a single call?

Body:
np.linalg.inv will do it, but you need to rearrange your axes:

 T_inv = np.moveaxis(np.linalg.inv(np.moveaxis(T, -1, 0)), 0, -1)

Might be better to just construct T so that T.shape = (68690, 4, 4).  It will help with broadcasting as well.


问:
redefinition of unused function in python
I have 2 python files in the same folder utils.py and preprocessing.py.

I have two functions defined in utils.py file: preprocess_text, text2seq_generator

I need to use these functions in preprocessing.py. But I'm getting unable to import and warning saying redefinition of unused preprocess_text from line 19

Code:

utils.py

```<code>from __future__ import print_function
from collections import defaultdict
from collections import Counter
from string import punctuation
#import pdb

def filter_text(text):
    return ''.join([c for c in text if c not in punctuation]).lower()

def preprocess_text(file_path_src, file_path_tar, max_feats):
    f_src = open(file_path_src)
    f_tar = open(file_path_tar)
    vocab = defaultdict(int)
    freq_src = defaultdict(int)
    freq_tar = defaultdict(int)
    sents_src = [line.rstrip() for line in f_src.readlines()]
    sents_tar = [line.rstrip() for line in f_tar.readlines()]

    for sent in sents_src:
        sent = filter_text(sent)
        for word in sent.split():
            freq_src[word] += 1

   for sent in sents_tar:
       for word in sent.split():
           freq_tar[word] += 1

   freq_sorted_src = Counter(freq_src)
   freq_sorted_src = freq_sorted_src.most_common(max_feats)
   freq_sorted_tar = Counter(freq_tar)
   freq_sorted_tar = freq_sorted_tar.most_common(max_feats)

   freq_words_src = map(lambda x:x[0], freq_sorted_src)
   freq_words_tar = map(lambda x:x[0], freq_sorted_tar)

   vocab_src = dict({v:k for k, v in enumerate(freq_words_src)})
   vocab_tar = dict({v:k for k, v in enumerate(freq_words_tar)})

   vocab_src["UNK"] = max_feats
   vocab_src["<s>"] = max_feats + 1
   vocab_src["</s>"] = max_feats + 2

   vocab_tar["UNK"] = max_feats
   vocab_tar["<s>"] = max_feats + 1
   vocab_tar["</s>"] = max_feats + 2
   #pdb.set_trace()
   return vocab_src, vocab_tar, sents_src, sents_tar

def text2seq_generator(vocab_src, vocab_tar, sents_src, sents_tar):
    unk_key = vocab_src["UNK"]
    for sent_src, sent_tar in zip(sents_src, sents_tar):
        seq_src = map(lambda x:vocab_src.get(x, unk_key), filter_text(sent_src).split())
        seq_tar = map(lambda x:vocab_tar.get(x, unk_key), sent_tar.split())
        #pdb.set_trace()
        yield seq_src, seq_tar

 #vs, vt, ss, st = preprocess_text('../data/training.hi-en.en', '../data/training.hi-en.hi', 5000)
 #for x,y in text2seq_generator(vs, vt, ss, st):
 #print(y)
</code>```

preprocessing.py file:

```<code>  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text,text2seq_generator
</code>```

Error :

```<code>  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text

  Traceback (most recent call last):

   File "<ipython-input-8-335a30ab7871>", line 6, in <module>
from utils import preprocess_text

  ImportError: cannot import name 'preprocess_text'
</code>```

warning:

```<code>   redefinition of unused preprocess_text from line 19
</code>```

答:
Option 1

You run it from a python IDE (instead of running it from the commandline). Then the IDE (at least with spyder this is the case) will look in your path environmental variable for the utils.py script. Which most likely isn't there.

Solution 1

Add these lines at the start of your script:

```<code>import sys
sys.path.insert(0, 'directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator
</code>```

Or just change your working directory:

```<code>import os
os.chdir('directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator
</code>```

Option 2

You already installed the module utils. Therefore, the script will try to find the function preprocess_text in this module (BTW: this will not happen if you run it via the commandline).

Solution 2

Rename utils.py (And if running from IDE add the lines from solution 1!).

Body:
I have 2 python files in the same folder utils.py and preprocessing.py.

I have two functions defined in utils.py file: preprocess_text, text2seq_generator

I need to use these functions in preprocessing.py. But I'm getting unable to import and warning saying redefinition of unused preprocess_text from line 19

Code:

utils.py

from __future__ import print_function
from collections import defaultdict
from collections import Counter
from string import punctuation
#import pdb

def filter_text(text):
    return ''.join([c for c in text if c not in punctuation]).lower()

def preprocess_text(file_path_src, file_path_tar, max_feats):
    f_src = open(file_path_src)
    f_tar = open(file_path_tar)
    vocab = defaultdict(int)
    freq_src = defaultdict(int)
    freq_tar = defaultdict(int)
    sents_src = [line.rstrip() for line in f_src.readlines()]
    sents_tar = [line.rstrip() for line in f_tar.readlines()]

    for sent in sents_src:
        sent = filter_text(sent)
        for word in sent.split():
            freq_src[word] += 1

   for sent in sents_tar:
       for word in sent.split():
           freq_tar[word] += 1

   freq_sorted_src = Counter(freq_src)
   freq_sorted_src = freq_sorted_src.most_common(max_feats)
   freq_sorted_tar = Counter(freq_tar)
   freq_sorted_tar = freq_sorted_tar.most_common(max_feats)

   freq_words_src = map(lambda x:x[0], freq_sorted_src)
   freq_words_tar = map(lambda x:x[0], freq_sorted_tar)

   vocab_src = dict({v:k for k, v in enumerate(freq_words_src)})
   vocab_tar = dict({v:k for k, v in enumerate(freq_words_tar)})

   vocab_src["UNK"] = max_feats
   vocab_src["<s>"] = max_feats + 1
   vocab_src["</s>"] = max_feats + 2

   vocab_tar["UNK"] = max_feats
   vocab_tar["<s>"] = max_feats + 1
   vocab_tar["</s>"] = max_feats + 2
   #pdb.set_trace()
   return vocab_src, vocab_tar, sents_src, sents_tar

def text2seq_generator(vocab_src, vocab_tar, sents_src, sents_tar):
    unk_key = vocab_src["UNK"]
    for sent_src, sent_tar in zip(sents_src, sents_tar):
        seq_src = map(lambda x:vocab_src.get(x, unk_key), filter_text(sent_src).split())
        seq_tar = map(lambda x:vocab_tar.get(x, unk_key), sent_tar.split())
        #pdb.set_trace()
        yield seq_src, seq_tar

 #vs, vt, ss, st = preprocess_text('../data/training.hi-en.en', '../data/training.hi-en.hi', 5000)
 #for x,y in text2seq_generator(vs, vt, ss, st):
 #print(y)

preprocessing.py file:

  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text,text2seq_generator

Error :

  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text

  Traceback (most recent call last):

   File "<ipython-input-8-335a30ab7871>", line 6, in <module>
from utils import preprocess_text

  ImportError: cannot import name 'preprocess_text'

warning:

   redefinition of unused preprocess_text from line 19

Body:
Option 1

You run it from a python IDE (instead of running it from the commandline). Then the IDE (at least with spyder this is the case) will look in your path environmental variable for the utils.py script. Which most likely isn't there.

Solution 1

Add these lines at the start of your script:

import sys
sys.path.insert(0, 'directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator

Or just change your working directory:

import os
os.chdir('directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator

Option 2

You already installed the module utils. Therefore, the script will try to find the function preprocess_text in this module (BTW: this will not happen if you run it via the commandline).

Solution 2

Rename utils.py (And if running from IDE add the lines from solution 1!).


问:
Configure firewall rules for kubernetes cluster
I am trying to configure firewall rules for kubernetes service to allow restricted access to my mongo pod when running a load balancer service. I would like to know how to specify the ip range because we have our own internal firewall?</p>

答:
From https://kubernetes.io/docs/tasks/access-application-cluster/configure-cloud-provider-firewall/#restrict-access-for-loadbalancer-service:

When using a Service with spec.type: LoadBalancer, you can specify the IP ranges that are allowed to access the load balancer by using spec.loadBalancerSourceRanges. This field takes a list of IP CIDR ranges, which Kubernetes will use to configure firewall exceptions. This feature is currently supported on Google Compute Engine, Google Container Engine and AWS. This field will be ignored if the cloud provider does not support the feature.

This loadBalancerSourceRanges property should help in your case.


问:
Multiple Git repos for one solution
I'm working on solutions split on multiple Git repos.

Every project has its own Git repository and a tool builds a workspace with the required ones and generates a solution file. That's the workframe of my company.

Eg:

```<code><root>
├─── solution.sln (generated by checkout tool)
├─── project group 1
│       ├─── project 1.1
|       |       ├─── .git
|       |       └─── <project files>
│       └─── project 1.2
|               ├─── .git
|               └─── <project files>
└─── project group 2
        ├─── project 2.1
        |       ├─── .git
        |       └─── <project files>
        └─── project 2.2
                ├─── .git
                └─── <project files>
</code>```

Note that there is no repo at the root (projects are not submodules).

Visual Studio seems to be able to connect to only one repo in the Team Explorer view. However, I sometimes edit files from multiple projects.

I'd like to have (at least) an agregated view of the changes for the current solution (ie across all the repos). If possible, I'd like to be able to see the diffs from that view.

JetBrain's Rider does this but for now, I'd prefer to be able to stick Visual Studio.

Is there any extension doing this?

答: Sounds like a this git submodule plugin for Visual studio. That is assuming you are working with submodules.</p>

Title: Multiple Git repos for one solution

Body:
I'm working on solutions split on multiple Git repos.

Every project has its own Git repository and a tool builds a workspace with the required ones and generates a solution file. That's the workframe of my company.

Eg:

<root>
├─── solution.sln (generated by checkout tool)
├─── project group 1
│       ├─── project 1.1
|       |       ├─── .git
|       |       └─── <project files>
│       └─── project 1.2
|               ├─── .git
|               └─── <project files>
└─── project group 2
        ├─── project 2.1
        |       ├─── .git
        |       └─── <project files>
        └─── project 2.2
                ├─── .git
                └─── <project files>

Note that there is no repo at the root (projects are not submodules).

Visual Studio seems to be able to connect to only one repo in the Team Explorer view. However, I sometimes edit files from multiple projects.

I'd like to have (at least) an agregated view of the changes for the current solution (ie across all the repos). If possible, I'd like to be able to see the diffs from that view.

JetBrain's Rider does this but for now, I'd prefer to be able to stick Visual Studio.

Is there any extension doing this?


问:
Kafka consumer group offset retention
How long does kafka store the offset of a consumer-group after all consumers in that group fail?
Is there a configuration variable for this?</p>

答:
The right property name is:

```<code>offsets.retention.minutes
</code>```

from https://kafka.apache.org/documentation/#brokerconfigs

ContentLicense: CC BY-SA 4.0

Title: Kafka consumer group offset retention

Body:
The right property name is:

offsets.retention.minutes

from https://kafka.apache.org/documentation/#brokerconfigs


问:
Deploying c# application issues
I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.

In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files  and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.

Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so

```<code>String[] filePaths = Directory.GetFiles(@"DataSources\");
</code>```

I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?

Thanks for your time

答:
Have you tried something like: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx or http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx ?

So
Directory.GetFiles(environment.currentdirectory + @"\DataSources\");

Title: Deploying c# application issues

Body:
I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.

In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files  and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.

Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so

String[] filePaths = Directory.GetFiles(@"DataSources\");

I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?

Thanks for your time


问:
.net/xslt: <xsl:include> with relative path causes error
My C# program has to generate different PDF documents in different versions. The basic header and footer are identical. So I would like to put them in a separate xsl.

Here the folder structure I like to have:

```<code>/common/headerFooter.xsl
/docVersion1/doc1.xsl
/docVersion1/doc2.xsl
...
/docVersion2/doc1a.xsl
/docVersion2/doc2a.xsl
...
</code>```

So in fact the include in e.g. doc1.xsl should work like:

```<code><xsl:include href="../common/headerFooter.xsl"/>
</code>```

But I get the following error:

```<code>[Fatal Error] :1:1 Content is not allowed in prolog.
System-ID unknown; Zeilennummer1; Spaltennummer1; org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
</code>```

Okay - first idea would be about BOM etc., but no. The files are perfectly okay (!).

So I made this try:

```<code>/docVersion1/headerFooter.xsl
/docVersion1/doc1.xsl
/docVersion1/doc2.xsl
...
/docVersion2/headerFooter.xsl
/docVersion2/doc1a.xsl
/docVersion2/doc2a.xsl
...
</code>```

And in the doc1.xsl (etc.):

```<code><xsl:include href="headerFooter.xsl"/>
</code>```

This one functioned... (!?!?)

Where is the problem?

The relative path in the first attempt is correct. Also Visual Studio tells it. And I think it would be quite strange to put a copy of the headerFooter.xsl in each docVersion-folder.

Recent code:

```<code>// xmlToPdfInfo holds all important information about the stylesheets.
// xmlToPdfInfo.XslPath : path to the doc_.xsl-files
java.io.File xsltfile = new java.io.File(xmlToPdfInfo.XslPath);

StreamSource streamSource = new StreamSource(xsltfile.getAbsoluteFile());

// ERROR LINE:
Transformer transformer = factory.newTransformer(streamSource);
// It seems there is already an analyse for all includes and it fails to
// get the relativ path correctly.
// No chance to put additional information e.g. about the path using
// parameters.

// Set the value of a <param> in the stylesheet);
if (xmlToPdfInfo.Arguments != null)
{
     IList keys = xmlToPdfInfo.Arguments.GetKeyList();
     foreach (var key in keys)
     {
          Object value = xmlToPdfInfo.Arguments[key];
          try
          {
              transformer.setParameter(key.ToString(), value);
          }
          catch (Exception spe)
          {
                Console.WriteLine(spe.Message);
          }
     }
 }
</code>```

To remind: putting the headerFooter.xsl in the docVersion folder all works. It seems there is a problem in stepping back ( ../ ).

答:
Finally I have got the answer myself:

The point is to write its own URIResolver! Here is my version/way:

```<code>public void createPDF(...) {
   ...
   xmlToPdfInfo.Resolver = new XmlResourceResolver(...);
   xmlToPdfInfo.XslPath = getPathToMyStyleSheet();
   xmlToPdfInfo.IncludedDocsList = GetIncludedDocsList();

   Utils.XmlToPdf(xmlToPdfInfo, outputStream);
}

protected SortedList GetIncludedDocsList()
{
    SortedList sortedList = new SortedList();
    sortedList.Add("headerFooter.xsl", BasePath() + ".common.headerFooter.xsl");
    ...
    return sortedList;
}
</code>```

```<code>public class Utils
{
    private static XmlResourceResolver resolver;
    private static SortedList includedDocsList;

    /// <summary>Gets a PDF as stream from an xml-file, rendered by an xsl stylesheet</summary>
    /// <param name="xmlToPdfInfo">Contains all input information</param>
    /// <param name="outputStream">resulting PDF as a stream</param>
    public static void XmlToPdf(XmlToPdfInfo xmlToPdfInfo, OutputStream outputStream)
    {
        resolver = xmlToPdfInfo.Resolver;
        includedDocsList = xmlToPdfInfo.IncludedDocsList;
        ...
    }

    public class VgUriResolver : URIResolver
    {
        /// <summary>Gets the embedded file for the UriResolver</summary>
        /// <param name="href">relative path to the file (the path that has been put in <xsl:include>)</param>
        /// <param name="baseUri">base path</param>
        /// <returns>The embedded source </returns>
        public Source resolve(String href, String baseUri)
        {
            if (includedDocsList != null)
            {
                IList keys = includedDocsList.GetKeyList();
                String hrefFilename = Path.GetFileName(href);

                foreach (var key in keys)
                {
                    String pfad = (string) includedDocsList[key];
                    String filename = (String) key;

                    try
                    {
                        // "hard-match": if by chance we can get the file
                        // by the real resource path.
                        if (pfad.Equals(href))
                        {
                            byte[] bArr = ReadToEnd(resolver.GetManifestResourceStream(pfad));
                            return new StreamSource(new ByteArrayInputStream(bArr));
                        }

                        // "soft-match": looks for the filenames without any path.
                        // Attention: works only fine if you **don't** have to include files
                        // with same name (different path)
                        if (filename.Equals(hrefFilename))
                        {
                            byte[] bArr = ReadToEnd(resolver.GetManifestResourceStream(pfad));
                            return new StreamSource(new ByteArrayInputStream(bArr));
                        }
                    }
                    catch (Exception)
                    {
                        try
                        {
                            return readFromFileStream(href);
                        }
                        catch (Exception)
                        {
                            return readFromFileStream(hrefFilename);
                        }
                    }
                }
            }
            return new StreamSource(new StringReader(href));
        }
    }

}
</code>```

In fact then what you write in  is more a key/placeholder to find the real file with the own URIResolver.

Well...

Body:
My C# program has to generate different PDF documents in different versions. The basic header and footer are identical. So I would like to put them in a separate xsl.

Here the folder structure I like to have:

/common/headerFooter.xsl
/docVersion1/doc1.xsl
/docVersion1/doc2.xsl
...
/docVersion2/doc1a.xsl
/docVersion2/doc2a.xsl
...

So in fact the include in e.g. doc1.xsl should work like:

<xsl:include href="../common/headerFooter.xsl"/>

But I get the following error:

[Fatal Error] :1:1 Content is not allowed in prolog.
System-ID unknown; Zeilennummer1; Spaltennummer1; org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

Okay - first idea would be about BOM etc., but no. The files are perfectly okay (!).

So I made this try:

/docVersion1/headerFooter.xsl
/docVersion1/doc1.xsl
/docVersion1/doc2.xsl
...
/docVersion2/headerFooter.xsl
/docVersion2/doc1a.xsl
/docVersion2/doc2a.xsl
...

And in the doc1.xsl (etc.):

<xsl:include href="headerFooter.xsl"/>

This one functioned... (!?!?)

Where is the problem?

The relative path in the first attempt is correct. Also Visual Studio tells it. And I think it would be quite strange to put a copy of the headerFooter.xsl in each docVersion-folder.

Recent code:

// xmlToPdfInfo holds all important information about the stylesheets.
// xmlToPdfInfo.XslPath : path to the doc_.xsl-files
java.io.File xsltfile = new java.io.File(xmlToPdfInfo.XslPath);

StreamSource streamSource = new StreamSource(xsltfile.getAbsoluteFile());

// ERROR LINE:
Transformer transformer = factory.newTransformer(streamSource);
// It seems there is already an analyse for all includes and it fails to
// get the relativ path correctly.
// No chance to put additional information e.g. about the path using
// parameters.

// Set the value of a <param> in the stylesheet);
if (xmlToPdfInfo.Arguments != null)
{
     IList keys = xmlToPdfInfo.Arguments.GetKeyList();
     foreach (var key in keys)
     {
          Object value = xmlToPdfInfo.Arguments[key];
          try
          {
              transformer.setParameter(key.ToString(), value);
          }
          catch (Exception spe)
          {
                Console.WriteLine(spe.Message);
          }
     }
 }

To remind: putting the headerFooter.xsl in the docVersion folder all works. It seems there is a problem in stepping back ( ../ ).

Body:
Finally I have got the answer myself:

The point is to write its own URIResolver! Here is my version/way:

public void createPDF(...) {
   ...
   xmlToPdfInfo.Resolver = new XmlResourceResolver(...);
   xmlToPdfInfo.XslPath = getPathToMyStyleSheet();
   xmlToPdfInfo.IncludedDocsList = GetIncludedDocsList();

   Utils.XmlToPdf(xmlToPdfInfo, outputStream);
}

protected SortedList GetIncludedDocsList()
{
    SortedList sortedList = new SortedList();
    sortedList.Add("headerFooter.xsl", BasePath() + ".common.headerFooter.xsl");
    ...
    return sortedList;
}

public class Utils
{
    private static XmlResourceResolver resolver;
    private static SortedList includedDocsList;

    /// <summary>Gets a PDF as stream from an xml-file, rendered by an xsl stylesheet</summary>
    /// <param name="xmlToPdfInfo">Contains all input information</param>
    /// <param name="outputStream">resulting PDF as a stream</param>
    public static void XmlToPdf(XmlToPdfInfo xmlToPdfInfo, OutputStream outputStream)
    {
        resolver = xmlToPdfInfo.Resolver;
        includedDocsList = xmlToPdfInfo.IncludedDocsList;
        ...
    }

    public class VgUriResolver : URIResolver
    {
        /// <summary>Gets the embedded file for the UriResolver</summary>
        /// <param name="href">relative path to the file (the path that has been put in <xsl:include>)</param>
        /// <param name="baseUri">base path</param>
        /// <returns>The embedded source </returns>
        public Source resolve(String href, String baseUri)
        {
            if (includedDocsList != null)
            {
                IList keys = includedDocsList.GetKeyList();
                String hrefFilename = Path.GetFileName(href);

                foreach (var key in keys)
                {
                    String pfad = (string) includedDocsList[key];
                    String filename = (String) key;

                    try
                    {
                        // "hard-match": if by chance we can get the file
                        // by the real resource path.
                        if (pfad.Equals(href))
                        {
                            byte[] bArr = ReadToEnd(resolver.GetManifestResourceStream(pfad));
                            return new StreamSource(new ByteArrayInputStream(bArr));
                        }

                        // "soft-match": looks for the filenames without any path.
                        // Attention: works only fine if you **don't** have to include files
                        // with same name (different path)
                        if (filename.Equals(hrefFilename))
                        {
                            byte[] bArr = ReadToEnd(resolver.GetManifestResourceStream(pfad));
                            return new StreamSource(new ByteArrayInputStream(bArr));
                        }
                    }
                    catch (Exception)
                    {
                        try
                        {
                            return readFromFileStream(href);
                        }
                        catch (Exception)
                        {
                            return readFromFileStream(hrefFilename);
                        }
                    }
                }
            }
            return new StreamSource(new StringReader(href));
        }
    }

}

In fact then what you write in  is more a key/placeholder to find the real file with the own URIResolver.

Well...


问:
Passing arguments to another controller in appcelerator
I am trying to implement a list view in Appcelerator. On the click event of a list item, a new controller should appear and according to the item index and the  URL mentioned in the list item, the video should auto play in the new controller. Every list item has a different URL that should play on the click event of that list item.
I have implemented the list view and am unable to figure out how to pass the argument e of the call back function to another controller, for it to recognize it and play the appropriate video.</p>

答:
I do not yet understand your whole usecase, but usually you pass arguments to a new Controller via a dictionary in the Constructor:

index.js

```<code>var myCtrl = Alloy.createController("MyController", {
    //put your arguments here
});
</code>```

You can recieve the args in the created controller by using $.args

if you create the Controller via require in the XML you have to call a setter.

index.xml

```<code><Alloy>
   <require src="MyController" id="myCtrl"/>
</Alloy>
</code>```

index.js

```<code>$.myCtrl.setArgs({
    //put your arguments here
})
</code>```

MyController.js

```<code>$.setArgs = function(args){
    //handleNewArgs
}
</code>```

Body:
I do not yet understand your whole usecase, but usually you pass arguments to a new Controller via a dictionary in the Constructor:

index.js

var myCtrl = Alloy.createController("MyController", {
    //put your arguments here
});

You can recieve the args in the created controller by using $.args

if you create the Controller via require in the XML you have to call a setter.

index.xml

<Alloy>
   <require src="MyController" id="myCtrl"/>
</Alloy>

index.js

$.myCtrl.setArgs({
    //put your arguments here
})

MyController.js

$.setArgs = function(args){
    //handleNewArgs
}


问:
How to prevent resolve in angular2 router?
Is there any way to prevent resolve on router if only parameters on that router are changed?

For example, I have this route config.

```<code>{path:'home/:status', component:HomeComponent,pathMatch:'full',resolve:{ actionList : HomeActionListResolve}}
</code>```

The resolve here returns full data set and the component just needs to filter the data based on status like (active, completed, etc)parameter.

What i am trying to achieve is that, if the user is landing on this URL for first time, then resolve should be called, so that it can fetch data.

But if user is changing only status, then resolve should not be called OR even if it is called, then it should not make HTTP request to get the same data again and again.

Can someone please suggest a way to achieve this?

Thanks for the help in advance.

答:
```<code>@Injectable()
export class ResolveFactory implements Resolve<any> {

  url: string[];

  constructor() {

  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
    // get the snapshot from activatedroutesnapshot
    let urlStatus= route.url[0].path;
    or
    let urlStatus = state.url;

    if(url.contains(split url to get the status){
         return false;
      } else {
        do your work call service and add the status to the URL[] in Resolve
      }
    }
  }
</code>```

Body:
Is there any way to prevent resolve on router if only parameters on that router are changed?

For example, I have this route config.

{path:'home/:status', component:HomeComponent,pathMatch:'full',resolve:{ actionList : HomeActionListResolve}}

The resolve here returns full data set and the component just needs to filter the data based on status like (active, completed, etc)parameter.

What i am trying to achieve is that, if the user is landing on this URL for first time, then resolve should be called, so that it can fetch data.

But if user is changing only status, then resolve should not be called OR even if it is called, then it should not make HTTP request to get the same data again and again.

Can someone please suggest a way to achieve this?

Thanks for the help in advance.


问:
There are errors when I install django by git?
I install django through :

git clone git://github.com/django/django.git

pip install -e django/

I use Ubuntu 16.04.

But some errors occur :

```<code>Obtaining file:///home/leo/django
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/leo/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 60, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /home/leo/django/
</code>```

How to fix this ?
Thank you.

答:
This because django version you have needs python3 interpreter. so try to run the same command using pip3

To install pip3
sudo apt-get -y install python3-pip

then run

pip3 install -e django/

Body:
I install django through :

git clone git://github.com/django/django.git

pip install -e django/

I use Ubuntu 16.04.

But some errors occur :

Obtaining file:///home/leo/django
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/leo/django/setup.py", line 32, in <module>
        version = __import__('django').get_version()
      File "django/__init__.py", line 1, in <module>
        from django.utils.version import get_version
      File "django/utils/version.py", line 60, in <module>
        @functools.lru_cache()
    AttributeError: 'module' object has no attribute 'lru_cache'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /home/leo/django/

How to fix this ?
Thank you.


问:
What is the equivalent of Javascript function closure in Java?
Although Javascript is not like Java, still what is the equivalent of a Javascript function closure in java ? And why do we need closures ?

This is my understanding
1. Private and protected variables in java are accessed by all the methods in that class.
2. Is there a way in which we can increment a private variable giving access to only one method in a class in Java ?
3. If the answer to point 2 is NO, then why is such a requirement satisfied by closures in JavaScript ?
4. Where can we face such a requirement as in point 2 above ?

答:
In java, you dont need "closure". All that you have in a function is only for this function, you should try dont use static for everything.

Java is OO, a variable in a object can be accesed by all methods from this Object. If you dont want other object acces to it, use "private" tag.

```<code>//Class
public class HelloWorld(){
  private int var1;
  public String var2;

  // Constructor
  public HelloWorld(){
  }

  public void function1(){
    //here you can use var1 and var2.
  }

  private void function2(){
    //here you can use var1 and var2.
  }

  // If you have a parameter with same name, you should use this
  private void  function3(int var1){
    // this.var1 object variable
    // var1 method variable
  }
}

//From another object:
public class ByeWorld(){

  private HelloWorld anInstanceOfHelloWorld;

  public ByeWorld(){
    anInstanceOfHelloWorld = new HelloWorld();

    // var2 is public you can use it (NO RECOMENDABLE)
    anInstanceOfHelloWorld.var2;
    anInstanceOfHelloWorld.function1();

    // YOU CANT
    // anInstanceOfHelloWorld.var1 // is private
    // anInstanceOfHelloWorld.function2() // is private
    //...
  }
}
</code>```

I hope this help you something.

Body:
In java, you dont need "closure". All that you have in a function is only for this function, you should try dont use static for everything.

Java is OO, a variable in a object can be accesed by all methods from this Object. If you dont want other object acces to it, use "private" tag.

//Class
public class HelloWorld(){
  private int var1;
  public String var2;

  // Constructor
  public HelloWorld(){
  }

  public void function1(){
    //here you can use var1 and var2.
  }

  private void function2(){
    //here you can use var1 and var2.
  }

  // If you have a parameter with same name, you should use this
  private void  function3(int var1){
    // this.var1 object variable
    // var1 method variable
  }
}

//From another object:
public class ByeWorld(){

  private HelloWorld anInstanceOfHelloWorld;

  public ByeWorld(){
    anInstanceOfHelloWorld = new HelloWorld();

    // var2 is public you can use it (NO RECOMENDABLE)
    anInstanceOfHelloWorld.var2;
    anInstanceOfHelloWorld.function1();

    // YOU CANT
    // anInstanceOfHelloWorld.var1 // is private
    // anInstanceOfHelloWorld.function2() // is private
    //...
  }
}

I hope this help you something.


问:
Unable to move row from one datatable to another
I have asked a question previously based on the errors of this code. However, after the suggestions given, there is no more error. However, the data from the row in queue table would not move to the the missedQueue table.

I'm not sure why it won't work :(

this is my code:

```<code>        DataSet queue = DBMgr.GetDataSet("SELECT * FROM queue");
        DataTable missedQueue = queue.Tables[0].Clone();

        DataRow dr = queue.Tables[0].NewRow();
        for (int i = 0; i < queue.Tables[0].Columns.Count; i++)
        {
           dr[queue.Tables[0].Columns[i].ColumnName] = queue.Tables[0].Rows[0][i];
        }

        missedQueue.Rows.Add(dr.ItemArray);

    }
</code>```

答:
Your DataRow should be of missedQueue table and add the row inside loop like

```<code>    DataRow dr = null;
    for (int i = 0; i < queue.Tables[0].Columns.Count; i++)
    {
       dr = missedQueue.NewRow();
       dr[queue.Tables[0].Columns[i].ColumnName] = queue.Tables[0].Rows[0][i];
       missedQueue.Rows.Add(dr);
    }
</code>```

Body:
I have asked a question previously based on the errors of this code. However, after the suggestions given, there is no more error. However, the data from the row in queue table would not move to the the missedQueue table.

I'm not sure why it won't work :(

this is my code:

        DataSet queue = DBMgr.GetDataSet("SELECT * FROM queue");
        DataTable missedQueue = queue.Tables[0].Clone();

        DataRow dr = queue.Tables[0].NewRow();
        for (int i = 0; i < queue.Tables[0].Columns.Count; i++)
        {
           dr[queue.Tables[0].Columns[i].ColumnName] = queue.Tables[0].Rows[0][i];
        }

        missedQueue.Rows.Add(dr.ItemArray);

    }

Body:
Your DataRow should be of missedQueue table and add the row inside loop like

    DataRow dr = null;
    for (int i = 0; i < queue.Tables[0].Columns.Count; i++)
    {
       dr = missedQueue.NewRow();
       dr[queue.Tables[0].Columns[i].ColumnName] = queue.Tables[0].Rows[0][i];
       missedQueue.Rows.Add(dr);
    }


问:
disabling children of a JPanel
Suppose I have a hierarchy like this:

```<code>JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...
</code>```

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?

答:
You can put a glass pane over the panel to have it intercept the events.

http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html

Title: disabling children of a JPanel

Body:
Suppose I have a hierarchy like this:

JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?


问:
Granular error reporting in PHP
I am not sure how to pose this question. Sorry if this is already asked somewhere else: I want to log PHP errors on screen and warnings and above in a log file. Is there a way in PHP itself to set this or do I need to program a class as error handler that decides where to log?</p>

答:
You may want to use set_error_handler(). You can catch the level of an error, therefore decide whether to show up or log to file.

FYI, php error handling

Title: Granular error reporting in PHP


问:
Unit test is incorrectly executing code from the launch view controller
I have a simple struct as below which is part of an iOS Application:

```<code>struct Country: JSONObject {
    let name: String!
    let code: String!

    static let nameKey = "name"
    static let codeKey = "dial_code"

    init?(_ json: [String: AnyObject]) throws {
        guard let name = json[Country.nameKey] as? String else {
           throw JSONError.InvalidTypeForKey(key: Country.nameKey)
        }

        guard let code = json[Country.codeKey] as? String else {
            throw JSONError.InvalidTypeForKey(key: Country.codeKey)
        }

        self.name = name
        self.code = code
    }
}
</code>```

I wrote a unit test to test initialisation of this class:

```<code>func testCorrectInitialisationOfCountry() {
    let countryDict = [Country.nameKey: "England", Country.codeKey: "+44"]

    do {
        let country = try Country(countryDict)!
        XCTAssert(countryDict[Country.nameKey] == country.name, "The country name does not match")
        XCTAssert(countryDict[Country.codeKey] == country.code, "The country code does not match")
    }
    catch _ {
        print("Initialisation of country failed with an exception")
    }
}
</code>```

The problem I am facing is this struct is initialised several times in the viewDidLoad() method in the first view controller of my app.

For some reason, that viewDidLoad() method is being called when I run my tests and generating incorrect code coverage because of that. The picture below shows the unit test stats generated by Xcode.

The numbers "241" should actually be just "1". The other 240 times, that line is being executed from the launch view controller which is not under test.

How can I stop the view controller code from executing?

Thanks in advance.

答:
You should use the setUp method (inside your unit test class) which is invoked AFTER the viewDidLoad.

Override this method to customize the initial state for all tests in the test case.

This way, you can reset whatever you need just before your test methods execute.

For example, I needed to reset a singleton that was invoked via a view controller. Note that you can reset between each method via the tearDown method:

called once after each test completes. Override this method to perform any per-test cleanup.

Body:
I have a simple struct as below which is part of an iOS Application:

struct Country: JSONObject {
    let name: String!
    let code: String!

    static let nameKey = "name"
    static let codeKey = "dial_code"

    init?(_ json: [String: AnyObject]) throws {
        guard let name = json[Country.nameKey] as? String else {
           throw JSONError.InvalidTypeForKey(key: Country.nameKey)
        }

        guard let code = json[Country.codeKey] as? String else {
            throw JSONError.InvalidTypeForKey(key: Country.codeKey)
        }

        self.name = name
        self.code = code
    }
}

I wrote a unit test to test initialisation of this class:

func testCorrectInitialisationOfCountry() {
    let countryDict = [Country.nameKey: "England", Country.codeKey: "+44"]

    do {
        let country = try Country(countryDict)!
        XCTAssert(countryDict[Country.nameKey] == country.name, "The country name does not match")
        XCTAssert(countryDict[Country.codeKey] == country.code, "The country code does not match")
    }
    catch _ {
        print("Initialisation of country failed with an exception")
    }
}

The problem I am facing is this struct is initialised several times in the viewDidLoad() method in the first view controller of my app.

For some reason, that viewDidLoad() method is being called when I run my tests and generating incorrect code coverage because of that. The picture below shows the unit test stats generated by Xcode.

The numbers "241" should actually be just "1". The other 240 times, that line is being executed from the launch view controller which is not under test.

How can I stop the view controller code from executing?

Thanks in advance.


问:
VueJS: Redirecting between two pages
I use Firebase with VueJS (and VueRouter).

I have a problem with redirecting. I want to redirect between two pages. The first page is used for authentication and the second one for content that should only be visible to logged-in users.

My state holds the firebase user key (which will be populated through a mutation, that calls firebase):

```<code>state: {
  user: { key: null }
}
</code>```

The authentication page these lines:

```<code>beforeCreate() {
  if (this.$store.state.user.key !== null) {
    this.$router.replace('/')
  }
}
</code>```

And the secret page these:

```<code>beforeCreate() {
  if (this.$store.state.user.key === null) {
    this.$router.replace('/new')
  }
}
</code>```

But: the redirect from the authentication page to the secret page doesn't take place.

My Vue-dev-tools show that the user-key is set.

What could be the solution to this problem?

EDIT:

This is the mutation that calls Firebase and sets the user-key:

```<code>updateSession(state) {
  auth.onAuthStateChanged((user) => {
    if (user) {
      state.user.key = user.uid
    }
  })
}
</code>```

Here is the action:

```<code>UPDATE_SESSION({ commit }) {
  commit('updateSession')
}
</code>```

I call the action in my root component (App.vue):

```<code>beforeCreate() {
  this.$store.dispatch('UPDATE_SESSION')
}
</code>```

EDIT 2:

Now my routes array:

```<code>routes: [
  { path: '/', component: Secret },
  { path: '/new', component: Authentication }
]
</code>```

答:
As per the conversation we had in the comments looks like you require this:

store.dispatch can handle Promise returned by the triggered action handler and it also returns Promise. See docs.

So you can setup the login action to retirn a promise like this:

```<code>a_logInUser: ({state, commit}, userInput) => {
    return new Promise((resolve, reject) => {
        firebase.auth().signInWithEmailAndPassword(userInput.email, userInput.paswword);
        resolve();
    });
}
</code>```

Then in your authentication page where you tale the login input details and click the login button , set this up as the click handler of your login button

```<code>loginUser(){
    this.$store.dispatch('a_logInUser', {email: this.email, password: this.password})
        .then((result) => {
            this.$router.replace('/');
            }, (err) => {
                // stay on this pageS
                //handle login error
        });
    }
}
</code>```

Title: VueJS: Redirecting between two pages

Body:
I use Firebase with VueJS (and VueRouter).

I have a problem with redirecting. I want to redirect between two pages. The first page is used for authentication and the second one for content that should only be visible to logged-in users.

My state holds the firebase user key (which will be populated through a mutation, that calls firebase):

state: {
  user: { key: null }
}

The authentication page these lines:

beforeCreate() {
  if (this.$store.state.user.key !== null) {
    this.$router.replace('/')
  }
}

And the secret page these:

beforeCreate() {
  if (this.$store.state.user.key === null) {
    this.$router.replace('/new')
  }
}

But: the redirect from the authentication page to the secret page doesn't take place.

My Vue-dev-tools show that the user-key is set.

What could be the solution to this problem?

EDIT:

This is the mutation that calls Firebase and sets the user-key:

updateSession(state) {
  auth.onAuthStateChanged((user) => {
    if (user) {
      state.user.key = user.uid
    }
  })
}

Here is the action:

UPDATE_SESSION({ commit }) {
  commit('updateSession')
}

I call the action in my root component (App.vue):

beforeCreate() {
  this.$store.dispatch('UPDATE_SESSION')
}

EDIT 2:

Now my routes array:

routes: [
  { path: '/', component: Secret },
  { path: '/new', component: Authentication }
]

Body:
As per the conversation we had in the comments looks like you require this:

store.dispatch can handle Promise returned by the triggered action handler and it also returns Promise. See docs.

So you can setup the login action to retirn a promise like this:

a_logInUser: ({state, commit}, userInput) => {
    return new Promise((resolve, reject) => {
        firebase.auth().signInWithEmailAndPassword(userInput.email, userInput.paswword);
        resolve();
    });
}

Then in your authentication page where you tale the login input details and click the login button , set this up as the click handler of your login button

loginUser(){
    this.$store.dispatch('a_logInUser', {email: this.email, password: this.password})
        .then((result) => {
            this.$router.replace('/');
            }, (err) => {
                // stay on this pageS
                //handle login error
        });
    }
}


问:
Can you explain me how does this work?
```<code>df = df.loc[-df['Retention time (min)'] < 0]
</code>```

Does this mean that it is removing the row where retention time is less than 0 .

答:
It is called boolean indexing.

Simply filter data rows by condition, here:

```<code>-df['Retention time (min)'] < 0
</code>```

loc is not necessary:

```<code>df = df[-df['Retention time (min)'] < 0]
</code>```

But if need filter also some column loc is necessary:

```<code>df = df.loc[-df['Retention time (min)'] < 0, 'col1']
</code>```

Sample:

```<code>df = pd.DataFrame({'Retention time (min)':[-1,2,3,-6,4,5],
                   'b':[4,5,4,5,5,4]})

print (df)
   Retention time (min)  b
0                    -1  4
1                     2  5
2                     3  4
3                    -6  5
4                     4  5
5                     5  4

df1 = df[-df['Retention time (min)'] < 0]
print (df1)
   Retention time (min)  b
1                     2  5
2                     3  4
4                     4  5
5                     5  4

df2 = df.loc[-df['Retention time (min)'] < 0, 'b']
print (df2)
1    5
2    4
4    5
5    4
Name: b, dtype: int64
</code>```

And it is same as:

```<code>df1 = df[df['Retention time (min)'] > 0]
print (df1)
   Retention time (min)  b
1                     2  5
2                     3  4
4                     4  5
5                     5  4

df2 = df.loc[df['Retention time (min)'] > 0, 'b']
print (df2)
1    5
2    4
4    5
5    4
Name: b, dtype: int64
</code>```

Title: Can you explain me how does this work?

Body:
df = df.loc[-df['Retention time (min)'] < 0]

Does this mean that it is removing the row where retention time is less than 0 .

Body:
It is called boolean indexing.

Simply filter data rows by condition, here:

-df['Retention time (min)'] < 0

loc is not necessary:

df = df[-df['Retention time (min)'] < 0]

But if need filter also some column loc is necessary:

df = df.loc[-df['Retention time (min)'] < 0, 'col1']

Sample:

df = pd.DataFrame({'Retention time (min)':[-1,2,3,-6,4,5],
                   'b':[4,5,4,5,5,4]})

print (df)
   Retention time (min)  b
0                    -1  4
1                     2  5
2                     3  4
3                    -6  5
4                     4  5
5                     5  4

df1 = df[-df['Retention time (min)'] < 0]
print (df1)
   Retention time (min)  b
1                     2  5
2                     3  4
4                     4  5
5                     5  4

df2 = df.loc[-df['Retention time (min)'] < 0, 'b']
print (df2)
1    5
2    4
4    5
5    4
Name: b, dtype: int64

And it is same as:

df1 = df[df['Retention time (min)'] > 0]
print (df1)
   Retention time (min)  b
1                     2  5
2                     3  4
4                     4  5
5                     5  4

df2 = df.loc[df['Retention time (min)'] > 0, 'b']
print (df2)
1    5
2    4
4    5
5    4
Name: b, dtype: int64


问:
Regex that allows 3-20 digits and must end with 00
I have a regex ".*00$" which restricts that the input must be ending with 00. How can I improve this to add a max length of 20 also. So:

100 => valid,

00 = > invalid,

12345678900 => valid,

111111111111111111100 = > 21 digits - invalid.

答:
Try this :

```<code>^[1-9][0-9]{0,17}00$
</code>```

The first [] will ensure it doesn't start by 0.

Body:
Try this :

^[1-9][0-9]{0,17}00$

The first [] will ensure it doesn't start by 0.