问:
Getting specific fields' values of a text using awk, sed, and grep
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

```<code>{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}
</code>```

答:
jq is the right tool for processing JSON data:

getting all name key values:

```<code>jq '[.cast[], .crew[] | .name]' file
</code>```

The output:

```<code>[
  "Brian O'Halloran",
  "Jason Mewes",
  "Jeff Anderson",
  "Kevin Smith",
  "Richard J. Gasparian",
  "Tristin Cole",
  "Nadia Vurbenova",
  "Simon Rodgers",
  "Kevin Smith",
  "Harvey Weinstein",
  "Bob Weinstein"
]
</code>```

To get just a list of strings, use the following:

```<code>jq '.cast[], .crew[] | .name' file
</code>```

The output:

```<code>"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"
</code>```

To get just a list of unquoted " strings, add the -r (--raw-output) option:

```<code>jq -r '.cast[], .crew[] | .name' file
</code>```

Body:
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}

Body:
jq is the right tool for processing JSON data:

getting all name key values:

jq '[.cast[], .crew[] | .name]' file

The output:

[
  "Brian O'Halloran",
  "Jason Mewes",
  "Jeff Anderson",
  "Kevin Smith",
  "Richard J. Gasparian",
  "Tristin Cole",
  "Nadia Vurbenova",
  "Simon Rodgers",
  "Kevin Smith",
  "Harvey Weinstein",
  "Bob Weinstein"
]

To get just a list of strings, use the following:

jq '.cast[], .crew[] | .name' file

The output:

"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"

To get just a list of unquoted " strings, add the -r (--raw-output) option:

jq -r '.cast[], .crew[] | .name' file


来源: stackexchange

问:
Unicode sequence resulting in multiple symbols
I am making a picklist of emoji, but some unicode sequences (whenever gender is concerned) result in two symbols, instead of one.

For example number 987 of the Unicode list: & #x1F3CC;& #x1F3FB;& #x200D;& #x2640;& #xFE0F; (without the spaces) results in a golfer and a female symbol. Is it possible to enter HTML code that renders the same single symbol as shown in the Unicode list?

答: Meanwhile I discovered that this has to do with font-family and browser differences. When you copy a symbol from the unicode list in Google Chrome, the pasted HTML code contains a span with a style attribute. With Microsoft Egde, the span element is not present.</p>

ContentLicense: CC BY-SA 3.0


问:
Spring controller getting bodyRequest null
I am facing a problem while trying to process a POST request via POSTMAN.
In my controller I have :

```<code>@ApiOperation(value = "xxxx", notes = "xxxx", response =
    String.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={ "saveCourse", })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "successful operation", response =
String.class),
    @ApiResponse(code = 404, message = "Not found", response =
String.class),
    @ApiResponse(code = 405, message = "Invalid input", response =
String.class),
    @ApiResponse(code = 500, message = "Internal Server Error", response =
String.class),
    @ApiResponse(code = 200, message = "unexpected error", response =
String.class) })
@RequestMapping(value = "/course/saveCourse",
    produces = { "application/json"},
    consumes = { "application/json"},
    method = RequestMethod.POST)
ResponseEntity<String> saveCourse(@ApiParam(value = "xxxxx" ,required=true ) @RequestBody Course coure){
LOG.info(course.toString);
}
</code>```

Class Course :

```<code>public class Course  implements Serializable {
/**
 *
 */
private static final long serialVersionUID = 1L;

@JsonProperty("prof")
private Prof prof = null;

@JsonProperty("students")
private List<Strudent> students = new ArrayList<Strudent>();

// getters & setters
// ...
}
</code>```

class Prof :

```<code>public class Prof  implements Serializable {
  @JsonProperty("profLastName")
  private String profLastName = null;

  @JsonProperty("profFirstName")
  private String profFirstName = null;

  @JsonProperty("age")
  private int age = null;

  // getters & setters
}
</code>```

class Student :

```<code>public class Student  implements Serializable {
  @JsonProperty("studentId")
  private String studentId = null;

  @JsonProperty("studentName")
  private String studentName = null;

  @JsonProperty("studAge")
  private int studAge = null;

  // getters & setters
  // ...
}
</code>```

in POSTMAN I am sending a POST request with the header :

```<code>Content-Type : application/json
</code>```

the body :

```<code>{
    "prof": {
         "profLastName":"test",
         "profFirstName":"test",
         "age":"30"
    },
    "students" :[
    "{'studentId':'0','studentName':'','studAge':'00'}",
    "{'studentId':'2','studentName':'','studAge':'21'}",
    "{'studentId':'4','studentName':'','studAge':'40'}",
    "{'studentId':'6','studentName':'','studAge':'60'}"
    ]
}
</code>```

When I process the request I am getting the RequestBody null :

[http-nio-xxxx-exec-4] INFO com.test.myControllerIml - class Course {
      prof: null
      students: []
  }

答:
you request body is wrong
you should use</p>

```<code>{
    "prof": {
         "profLastName":"test",
         "profFirstName":"test",
         "age":"30"
    },
    "students" :[
    {"studentId":"0","studentName":"","studAge":"00"},
    {"studentId":"2","studentName":"","studAge":"21"},
    {"studentId":"4","studentName":"","studAge":"40"},
    {"studentId":"6","studentName":"","studAge":"60"}
    ]
}
</code>```

Body:
I am facing a problem while trying to process a POST request via POSTMAN.
In my controller I have :

@ApiOperation(value = "xxxx", notes = "xxxx", response =
    String.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={ "saveCourse", })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "successful operation", response =
String.class),
    @ApiResponse(code = 404, message = "Not found", response =
String.class),
    @ApiResponse(code = 405, message = "Invalid input", response =
String.class),
    @ApiResponse(code = 500, message = "Internal Server Error", response =
String.class),
    @ApiResponse(code = 200, message = "unexpected error", response =
String.class) })
@RequestMapping(value = "/course/saveCourse",
    produces = { "application/json"},
    consumes = { "application/json"},
    method = RequestMethod.POST)
ResponseEntity<String> saveCourse(@ApiParam(value = "xxxxx" ,required=true ) @RequestBody Course coure){
LOG.info(course.toString);
}

Class Course :

public class Course  implements Serializable {
/**
 *
 */
private static final long serialVersionUID = 1L;

@JsonProperty("prof")
private Prof prof = null;

@JsonProperty("students")
private List<Strudent> students = new ArrayList<Strudent>();

// getters & setters
// ...
}

class Prof :

public class Prof  implements Serializable {
  @JsonProperty("profLastName")
  private String profLastName = null;

  @JsonProperty("profFirstName")
  private String profFirstName = null;

  @JsonProperty("age")
  private int age = null;

  // getters & setters
}

class Student :

public class Student  implements Serializable {
  @JsonProperty("studentId")
  private String studentId = null;

  @JsonProperty("studentName")
  private String studentName = null;

  @JsonProperty("studAge")
  private int studAge = null;

  // getters & setters
  // ...
}

in POSTMAN I am sending a POST request with the header :

Content-Type : application/json

the body :

{
    "prof": {
         "profLastName":"test",
         "profFirstName":"test",
         "age":"30"
    },
    "students" :[
    "{'studentId':'0','studentName':'','studAge':'00'}",
    "{'studentId':'2','studentName':'','studAge':'21'}",
    "{'studentId':'4','studentName':'','studAge':'40'}",
    "{'studentId':'6','studentName':'','studAge':'60'}"
    ]
}

When I process the request I am getting the RequestBody null :

[http-nio-xxxx-exec-4] INFO com.test.myControllerIml - class Course {
      prof: null
      students: []
  }

Body:
you request body is wrong
you should use

{
    "prof": {
         "profLastName":"test",
         "profFirstName":"test",
         "age":"30"
    },
    "students" :[
    {"studentId":"0","studentName":"","studAge":"00"},
    {"studentId":"2","studentName":"","studAge":"21"},
    {"studentId":"4","studentName":"","studAge":"40"},
    {"studentId":"6","studentName":"","studAge":"60"}
    ]
}


问:
Reset checkbox to initial status
As you may know, Reset buttons in a form can not reset checkboxes to their initial status. How can I make that happen either with javascript or PHP or jquery or ...?

Here is the code I have:

```<code><form method="POST">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset"> Reset </button>
<button type="submit"> Submit </button>
</form>
</code>```

答:
Try this:

var resetForm = function(){
    $('#form')[0].reset();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form method="POST" id="form">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset" onclick="resetForm()"> Reset </button>
<button type="submit"> Submit </button>
</form></code>```

Title: Reset checkbox to initial status

Body:
As you may know, Reset buttons in a form can not reset checkboxes to their initial status. How can I make that happen either with javascript or PHP or jquery or ...?

Here is the code I have:

<form method="POST">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset"> Reset </button>
<button type="submit"> Submit </button>
</form>

Body:
Try this:

var resetForm = function(){
    $('#form')[0].reset();
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form method="POST" id="form">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset" onclick="resetForm()"> Reset </button>
<button type="submit"> Submit </button>
</form>


问:
using rails.vim Rake run spec in MacVim, how to get colored output
when using Rake to run a spec, the output in quickfix is not colored, meaning, it doesn't have green for passing specs and red for failing specs. Is this something solvable? Thanks for any hints.</p>

答: According to Tim Pope, the author of rails.vim, not much that can be done about that; Vim doesn't support ANSI color codes.</p>

ContentLicense: CC BY-SA 2.5


问:
How to efficiently search specific values in array using JavaScript
Im wondering how to search big arrays using JavaScript.

Let's say we have an array consisting of elements that represent businesses. There are a couple thousand elements in the array, they are objects that sometimes also have arrays in them.

In each of those elements is a key e.g. called category that looks like this category: ["attr1", "attr2", "attr3"]. Now I only want to find elements of the array that have a category like this:

```<code>category: ["Restaurant"]
</code>```

The problem is that other keys of the elements in the array sometimes also have a property where "Restaurant" is in the name followed by something else e.g. "RestaurantPrice" so

```<code>if(array[i].categories != null &&
array[i].categories.indexOf("Restaurant") != -1) {
    do something
}
</code>```

Would not work properly because it would return all occurences of the word "Restaurant" or am I wrong?

If not how should I search for specific things in an array?

答:
If categories is an array like ["foobar", "foo"]

categories.indexOf("foo") would return 1, foobar would be ignored.

The other question was how to find elements efficient?.

It depends, if your set is static, you can prebuilt and cache some sort of index like:

```<code>var categoriesMap = {
  foobar: [1, 2, 4],
  foo: [1, 5, 7]
}
</code>```

The array would represent the indexes of items, which includes the given categories.

Body:
Im wondering how to search big arrays using JavaScript.

Let's say we have an array consisting of elements that represent businesses. There are a couple thousand elements in the array, they are objects that sometimes also have arrays in them.

In each of those elements is a key e.g. called category that looks like this category: ["attr1", "attr2", "attr3"]. Now I only want to find elements of the array that have a category like this:

category: ["Restaurant"]

The problem is that other keys of the elements in the array sometimes also have a property where "Restaurant" is in the name followed by something else e.g. "RestaurantPrice" so

if(array[i].categories != null &&
array[i].categories.indexOf("Restaurant") != -1) {
    do something
}

Would not work properly because it would return all occurences of the word "Restaurant" or am I wrong?

If not how should I search for specific things in an array?

Body:
If categories is an array like ["foobar", "foo"]

categories.indexOf("foo") would return 1, foobar would be ignored.

The other question was how to find elements efficient?.

It depends, if your set is static, you can prebuilt and cache some sort of index like:

var categoriesMap = {
  foobar: [1, 2, 4],
  foo: [1, 5, 7]
}

The array would represent the indexes of items, which includes the given categories.


问:
How to skip a transaction in replicate(Target system) in Goldengate oracle
Requirement:

Source table contains 5 columns. We are replicating 3 columns on target out of 5.
SEQ_ID is additional column on target.

When update operation is performed on columns which are not in target table,SEQ_ID is increased.
SEQ_ID should increase only when update performed on columns which are present on target.

Enabling unconditional supplemental table level logging on selected columns(ID,AGE,COL1) to be replicated:

Source:
Table name: Test1(ID,AGE,COL1,COL2,COL3)

Target:
Table name: Test1(ID,AGE,COL1,SEQ_ID)

We created a sequence to increse the SEQ_ID when a insert or update happens.

Scenario :
If insert or update happens on source table on these columns (ID,AGE,COL1)  SEQ_ID is incresed,
and if update happens on others columns(COL2,COL3)  SEQ_ID is also getting incremented.

Our Requirement is when update happens on others columns(COL2,COL3) ,SEQ_ID should not get incrementd.
I want to skip the transaction of updates happening on columns(COL2,COL3) .

Source:
Primary extract test_e1
EXTRACT  TEST_e1
USERID DBTUAT_GG,PASSWORD dbt_1234
EXTTRAIL /DB_TRACK_GG/GGS/dirdat/dd
GETUPDATEBEFORES
--IGNOREUPDATES
--IGNOREDELETES
NOCOMPRESSUPDATES
TABLE HARI.TEST1,COLS(ID,AGE,COL1),FILTER (ON UPDATE,IGNORE UPDATE, @STREQ(before.AGE, AGE) = 0);

Datapump test_p1:
EXTRACT TEST_P1
USERID DBTUAT_GG,PASSWORD dbt_1234
RMTHOST 10.24.187.235, MGRPORT 7809,

RMTTRAIL /Trail_files/tt
--PASSTHRU
TABLE DBTUAT_GG.TEST1;

Target:
Target Repicat file:
Edit param test_r

REPLICAT TEST_R
USERID GGPROD,PASSWORD GGPROD_123
SOURCEDEFS ./dirsql/def32.sql
HANDLECOLLISIONS
IGNOREDELETES
INSERTMISSINGUPDATES
MAP HARI.TEST1, TARGET HARI.TEST1, &
SQLEXEC (ID test_num,QUERY "select GGPROD.test_seq.NEXTVAL test_val from dual", NOPARAMS), &
COLMAP(USEDEFAULTS,SEQ_ID=test_num.test_val);

Kindly suggest any possible solutions .

答:
First note: you don't need USERID and PASSWORD in the Pump PRM. The Pump process does not connect to any database.

Actually you have already achieved your goal. You are only replicating the data when AGE is modified. There is a FILTER clause in the Extract PRM file. The ID column should not get changed since this is the PK. The only problem is that your are increasing the SEQ_ID if a delete gets replicated.

Something like that should work:

```<code>ALLOWDUPTARGETMAP

IGNOREDELETES
-- just inserts and updates that change COL1
MAP HARI.TEST1, TARGET HARI.TEST1, &
  SQLEXEC (ID test_num,QUERY "select GGPROD.test_seq.NEXTVAL test_val from dual", NOPARAMS), &
  COLMAP(USEDEFAULTS, SEQ_ID = test_num.test_val);

-- just replicate the delete operations
GETDELETES
IGNOREINSERTS
IGNOREUPDATES
MAP HARI.TEST1, TARGET HARI.TEST1;
GETINSERTS
GETUPDATES
</code>```

Body:
First note: you don't need USERID and PASSWORD in the Pump PRM. The Pump process does not connect to any database.

Actually you have already achieved your goal. You are only replicating the data when AGE is modified. There is a FILTER clause in the Extract PRM file. The ID column should not get changed since this is the PK. The only problem is that your are increasing the SEQ_ID if a delete gets replicated.

Something like that should work:

ALLOWDUPTARGETMAP

IGNOREDELETES
-- just inserts and updates that change COL1
MAP HARI.TEST1, TARGET HARI.TEST1, &
  SQLEXEC (ID test_num,QUERY "select GGPROD.test_seq.NEXTVAL test_val from dual", NOPARAMS), &
  COLMAP(USEDEFAULTS, SEQ_ID = test_num.test_val);

-- just replicate the delete operations
GETDELETES
IGNOREINSERTS
IGNOREUPDATES
MAP HARI.TEST1, TARGET HARI.TEST1;
GETINSERTS
GETUPDATES


问:
Custom sort in multi-level python dictionary
I have a python dictionary data.I am using Python 3.The dictionary is like bellow:

```<code>dct = {
    "3LHet": {
        "g35": {
            "exon": [
                [
                    "197631",
                    "197742",
                    "-"
                ],
                [
                    "198407",
                    "198470",
                    "-"
                ]

            ],
            "gene": [
                [
                    "197631",
                    "207214",
                    "-"
                ]
            ],
            "CDS": [
                [
                    "197631",
                    "197742",
                    "-"
                ],
                [
                    "198407",
                    "198470",
                    "-"
                ]

            ]
        },
        "g17": {
            "exon": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ],
            "gene": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ],
            "CDS": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ]
        }
    }
}
</code>```

I am accessing the dictionary in the bellow code.

```<code>for scaffold, scaffold_dct in dct.items():
    for gene, gene_dct in scaffold_dct.items():
        print(gene)
        for feature, feature_dct in gene_dct.items():
            print("\t"+feature)
</code>```

output:

```<code>g35
    exon
    gene
    CDS
g17
    exon
    gene
    CDS
</code>```

But I need the output in bellow format. Can someone please help me to solve the problem.

Expected output:

```<code>g17
    gene
    CDS
    exon
g35
   gene
   CDS
   exon
</code>```

答:
You cannot reorder these items since they're dictionaries, but you can order them when printing:

```<code>lookup = {'exon' : 1, 'cds' : 2, 'gene' : 3, }
for key, item in sorted(dct["3LHet"].items()):
    print(key)
    for subkey, subitem in sorted(item.items(), key=lambda x: lookup.get(x[0].lower(), 0)):
        print('  ', subkey)
</code>```

You'll need to keep a lookup dict, so that the inner keys are displayed in the order you want.

Output:

```<code>g17
   gene
   CDS
   exon
g35
   gene
   CDS
   exon
</code>```

If you've more inner keys that need explicit ordering, then just add then to your lookup.

Body:
I have a python dictionary data.I am using Python 3.The dictionary is like bellow:

dct = {
    "3LHet": {
        "g35": {
            "exon": [
                [
                    "197631",
                    "197742",
                    "-"
                ],
                [
                    "198407",
                    "198470",
                    "-"
                ]

            ],
            "gene": [
                [
                    "197631",
                    "207214",
                    "-"
                ]
            ],
            "CDS": [
                [
                    "197631",
                    "197742",
                    "-"
                ],
                [
                    "198407",
                    "198470",
                    "-"
                ]

            ]
        },
        "g17": {
            "exon": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ],
            "gene": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ],
            "CDS": [
                [
                    "2010292",
                    "2011137",
                    "+"
                ]
            ]
        }
    }
}

I am accessing the dictionary in the bellow code.

for scaffold, scaffold_dct in dct.items():
    for gene, gene_dct in scaffold_dct.items():
        print(gene)
        for feature, feature_dct in gene_dct.items():
            print("\t"+feature)

output:

g35
    exon
    gene
    CDS
g17
    exon
    gene
    CDS

But I need the output in bellow format. Can someone please help me to solve the problem.

Expected output:

g17
    gene
    CDS
    exon
g35
   gene
   CDS
   exon

Body:
You cannot reorder these items since they're dictionaries, but you can order them when printing:

lookup = {'exon' : 1, 'cds' : 2, 'gene' : 3, }
for key, item in sorted(dct["3LHet"].items()):
    print(key)
    for subkey, subitem in sorted(item.items(), key=lambda x: lookup.get(x[0].lower(), 0)):
        print('  ', subkey)

You'll need to keep a lookup dict, so that the inner keys are displayed in the order you want.

Output:

g17
   gene
   CDS
   exon
g35
   gene
   CDS
   exon

If you've more inner keys that need explicit ordering, then just add then to your lookup.


问:
adding a row for missing data
Between a date range 2017-02-01 - 2017-02-10, i'm calculating a running balance.
I have days where we have missing data, how would I include these missing dates with the previous days balance ?

Example data:

we are missing data for 2017-02-04,2017-02-05 and 2017-02-06, how would i add a row in the query with the previous balance?
The date range is a parameter, so could change....

Can i use something like the lag function?

答:
I would be inclined to use a recursive CTE and then fill in the values.  Here is one approach using outer apply:

```<code>with dates as (
      select mind as dte, mind, maxd
      from (select min(date) as mind, max(date) as maxd from t) t
      union all
      select dateadd(day, 1, dte), mind, maxd
      from dates
      where dte < maxd
     )
select d.dte, t.balance
from dates d outer apply
     (select top 1 t.*
      from t
      where t.date <= d.dte
      order by t.date desc
     ) t;
</code>```

Title: adding a row for missing data

Body:
I would be inclined to use a recursive CTE and then fill in the values.  Here is one approach using outer apply:

with dates as (
      select mind as dte, mind, maxd
      from (select min(date) as mind, max(date) as maxd from t) t
      union all
      select dateadd(day, 1, dte), mind, maxd
      from dates
      where dte < maxd
     )
select d.dte, t.balance
from dates d outer apply
     (select top 1 t.*
      from t
      where t.date <= d.dte
      order by t.date desc
     ) t;


问:
How to solve 'Error in plot.new() : figure margins too large' in rstudio?
I've read all posts relevant to this problem.But the truth is: if you have lots of variables to plot,this problem still occur.

My laptop resolution is 1080p, I open rstudio and run below script:

```<code>a<-iris[,1:4]
> a<-t(a)
> a<-as.data.frame(a)
> pairs(a)
Error in plot.new() : figure margins too large
</code>```

I  have tried all the solution in this site from similar questions, none is workable.

I really need this plot but cannot get it.How to solve this problem?

答:
The only way I can possibly imagine doing this is (as I think has previously been suggested) sending the output to a PDF file and then using a PDF viewer to look at it.  (My answer is very similar to the answer you got to this question, except that I'm using PDF rather than PNG as output ... tried it for PNG as well, seems to work for 2000x2000 pixels ...)

For smaller/reasonable examples, zooming and/or opening an external graphics window with dev.new() should work ...

```<code>a <- iris[,1:4]
a <- t(a)
a <- as.data.frame(a)
pdf(file="tmp.pdf",width=100,height=100)
pairs(a,gap=0,pch=".")
dev.off()
</code>```

This took about 18 seconds on my laptop and produced a 1.2M PDF file. Here's what the picture looked like when I zoomed all the way out ("fit to window") in my PDF viewer:

If you have 150x150 subplots and want to render each one at 1 cm wide x 1 cm tall (which seems pretty small for viewing any detail), you're either going to need a very high-resolution projector or a large-format (poster) printer.  You could scroll around the image with a PDF viewer, but it doesn't seem very practical ...

Body:
I've read all posts relevant to this problem.But the truth is: if you have lots of variables to plot,this problem still occur.

My laptop resolution is 1080p, I open rstudio and run below script:

a<-iris[,1:4]
> a<-t(a)
> a<-as.data.frame(a)
> pairs(a)
Error in plot.new() : figure margins too large

I  have tried all the solution in this site from similar questions, none is workable.

I really need this plot but cannot get it.How to solve this problem?

Body:
The only way I can possibly imagine doing this is (as I think has previously been suggested) sending the output to a PDF file and then using a PDF viewer to look at it.  (My answer is very similar to the answer you got to this question, except that I'm using PDF rather than PNG as output ... tried it for PNG as well, seems to work for 2000x2000 pixels ...)

For smaller/reasonable examples, zooming and/or opening an external graphics window with dev.new() should work ...

a <- iris[,1:4]
a <- t(a)
a <- as.data.frame(a)
pdf(file="tmp.pdf",width=100,height=100)
pairs(a,gap=0,pch=".")
dev.off()

This took about 18 seconds on my laptop and produced a 1.2M PDF file. Here's what the picture looked like when I zoomed all the way out ("fit to window") in my PDF viewer:

If you have 150x150 subplots and want to render each one at 1 cm wide x 1 cm tall (which seems pretty small for viewing any detail), you're either going to need a very high-resolution projector or a large-format (poster) printer.  You could scroll around the image with a PDF viewer, but it doesn't seem very practical ...


问:
How to split JSON data in Angular 2 and ionic 2
I need to separate the json file data, I create a function to separate the character string but it returns single strings:

"AKERMI ## 1988",
"AKIM DE DUCOR ## 2005", ...

But I want to split this string into fields:

Name: AKERMI

Date: 1988

Name: AKIM DE DUCOR

Date: 2005

test.ts

```<code>  getDataEtalon() {
        return this.data.getEtalon().subscribe(
            data => {
                for (let key in data) {
                    this.etalon = data[key].split('##');
                }
                console.log(this.etalon);
            },
            err => {
                console.log(err);
            }
        );
    }
</code>```

JSON

```<code> {
    0: "AKERMI##1988",
    5: "AKIM DE DUCOR##2005",
    6: "AL FATIH##2003",
    9: "AMER##1984",
    13: "BELAMER##2004",
    15: "CHAHATA##1990",
    20: "CHARH##1999",
    23: "CHEIKH EL ARAB##1990",
    24: "DAHESS##1999",
    35: "DARIKE##1991",
    44: "DARMAN##1998",
    50: "DAYJUR##1991",
    51: "DJARNI DES FORGES##1995",
    55: "DJELMANE##1999",
    77: "DJOURDAN##1999",
    83: "DORMANE##1984",
    103: "FARADJALA##1993",
    105: "GITPEN##1994",
    110: "HAJJAM##1995",
    175: "HAKIM DU BAC##1995",
    180: "HALIM##1995",
    185: "HAMID##1996",
    194: "HAMZA##1995",
    204: "HYRAM##1995",
    206: "ISSAOUI##1996",
    210: "JAMAK##1997",
    213: "JEDEL##1997",
    231: "JESROY DE CHAILLAC##1997",
    232: "KAHLOUN##1998",
    233: "KERBELLA##1992",
    236: "LATHLETH##1999",
    246: "MAJD AL ARAB##2002",
    251: "MAKZAN##1991",
    258: "MANGANELLO##1990",
    259: "MANGUIER DE PIBOUL##1995",
    263: "MAYSOUN##2000",
    266: "MIGYESS##2000",
    269: "MOUSSOUL##2000",
    324: "MUNEEF##2001",
    334: "NADIM##2001",
    336: "NAKKACH##2001",
    337: "NEDJAM LOTOIS##1996",
    338: "NEMROD DU PAON##2001",
    345: "NEZ D'OR##1997",
    346: "NIZAM##1998",
    348: "ORIENT EXPRESS##1995",
    349: "OUAAD##2003",
    350: "PHARAON DES CEDRES##2000",
    351: "RAAD##2003",
    357: "RAEEH##2003",
    358: "RAFII##2003",
    366: "ROUSHAAN##2003",
    371: "SAMIR##1985",
    391: "SARKI D'ESPIENS##1992",
    392: "SAYAF##2004",
    398: "SEMAOU'EL##2004",
    400: "SOUR##1985",
    404: "SULTAN AL BADR##2004",
    405: "TIDJAM LOTOIS##1999",
    433: "TOUWAYSSAN##1986",
    434: "VENT DREDY##1992",
    435: "VIOLET##2001",
    436: "ZEIDOUN##1987"
    }
</code>```

答:
```<code>data.map(car => {
let [name, year] = car.split('##');
return { name, year };
});
</code>```

Will result in an array of objects with a name and a year

Body:
I need to separate the json file data, I create a function to separate the character string but it returns single strings:

"AKERMI ## 1988",
"AKIM DE DUCOR ## 2005", ...

But I want to split this string into fields:

Name: AKERMI

Date: 1988

Name: AKIM DE DUCOR

Date: 2005

test.ts

  getDataEtalon() {
        return this.data.getEtalon().subscribe(
            data => {
                for (let key in data) {
                    this.etalon = data[key].split('##');
                }
                console.log(this.etalon);
            },
            err => {
                console.log(err);
            }
        );
    }

JSON

 {
    0: "AKERMI##1988",
    5: "AKIM DE DUCOR##2005",
    6: "AL FATIH##2003",
    9: "AMER##1984",
    13: "BELAMER##2004",
    15: "CHAHATA##1990",
    20: "CHARH##1999",
    23: "CHEIKH EL ARAB##1990",
    24: "DAHESS##1999",
    35: "DARIKE##1991",
    44: "DARMAN##1998",
    50: "DAYJUR##1991",
    51: "DJARNI DES FORGES##1995",
    55: "DJELMANE##1999",
    77: "DJOURDAN##1999",
    83: "DORMANE##1984",
    103: "FARADJALA##1993",
    105: "GITPEN##1994",
    110: "HAJJAM##1995",
    175: "HAKIM DU BAC##1995",
    180: "HALIM##1995",
    185: "HAMID##1996",
    194: "HAMZA##1995",
    204: "HYRAM##1995",
    206: "ISSAOUI##1996",
    210: "JAMAK##1997",
    213: "JEDEL##1997",
    231: "JESROY DE CHAILLAC##1997",
    232: "KAHLOUN##1998",
    233: "KERBELLA##1992",
    236: "LATHLETH##1999",
    246: "MAJD AL ARAB##2002",
    251: "MAKZAN##1991",
    258: "MANGANELLO##1990",
    259: "MANGUIER DE PIBOUL##1995",
    263: "MAYSOUN##2000",
    266: "MIGYESS##2000",
    269: "MOUSSOUL##2000",
    324: "MUNEEF##2001",
    334: "NADIM##2001",
    336: "NAKKACH##2001",
    337: "NEDJAM LOTOIS##1996",
    338: "NEMROD DU PAON##2001",
    345: "NEZ D'OR##1997",
    346: "NIZAM##1998",
    348: "ORIENT EXPRESS##1995",
    349: "OUAAD##2003",
    350: "PHARAON DES CEDRES##2000",
    351: "RAAD##2003",
    357: "RAEEH##2003",
    358: "RAFII##2003",
    366: "ROUSHAAN##2003",
    371: "SAMIR##1985",
    391: "SARKI D'ESPIENS##1992",
    392: "SAYAF##2004",
    398: "SEMAOU'EL##2004",
    400: "SOUR##1985",
    404: "SULTAN AL BADR##2004",
    405: "TIDJAM LOTOIS##1999",
    433: "TOUWAYSSAN##1986",
    434: "VENT DREDY##1992",
    435: "VIOLET##2001",
    436: "ZEIDOUN##1987"
    }

Body:
data.map(car => {
let [name, year] = car.split('##');
return { name, year };
});

Will result in an array of objects with a name and a year


问:
WebMethods Integration Server pub.client.soapclient changes the request element names
I have an issue with build-in (non accessible) webMethods Integration Server soapClient service. Somehow it changes the request it should send while processing it, renaming parameter items to item.

what is send to the method:

```<code><request>
  <t1>1</t1>
  <operation>op</operation>
  <service>1</service>
  <params>
    <count>1</count>
    <items>
      <key>12</key>
      <value>12</value>
    </items>
  </params>
</request>
</code>```

what request webmethods sends:

```<code><request>
  <t1>1</t1>
  <operation>op</operation>
  <service>1</service>
  <params>
    <count>1</count>
    <item>
      <key>12</key>
      <value>12</value>
    </item>
  </params>
</request>
</code>```

I'd be grateful for any workaround/idea for a solution.

答: I see in your example code that you first create an document named "items", then you map this document to a document list named "items". This is not valid. Please note that the pipeline in IntegrationServer is nothing but a key-value map, and the keys must be unique. That is the reason why you still have a single document named "items" instead of a document list. Rename your document to something like "item", and then use appendToDocumentList to add it to the "items" doc list.

Body:
I have an issue with build-in (non accessible) webMethods Integration Server soapClient service. Somehow it changes the request it should send while processing it, renaming parameter items to item.

what is send to the method:

<request>
  <t1>1</t1>
  <operation>op</operation>
  <service>1</service>
  <params>
    <count>1</count>
    <items>
      <key>12</key>
      <value>12</value>
    </items>
  </params>
</request>

what request webmethods sends:

<request>
  <t1>1</t1>
  <operation>op</operation>
  <service>1</service>
  <params>
    <count>1</count>
    <item>
      <key>12</key>
      <value>12</value>
    </item>
  </params>
</request>

I'd be grateful for any workaround/idea for a solution.


问:
MVC Why unit test controllers
just a Provocative Question

why do you thing we should unit test controllers in MVC why not just write test against models or service layer.

答: The controllers can contain quite a bit of critical functionality.  If your app doesn't have critical logic here, it may not be necessary to unit test quite so heavily.  But I'd at least write a few tests to make sure your routes are set up correctly.</p>

Title: MVC Why unit test controllers


问:
Call a SQL Server stored proc with parameters in PHP
Based on this :

how to execute sql server stored procedure on php?

Tried the following :

```<code>$odbc = odbc_connect($DB1_ODBC,$DB1_USER,$DB1_PWD);  // proven to be fully functionnal
$result = odbc_exec($odbc,"CALL importClient( @name = 'hello',@number = 457)");
</code>```

It does not call the stored procedure, i can't see any error code.

I replaced "CALL by "EXEC but it's not working in either cases.

Otherwise, the stored procedure can be run by using the same credentials to connect to the database, and using this SQL statement :

```<code>EXECUTE [dbo].[importClient] @name = 'hello',@number = 457
</code>```

I couldn't find anything helpful, neither think of another way, and I definitely need the parameters.

答:
```<code>$stmt = odbc_prepare($odbc, "call dbo.importClient(?, ?)");
odbc_execute($stmt, ["hello", 457]);
</code>```

Using a prepared statement will protect your code from SQL injection attacks. Use this when you replace your literal values with variables containing user input.

Body:
Based on this :

how to execute sql server stored procedure on php?

Tried the following :

$odbc = odbc_connect($DB1_ODBC,$DB1_USER,$DB1_PWD);  // proven to be fully functionnal
$result = odbc_exec($odbc,"CALL importClient( @name = 'hello',@number = 457)");

It does not call the stored procedure, i can't see any error code.

I replaced "CALL by "EXEC but it's not working in either cases.

Otherwise, the stored procedure can be run by using the same credentials to connect to the database, and using this SQL statement :

EXECUTE [dbo].[importClient] @name = 'hello',@number = 457

I couldn't find anything helpful, neither think of another way, and I definitely need the parameters.

Body:
$stmt = odbc_prepare($odbc, "call dbo.importClient(?, ?)");
odbc_execute($stmt, ["hello", 457]);

Using a prepared statement will protect your code from SQL injection attacks. Use this when you replace your literal values with variables containing user input.


问:
How to get the script name in Groovy
How do I get the name of the script being executed in Groovy?

It is not a command line argument and hence the args array is not of any help.

答:
I do this for a lot of scripts in a support class, so itsraghz 's answer doesnt work for me.

If you use this.class or getClass() from a support class called by the script, you'll get the support class's name, not the script's name. To get the script's name every time I use:

```<code>// Get the executed script as a (java) File
File scriptFile = new File(getClass().protectionDomain.codeSource.location.path)

// This holds the file name like "myscript.groovy"
def scriptName = scriptFile.getName()

// strip the extension to get "myscript"
def withoutExt = scriptName.take(scriptName.lastIndexOf('.'))
</code>```

Title: How to get the script name in Groovy

Body:
I do this for a lot of scripts in a support class, so itsraghz 's answer doesnt work for me.

If you use this.class or getClass() from a support class called by the script, you'll get the support class's name, not the script's name. To get the script's name every time I use:

// Get the executed script as a (java) File
File scriptFile = new File(getClass().protectionDomain.codeSource.location.path)

// This holds the file name like "myscript.groovy"
def scriptName = scriptFile.getName()

// strip the extension to get "myscript"
def withoutExt = scriptName.take(scriptName.lastIndexOf('.'))


问:
Fragment MyFragment not attached to Activity
I've created a small test app which represents my problem.
I'm using ActionBarSherlock to implement tabs with (Sherlock)Fragments.

My code:
TestActivity.java

```<code>public class TestActivity extends SherlockFragmentActivity {
    private ActionBar actionBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupTabs(savedInstanceState);
    }

    private void setupTabs(Bundle savedInstanceState) {
        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        addTab1();
        addTab2();
    }

    private void addTab1() {
        Tab tab1 = actionBar.newTab();
        tab1.setTag("1");
        String tabText = "1";
        tab1.setText(tabText);
        tab1.setTabListener(new TabListener<MyFragment>(TestActivity.this, "1", MyFragment.class));

        actionBar.addTab(tab1);
    }

    private void addTab2() {
        Tab tab1 = actionBar.newTab();
        tab1.setTag("2");
        String tabText = "2";
        tab1.setText(tabText);
        tab1.setTabListener(new TabListener<MyFragment>(TestActivity.this, "2", MyFragment.class));

        actionBar.addTab(tab1);
    }
}
</code>```

TabListener.java

```<code>public class TabListener<T extends SherlockFragment> implements com.actionbarsherlock.app.ActionBar.TabListener {
    private final SherlockFragmentActivity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);

        // Check if the fragment is already initialized
        if (preInitializedFragment == null) {
            // If not, instantiate and add it to the activity
            SherlockFragment mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(preInitializedFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);

        if (preInitializedFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(preInitializedFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}
</code>```

MyFragment.java

```<code>public class MyFragment extends SherlockFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result){
                getResources().getString(R.string.app_name);
            }

        }.execute();
    }
}
</code>```

I've added the Thread.sleep part to simulate downloading data. The code in the onPostExecute is to simulate use of the Fragment.

When I rotate the screen very fast between landscape and portrait, I get an Exception at the onPostExecute code:

java.lang.IllegalStateException: Fragment MyFragment{410f6060} not
  attached to Activity

I think it's because a new MyFragment has been created in the meantime, and was attached to the Activity before the AsyncTask finished. The code in onPostExecute calls upon a unattached MyFragment.

But how can I fix this?

答:
```<code>if (getActivity() == null) return;
</code>```

works also in some cases. Just breaks the code execution from it and make sure the app not crash

Body:
I've created a small test app which represents my problem.
I'm using ActionBarSherlock to implement tabs with (Sherlock)Fragments.

My code:
TestActivity.java

public class TestActivity extends SherlockFragmentActivity {
    private ActionBar actionBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupTabs(savedInstanceState);
    }

    private void setupTabs(Bundle savedInstanceState) {
        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        addTab1();
        addTab2();
    }

    private void addTab1() {
        Tab tab1 = actionBar.newTab();
        tab1.setTag("1");
        String tabText = "1";
        tab1.setText(tabText);
        tab1.setTabListener(new TabListener<MyFragment>(TestActivity.this, "1", MyFragment.class));

        actionBar.addTab(tab1);
    }

    private void addTab2() {
        Tab tab1 = actionBar.newTab();
        tab1.setTag("2");
        String tabText = "2";
        tab1.setText(tabText);
        tab1.setTabListener(new TabListener<MyFragment>(TestActivity.this, "2", MyFragment.class));

        actionBar.addTab(tab1);
    }
}

TabListener.java

public class TabListener<T extends SherlockFragment> implements com.actionbarsherlock.app.ActionBar.TabListener {
    private final SherlockFragmentActivity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);

        // Check if the fragment is already initialized
        if (preInitializedFragment == null) {
            // If not, instantiate and add it to the activity
            SherlockFragment mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(preInitializedFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        SherlockFragment preInitializedFragment = (SherlockFragment) mActivity.getSupportFragmentManager().findFragmentByTag(mTag);

        if (preInitializedFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(preInitializedFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}

MyFragment.java

public class MyFragment extends SherlockFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result){
                getResources().getString(R.string.app_name);
            }

        }.execute();
    }
}

I've added the Thread.sleep part to simulate downloading data. The code in the onPostExecute is to simulate use of the Fragment.

When I rotate the screen very fast between landscape and portrait, I get an Exception at the onPostExecute code:

java.lang.IllegalStateException: Fragment MyFragment{410f6060} not
  attached to Activity

I think it's because a new MyFragment has been created in the meantime, and was attached to the Activity before the AsyncTask finished. The code in onPostExecute calls upon a unattached MyFragment.

But how can I fix this?

Body:
if (getActivity() == null) return;

works also in some cases. Just breaks the code execution from it and make sure the app not crash


问:
Selenium ChromeDriver not going to url using default user data
It opens in a new window with the default start menu and shows a notification that Chrome is being controlled by automated test software, but it does not go to the url.

```<code>System.setProperty("webdriver.chrome.driver","C:\\Users\\"+System.getProperty("user.name")+"\\chromedriver.exe");

    ChromeOptions options = new ChromeOptions();
    options.setBinary("C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
    options.addArguments("--user-data-dir=C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\User Data\\");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com");
</code>```

What I also tried:

```<code>        System.setProperty("webdriver.chrome.driver","C:\\Users\\"+System.getProperty("user.name")+"\\chromedriver.exe");

    ChromeOptions options = new ChromeOptions();
    options.setBinary("C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
    options.addArguments("--user-data-dir=C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\User Data\\");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new ChromeDriver(capabilities);
    driver.get("https://www.google.com");
</code>```

The exception it gives

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: crashed
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 61.65 seconds

I am using the lastest ChromeDriver 2.30 and Selenium 3.4.0 versions

答:
Found the answer to my own question. It worked when I copied the Default folder from the profile path and moved it somewhere else.</p>
```<code>    ChromeOptions options = new ChromeOptions();
    options.addArguments("user-data-dir=C:/Users/"+System.getProperty("user.name")+"/Desktop/");
    options.addArguments("--start-maximized");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It opens in a new window with the default start menu and shows a notification that Chrome is being controlled by automated test software, but it does not go to the url.

System.setProperty("webdriver.chrome.driver","C:\\Users\\"+System.getProperty("user.name")+"\\chromedriver.exe");

    ChromeOptions options = new ChromeOptions();
    options.setBinary("C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
    options.addArguments("--user-data-dir=C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\User Data\\");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com");

What I also tried:

        System.setProperty("webdriver.chrome.driver","C:\\Users\\"+System.getProperty("user.name")+"\\chromedriver.exe");

    ChromeOptions options = new ChromeOptions();
    options.setBinary("C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
    options.addArguments("--user-data-dir=C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Local\\Google\\Chrome\\User Data\\");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new ChromeDriver(capabilities);
    driver.get("https://www.google.com");

The exception it gives

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: crashed
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 61.65 seconds

I am using the lastest ChromeDriver 2.30 and Selenium 3.4.0 versions

Body:
Found the answer to my own question. It worked when I copied the Default folder from the profile path and moved it somewhere else.

    ChromeOptions options = new ChromeOptions();
    options.addArguments("user-data-dir=C:/Users/"+System.getProperty("user.name")+"/Desktop/");
    options.addArguments("--start-maximized");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://www.google.com");


问:
Run SQL-like queries across large JSON datasets, in the cloud?
Is there a product that meets these requirements:

running SQL-like queries (preferably with a friendly UI, though can use command line if necessary)

across largely static JSON datasets of several million documents, without a consistent schema

with the JSON documents stored in the cloud, not locally.

Basically, I would like Google BigQuery, but without the requirement for a consistent pre-specified schema.

Apache Drill offers SQL-like queries across large JSON datasets with different schemas. However, I don't think it works well on cloud-hosted datasets - have set it up to talk to an S3 bucket, and it seems to need to download all the data locally, which makes it unusable with large datasets.

答:
BigQuery requires a static schema, but one option is to define the tables as CSV with a separator that doesn't appear in the data, meaning you'd have a single string column. You'll be limited to the JSON_EXTRACT functions for pulling data from the JSON, but from there you can cast to other data types and so on.

You could also consider filing a feature request for the BigQuery team to consider supporting a document type to make working with this kind of data easier in the future.


问:
How to move a Rails one to many association to a one to one association?
User model has_many Companies and Company belongs_to a User.

I now want to change this to a user has_one Company and Company has_one/belongs_to association. I have changed the models to look like this:

user.rb

```<code>class User < ApplicationRecord
    has_one :company #was has_many
    accepts_nested_attributes_for :company
    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end
</code>```

company.rb

```<code>class Company < ApplicationRecord
    belongs_to  :user
    has_many        :employees, inverse_of: :company
    has_many        :quotes, inverse_of: :company
    accepts_nested_attributes_for :employees, reject_if: :all_blank, allow_destroy: true #, :reject_if => lambda { |e| e.first_name.blank? }
    accepts_nested_attributes_for :quotes, allow_destroy: true

    validates_presence_of :user, :co_name, :co_number, :postcode
    validates :co_name, length: { minimum: 2, message: "minimum of 2 chars" }
    validates :co_number, format: { with: /\A([1-9]\d{6,7}|\d{6,7}|(SC|NI|AC|FC|GE|GN|GS|IC|IP|LP|NA|NF|NL|NO|NP|NR|NZ|OC|R|RC|SA|SF|SI|SL|SO|SP|SR|SZ|ZC|)\d{6,8})\z/,
                message: "must be valid company number" }
    validates :postcode, format: { with: /\A(?:gir(?: *0aa)?|[a-pr-uwyz](?:[a-hk-y]?[0-9]+|[0-9][a-hjkstuw]|[a-hk-y][0-9][abehmnprv-y])(?: *[0-9][abd-hjlnp-uw-z]{2})?)\z/,
                message: "must be valid postcode" }

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
end
</code>```

and have rake db:reset and have changed this line in my Companies#create method:

```<code>@company = current_user.companies.new(company_params)
</code>```

to

```<code>@company = current_user.company.new(company_params)
</code>```

But I'm getting a

```<code>undefined method `new' for nil:NilClass
</code>```

and I can't see where I'm going wrong. current_user should be available? the has_one association is defined so I should be able to call company.new on it right? I don;t need a foreign_key added to User, or do I?

Can anyone help me with where I'm going wrong? Thank you.

答:
undefined method `new' for nil:NilClass

For has_one, you should use build_association method, so

```<code>@company = current_user.company.new(company_params)
</code>```

should be

```<code>@company = current_user.build_company(company_params)
</code>```

Here is a list of all available methods for has_one association

Body:
User model has_many Companies and Company belongs_to a User.

I now want to change this to a user has_one Company and Company has_one/belongs_to association. I have changed the models to look like this:

user.rb

class User < ApplicationRecord
    has_one :company #was has_many
    accepts_nested_attributes_for :company
    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

company.rb

class Company < ApplicationRecord
    belongs_to  :user
    has_many        :employees, inverse_of: :company
    has_many        :quotes, inverse_of: :company
    accepts_nested_attributes_for :employees, reject_if: :all_blank, allow_destroy: true #, :reject_if => lambda { |e| e.first_name.blank? }
    accepts_nested_attributes_for :quotes, allow_destroy: true

    validates_presence_of :user, :co_name, :co_number, :postcode
    validates :co_name, length: { minimum: 2, message: "minimum of 2 chars" }
    validates :co_number, format: { with: /\A([1-9]\d{6,7}|\d{6,7}|(SC|NI|AC|FC|GE|GN|GS|IC|IP|LP|NA|NF|NL|NO|NP|NR|NZ|OC|R|RC|SA|SF|SI|SL|SO|SP|SR|SZ|ZC|)\d{6,8})\z/,
                message: "must be valid company number" }
    validates :postcode, format: { with: /\A(?:gir(?: *0aa)?|[a-pr-uwyz](?:[a-hk-y]?[0-9]+|[0-9][a-hjkstuw]|[a-hk-y][0-9][abehmnprv-y])(?: *[0-9][abd-hjlnp-uw-z]{2})?)\z/,
                message: "must be valid postcode" }

    enum industry:          [ :financial_services, :architect, :business_consultancy ]
end

and have rake db:reset and have changed this line in my Companies#create method:

@company = current_user.companies.new(company_params)

to

@company = current_user.company.new(company_params)

But I'm getting a

undefined method `new' for nil:NilClass

and I can't see where I'm going wrong. current_user should be available? the has_one association is defined so I should be able to call company.new on it right? I don;t need a foreign_key added to User, or do I?

Can anyone help me with where I'm going wrong? Thank you.

Body:
undefined method `new' for nil:NilClass

For has_one, you should use build_association method, so

@company = current_user.company.new(company_params)

should be

@company = current_user.build_company(company_params)

Here is a list of all available methods for has_one association


答: Try using HashMaps if your keys are unique.</p>

Title: How to efficiently search specific values in array using JavaScript

Body:
Im wondering how to search big arrays using JavaScript.

Let's say we have an array consisting of elements that represent businesses. There are a couple thousand elements in the array, they are objects that sometimes also have arrays in them.

In each of those elements is a key e.g. called category that looks like this category: ["attr1", "attr2", "attr3"]. Now I only want to find elements of the array that have a category like this:

category: ["Restaurant"]

The problem is that other keys of the elements in the array sometimes also have a property where "Restaurant" is in the name followed by something else e.g. "RestaurantPrice" so

if(array[i].categories != null &&
array[i].categories.indexOf("Restaurant") != -1) {
    do something
}

Would not work properly because it would return all occurences of the word "Restaurant" or am I wrong?

If not how should I search for specific things in an array?


问:
I am struggling to link my PHPMyAdmin MySQL database to
I am trying to link my MySQL database to my PHP code. My friend has the same code as me and is able to connect their database to their PHP code. I end up getting a error code and do not know where I am going wrong.

This is the code that I am using

```<code><?php

$username="root";
$password="password";
$database="account";
$connect = mysql_connect('localhost', $username, $password);
//$db-select = mysql_select_db($database,$connect) or die("Unable to select database");

$user = $_GET['user'];
$pass = $_GET['pass'];

if(!$connect) {
    die('eror');
}

$db = my_sql_select_db("account", $connect)
mysql_query($db, "INSERT INTO 'account', 'tbl_account' (Username, Password) VALUES ('$user', '$pass')";);

mysql_close($connect);
?>
</code>```

This is the outcome:

Parse error: syntax error, unexpected 'mysql_query' (T_STRING) in C:\Apache24\htdocs\PHP\index.php on line 11

答:
add semicolon at the end of first line and remove the extra semicolon in second line </p>

```<code>$db = my_sql_select_db("account", $connect);
mysql_query($db,"INSERT INTO 'account','tbl_account' (Username,Password) VALUES ('$user','$pass')");
</code>```

Body:
I am trying to link my MySQL database to my PHP code. My friend has the same code as me and is able to connect their database to their PHP code. I end up getting a error code and do not know where I am going wrong.

This is the code that I am using

<?php

$username="root";
$password="password";
$database="account";
$connect = mysql_connect('localhost', $username, $password);
//$db-select = mysql_select_db($database,$connect) or die("Unable to select database");

$user = $_GET['user'];
$pass = $_GET['pass'];

if(!$connect) {
    die('eror');
}

$db = my_sql_select_db("account", $connect)
mysql_query($db, "INSERT INTO 'account', 'tbl_account' (Username, Password) VALUES ('$user', '$pass')";);

mysql_close($connect);
?>

This is the outcome:

Parse error: syntax error, unexpected 'mysql_query' (T_STRING) in C:\Apache24\htdocs\PHP\index.php on line 11

Body:
add semicolon at the end of first line and remove the extra semicolon in second line

$db = my_sql_select_db("account", $connect);
mysql_query($db,"INSERT INTO 'account','tbl_account' (Username,Password) VALUES ('$user','$pass')");


问:
Change S3 Endpoint in Laravel
I used the filesystems.php file to configure my S3.
When I try to put content in the bucket I receive this error:

```<code>Encountered a permanent redirect while requesting https://s3-us-west-2.amazonaws.com/MYBUCKET... Are you sure you are using the correct region for this bucket?
</code>```

I then try to acces the url and I get this message:

```<code>The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
</code>```

On the same page I get:

```<code><Endpoint>s3.amazonaws.com</Endpoint>
</code>```

Then how could I remove the region from the URL Laravel generates?

答:
You can create a customer service provider like that:

```<code>use Illuminate\Support\ServiceProvider;
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
use Aws\Laravel\AwsServiceProvider;
use Storage;

class AwsS3ServiceProvider extends ServiceProvider
{

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('s3', function($app, $config) {
            $client = new S3Client([
                'credentials' => [
                    'key'    => $config['key'],
                    'secret' => $config['secret'],
                ],
                'region' => $config['region'],
                'version' => $config['version'],
                'endpoint' => $config['endpoint'],
                'ua_append' => [
                    'L5MOD/' . AwsServiceProvider::VERSION,
                ],
            ]);

            return new Filesystem(new AwsS3Adapter($client, $config['bucket_name']));
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
</code>```

And add endpoint variable into config/filesystems.php as well:

```<code>'s3' => [
    'driver' => 's3',
    'key'    => env('AWS_KEY'),
    'secret' => env('AWS_SECRET'),
    'region' => env('AWS_REGION'),
    'version' => 'latest',
    'endpoint' => env('AWS_ENDPOINT'),
    'bucket_name' => env('AWS_BUCKET_NAME')
]
</code>```

Look at docs to get details about how to extend Storage facade.

Title: Change S3 Endpoint in Laravel

Body:
I used the filesystems.php file to configure my S3.
When I try to put content in the bucket I receive this error:

Encountered a permanent redirect while requesting https://s3-us-west-2.amazonaws.com/MYBUCKET... Are you sure you are using the correct region for this bucket?

I then try to acces the url and I get this message:

The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

On the same page I get:

<Endpoint>s3.amazonaws.com</Endpoint>

Then how could I remove the region from the URL Laravel generates?

Body:
You can create a customer service provider like that:

use Illuminate\Support\ServiceProvider;
use Aws\S3\S3Client;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use League\Flysystem\Filesystem;
use Aws\Laravel\AwsServiceProvider;
use Storage;

class AwsS3ServiceProvider extends ServiceProvider
{

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Storage::extend('s3', function($app, $config) {
            $client = new S3Client([
                'credentials' => [
                    'key'    => $config['key'],
                    'secret' => $config['secret'],
                ],
                'region' => $config['region'],
                'version' => $config['version'],
                'endpoint' => $config['endpoint'],
                'ua_append' => [
                    'L5MOD/' . AwsServiceProvider::VERSION,
                ],
            ]);

            return new Filesystem(new AwsS3Adapter($client, $config['bucket_name']));
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

And add endpoint variable into config/filesystems.php as well:

's3' => [
    'driver' => 's3',
    'key'    => env('AWS_KEY'),
    'secret' => env('AWS_SECRET'),
    'region' => env('AWS_REGION'),
    'version' => 'latest',
    'endpoint' => env('AWS_ENDPOINT'),
    'bucket_name' => env('AWS_BUCKET_NAME')
]

Look at docs to get details about how to extend Storage facade.


问:
Converting from for loops to forEach/map/some .. etc
Is it possible to not use for loops in the following snippet?

```<code>const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  const range = [];

  for (let i = 0; i < states.length; i += 1) {
    let prevState;

    for (let j = i - 1; j >= 0; j -= 1) {
      prevState = states[j] && states[j][prop];
      if (prevState) break;
    }

    range[i] = states[i][prop] || (prevState || defaultState[prop]);
  }

  return range;
};

getRange('a') // [1, 1, 1]
getRange('b') // [0, 1, 2]
getRange('c') // [0, 0, 1]
</code>```

It should be in JavaScript only without depending on any other libs, I've tried to play a little with forEach() and some(), but couldn't replicate the current behavior. This is for exploration of the language purposes.

答:
const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  return states.reduce((res, o, i) => {
    res.push( o[prop] || res[i - 1] || defaultState[prop] );
    return res;
  }, []);
};

console.log(getRange('a')); // [1, 1, 1]
console.log(getRange('b')); // [0, 1, 2]
console.log(getRange('c')); // [0, 0, 1]```
</div>
</div>
</p>

<p><code>res</code> is the result array. For each object <code>o</code> in the <code>states</code> array we push:</p>

```res.push( o[prop] || res[i - 1] || defaultState[prop] );
// or:
res[i] = o[prop] || res[i - 1] || defaultState[prop];
```

<p>either:</p>

<ul>
<li>this current object <code>o</code> state,</li>
<li>the previous state recorded (stored in <code>res[i - 1]</code>) (the previous state),</li>
<li>or the default state from <code>defaultState</code>.</li>
</ul>

<p>In my code, <code>reduce</code> replaces the outer <code>for</code> from your code, <code>res[i - 1]</code> replaces the inner <code>for</code> (as there is no need to loop until the first element to get the previous state that we already know it's only one step behind).</p>

<p><strong>EDIT:</strong></p>

<p>To treat <code>0</code>s as thruthy use this:</p>

```res.push( (o[prop] || o[prop] == 0)? o[prop]:               // if o[prop] is truthy or equal to 0 then use it
          (res[i - 1] || res[i - 1] == 0)? res[i - 1]:      // otherwise (o[prop] is neither truthy nor equal to 0) then if res[i - 1] is truthy or equal to 0 then use res[i - 1]
          defaultState[prop] );                             // otherwise just use the default value no matter whether it is truthy or not (that's the point of default values anyway)
```

<p>or:</p>

```res.push( !isNaN(o[prop])? o[prop]:                         // if o[prop] is a valid number use it
          !isNaN(res[i - 1])? res[i - 1]:                   // otherwise, if res[i - 1] is a valid number then use it
          defaultState[prop] );                             // otherwise, use the default value
```

Body:
Is it possible to not use for loops in the following snippet?

const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  const range = [];

  for (let i = 0; i < states.length; i += 1) {
    let prevState;

    for (let j = i - 1; j >= 0; j -= 1) {
      prevState = states[j] && states[j][prop];
      if (prevState) break;
    }

    range[i] = states[i][prop] || (prevState || defaultState[prop]);
  }

  return range;
};

getRange('a') // [1, 1, 1]
getRange('b') // [0, 1, 2]
getRange('c') // [0, 0, 1]

It should be in JavaScript only without depending on any other libs, I've tried to play a little with forEach() and some(), but couldn't replicate the current behavior. This is for exploration of the language purposes.

Body:
const states = [
  { a: 1 },
  { b: 1 },
  { b: 2, c: 1 }
];

const defaultState = {
  a: 0,
  b: 0,
  c: 0
};

const getRange = prop => {
  return states.reduce((res, o, i) => {
    res.push( o[prop] || res[i - 1] || defaultState[prop] );
    return res;
  }, []);
};

console.log(getRange('a')); // [1, 1, 1]
console.log(getRange('b')); // [0, 1, 2]
console.log(getRange('c')); // [0, 0, 1]

res is the result array. For each object o in the states array we push:

res.push( o[prop] || res[i - 1] || defaultState[prop] );
// or:
res[i] = o[prop] || res[i - 1] || defaultState[prop];

either:

this current object o state,

the previous state recorded (stored in res[i - 1]) (the previous state),

or the default state from defaultState.

In my code, reduce replaces the outer for from your code, res[i - 1] replaces the inner for (as there is no need to loop until the first element to get the previous state that we already know it's only one step behind).

EDIT:

To treat 0s as thruthy use this:

res.push( (o[prop] || o[prop] == 0)? o[prop]:               // if o[prop] is truthy or equal to 0 then use it
          (res[i - 1] || res[i - 1] == 0)? res[i - 1]:      // otherwise (o[prop] is neither truthy nor equal to 0) then if res[i - 1] is truthy or equal to 0 then use res[i - 1]
          defaultState[prop] );                             // otherwise just use the default value no matter whether it is truthy or not (that's the point of default values anyway)

or:

res.push( !isNaN(o[prop])? o[prop]:                         // if o[prop] is a valid number use it
          !isNaN(res[i - 1])? res[i - 1]:                   // otherwise, if res[i - 1] is a valid number then use it
          defaultState[prop] );                             // otherwise, use the default value


问:
Android: Detect long press on the whole activity
How can i detect a long press on the whole activity? since onLongClickListener is only for individual views.I want to run a method everytime the user longpress the screen</p>

答:
You can override your activity's dispatchTouchEvent() method.  You also need a gesture detector in order to determine which motion events are 'long presses'. Put this into your activity:

```<code>final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        // The code for when a long-press happens
    }
});

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);
    return super.dispatchTouchEvent(event);
}
</code>```

Please note that I did not test the above code.

Body:
You can override your activity's dispatchTouchEvent() method.  You also need a gesture detector in order to determine which motion events are 'long presses'. Put this into your activity:

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        // The code for when a long-press happens
    }
});

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);
    return super.dispatchTouchEvent(event);
}

Please note that I did not test the above code.


问:
Is it possible to step into a member function defined in a .dll file?
I downloaded an SDK from NVIDIA and I'm using Visual Studio 2015 to run the demo project files provided in the SDK.

The demo project files in the SDK worked as expected until I made some small changes in the code (If you'd like details about the changes, please see last paragraph).

After making these changes, a line in the code seems to run forever. Using the debugger I found that there's a member function in that line of code that is not returning anything and therefore the program flow is just stuck at that line. I tried stepping into this function but it's defined in a .dll file that came with the SDK.

Visual Studio tells me that the symbol file is not loaded and the PDB file cannot be found on the Microsoft Server. The debugger lets me see the disassembly code but I don't know if I can identify the problem using that.

So now I'm stuck at a line of code because the member function defined in a .dll file won't return anything and just keeps on running (I've left it running for over an hour and still it didn't return anything).

I want to identify the reason why this is happening, but I'm unable to see the source code of the member function so I have no idea what's happening inside the member function or how to debug it. Is there any way I can identify the cause of this problem? Is it possible to somehow see the source code of the member function in a way that I can understand what is going on?

More details on changes I made:

I've separated this from main body of the question because I don't see it as being very relevant but it may be useful for the answerer. The SDK stitches videos together into a single video (creating 360 view videos). The demo project works fine as long as I use the demo video files. The video files are fed into the project using command line arguments. When I feed my own video files to the demo project, that's when I face this problem, otherwise the member function returns successfully and the project successfully creates a stitched video. The only thing I changed is the input to the project (i.e. the video files), I haven't changed the source code at all.

答: As stated by VTT and Aganju, I cannot step into the member function defined in the DLL unless the source code is provided to me with the DLL. This answers what I asked. For my specific case, I was working with NVIDIA VRWorks 360 Video SDK, the problem was caused by not having the right codec for the video files that get stitched. Although this is mentioned nowhere in the SDK documentation, the video codec that should be used is H264 - MPEG-4 AVC (part 10) (AVC1).</p>


问:
Make and Visualise table in R
First I have an input and I want to get an output like this
(I want to group the occurrences in the dataset between columns):

Second:
Display this table in a good looking way (something that looks like Word or Excel)
I can't use Word or Excel as I'm making some calculations in R with this dataset (it contains columns with numbers which aren't displayed here)

答:
calculating the output table

I don't really see how the output table is calculated. Shouldn't it be output_table["A", "C"] = "e"?

Displaying your data

There are a lot of ways to do that. You might consider using RMarkdown to create a report-style output.

The DT library is also a very handy tool to display tables. It works well with RMarkdown and can be embedded in HTML documents. If you are using RStudio, you can use the following code to display your data

```<code>library(DT)
DT::datatable(iris)
</code>```

Title: Make and Visualise table in R

Body:
calculating the output table

I don't really see how the output table is calculated. Shouldn't it be output_table["A", "C"] = "e"?

Displaying your data

There are a lot of ways to do that. You might consider using RMarkdown to create a report-style output.

The DT library is also a very handy tool to display tables. It works well with RMarkdown and can be embedded in HTML documents. If you are using RStudio, you can use the following code to display your data

library(DT)
DT::datatable(iris)


问:
Cannot read property 'password' of undefined at Query._callback Node.js
While implementing passport and working the backend for it i got this error. Could anyone help me figure out how to fix it?

TypeError: Cannot read property 'password' of undefined
      at Query._callback (/Users/oscarstein/Documents/Programering/express-cc/app.js:76:32)

Using the following code:

```<code>passport.use(new LocalStrategy(
  function(username, password, done) {
      console.log(username);
      console.log(password);
      const db = require('./db');

      db.query('SELECT id, password FROM users WHERE username = ?', [username], function(err, results, fields){
        if (err) {done(err)};

        if (results.length == 0) {
          done(null, false);
        }

        const hash = results[0].password.toString();

        bcrypt.compare(password, hash, function(err, response){
            if (response == true) {
              return done(null, {user_id: results[0].id});
            } else {
              return done(null, false);
            }

          });
      })

    }
));
</code>```

答: Check if the table from the database has a field called 'password'</p>

Body:
While implementing passport and working the backend for it i got this error. Could anyone help me figure out how to fix it?

TypeError: Cannot read property 'password' of undefined
      at Query._callback (/Users/oscarstein/Documents/Programering/express-cc/app.js:76:32)

Using the following code:

passport.use(new LocalStrategy(
  function(username, password, done) {
      console.log(username);
      console.log(password);
      const db = require('./db');

      db.query('SELECT id, password FROM users WHERE username = ?', [username], function(err, results, fields){
        if (err) {done(err)};

        if (results.length == 0) {
          done(null, false);
        }

        const hash = results[0].password.toString();

        bcrypt.compare(password, hash, function(err, response){
            if (response == true) {
              return done(null, {user_id: results[0].id});
            } else {
              return done(null, false);
            }

          });
      })

    }
));


问:
Angular 2 CLI Project read json data from file
I'm trying to read a json file from within my Angular2 src/app folder

The directory structure is as follows:-

And I'm trying to read the file in app.config.js using the following code:-

```<code>public load() {
    return new Promise((resolve, reject) => {
        this._http.get("config.json")
            .map(res => res.json())
            .subscribe((data) => {
                this.cache['config.json'] = new ConfigData(data.json());
                resolve(true);
            });
    });
}
</code>```

But everything I try results in the following error:-

zone.js:2224 GET http://localhost:4200/config.json 404 (Not Found)

Where do I need to put the file?

I've tried moving it to the src directory to no avail. I've also tried:-

app/config.json
./app/config.json

I also added an assets folder under app and added it into there but that didn't work either

What do I need to do?

Thanks

答:
Put the config.json file in assets folder and change the request to following,

```<code>public load() {
    return new Promise((resolve, reject) => {
        this._http.get("assets/config.json")
            .map(res => res.json())
            .subscribe((data) => {
                this.cache['config.json'] = new ConfigData(data.json());
                resolve(true);
            });
    });
}
</code>```

It should work. make sure to relunch the to make the changes reflect in www/assets folder.

Body:
I'm trying to read a json file from within my Angular2 src/app folder

The directory structure is as follows:-

And I'm trying to read the file in app.config.js using the following code:-

public load() {
    return new Promise((resolve, reject) => {
        this._http.get("config.json")
            .map(res => res.json())
            .subscribe((data) => {
                this.cache['config.json'] = new ConfigData(data.json());
                resolve(true);
            });
    });
}

But everything I try results in the following error:-

zone.js:2224 GET http://localhost:4200/config.json 404 (Not Found)

Where do I need to put the file?

I've tried moving it to the src directory to no avail. I've also tried:-

app/config.json
./app/config.json

I also added an assets folder under app and added it into there but that didn't work either

What do I need to do?

Thanks

Body:
Put the config.json file in assets folder and change the request to following,

public load() {
    return new Promise((resolve, reject) => {
        this._http.get("assets/config.json")
            .map(res => res.json())
            .subscribe((data) => {
                this.cache['config.json'] = new ConfigData(data.json());
                resolve(true);
            });
    });
}

It should work. make sure to relunch the to make the changes reflect in www/assets folder.


问:
Draft.js editor lost focus on Android browser(s) after first word
I'm using Draft.js in a React.js project. The Editor works fine on desktop browser(s) (Chrome,Firefox, IE, Edge...) but I have problem in Android device.

After I enter the first word in editor and press spacebar (on soft keyboard) the Editor lost focus & I will have to touch there again if I want to continue to type in the Editor.

This is such a very bad user experience. The Draft.js Editor setup is nothing special, just like their example.

Anyone have same problem & have a fix please ?

答:
The following seems to work in draft-js@0.10.1

```<code><Editor
  autoCapitalize={'none'}
  autoComplete={'off'}
  autoCorrect={'off'}
  spellCheck={false} ... />
</code>```

Body:
The following seems to work in draft-js@0.10.1

<Editor
  autoCapitalize={'none'}
  autoComplete={'off'}
  autoCorrect={'off'}
  spellCheck={false} ... />


问:
javascript determining if a day is beyond 2 days
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

```<code>var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();
</code>```

but how do i find if the asked by just day name is beyond 2 days or not?

答:
```<code>var daysArr = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var today = new Date().getDay();

//return if day difference is bigger than 2
function dayDiff(day){
    if(Math.abs(daysArr.indexOf(day) - today) > 2){
        return true;
    }else{
        return false;
    }
}

dayDiff("Wednesday");
</code>```

Body:
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();

but how do i find if the asked by just day name is beyond 2 days or not?


问:
Cordova InAppBrowser PDF Does Not Show Initially In PhoneGap iOS App
So I'm using PhoneGap Build to build my app.

The InAppBrowser works fine when running the app via the PhoneGap Developer application however when I use PhoneGap Build and install the IPA file onto the iPad the button that I click to open up the InAppBrowser does not open InAppBrowser. I have to double tap on the home button and then go back into the app for it to appear. Has anyone else ever experienced this?

The code for the button is as follow:

```<code>$("#dashboardSmPC").on(app.interactionEvent, function () {
  var inAppBrowser = cordova.InAppBrowser.open('pdf/SmPC.pdf', '_blank', 'closebuttoncaption=Back,location=no,presentationstyle=fullscreen,transitionstyle=coververtical');
});
</code>```

EDIT: This problem seems to be in iOS 10.3.2., 9.3.5 works fine.

答:
This was because of too tight an CSP (Content Security Policy) meta tag in the index.html. I changed it to this and it works in iOS 10.3.2:</p>

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self' gap://ready file://* *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; media-src *; img-src * data:">
</code>```

Body:
So I'm using PhoneGap Build to build my app.

The InAppBrowser works fine when running the app via the PhoneGap Developer application however when I use PhoneGap Build and install the IPA file onto the iPad the button that I click to open up the InAppBrowser does not open InAppBrowser. I have to double tap on the home button and then go back into the app for it to appear. Has anyone else ever experienced this?

The code for the button is as follow:

$("#dashboardSmPC").on(app.interactionEvent, function () {
  var inAppBrowser = cordova.InAppBrowser.open('pdf/SmPC.pdf', '_blank', 'closebuttoncaption=Back,location=no,presentationstyle=fullscreen,transitionstyle=coververtical');
});

EDIT: This problem seems to be in iOS 10.3.2., 9.3.5 works fine.

Body:
This was because of too tight an CSP (Content Security Policy) meta tag in the index.html. I changed it to this and it works in iOS 10.3.2:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' gap://ready file://* *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; media-src *; img-src * data:">


问:
hibernate table does not exist error
In configuration hibernate.cfg.xml, i add
<property name="hibernate.hbm2ddl.auto">create</property>
Hibernate do create table automatically when i run the application. However, i remove the table from database manually by running drop table sql. Then run the hibernate application again. The exception appear

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.person' doesn't exist

only way to fix the problem is restart the Mysql database. Could anyone explain this issue for me?

this is my hibernate.cfg.xml

```<code><hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">create</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Mapping files -->
    <mapping resource="com/mapping/Event.hbm.xml" />
    <mapping resource="com/mapping/Person.hbm.xml"/>
</session-factory>
</code>```

Thx

答:
Is there a space between "property" and "name"?

```<code><propertyname="hibernate.hbm2ddl.auto">create</property>
</code>```

If not, then that's probably the issue. Also, what do you mean that it fixes when you "reboot the MySQL database"? Does it means you just restart the MySQL server, or it means that you need to manually recreate the table? Also, if the XML excerpt above indeed contains an space between "property" and "name", please provide also the except for the hibernate logs, specially the part that it lists all the properties it identified.

Title: hibernate table does not exist error

Body:
In configuration hibernate.cfg.xml, i add
<property name="hibernate.hbm2ddl.auto">create</property>
Hibernate do create table automatically when i run the application. However, i remove the table from database manually by running drop table sql. Then run the hibernate application again. The exception appear

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.person' doesn't exist

only way to fix the problem is restart the Mysql database. Could anyone explain this issue for me?

this is my hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
    </property>
    <property name="hibernate.connection.url">
        jdbc:mysql://localhost/test
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="dialect">
        org.hibernate.dialect.MySQLDialect
    </property>

    <property name="hibernate.hbm2ddl.auto">create</property>

    <property name="current_session_context_class">thread</property>

    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

    <property name="show_sql">true</property>

    <mapping resource="com/mapping/Event.hbm.xml" />
    <mapping resource="com/mapping/Person.hbm.xml"/>
</session-factory>

Thx

Body:
Is there a space between "property" and "name"?

<propertyname="hibernate.hbm2ddl.auto">create</property>

If not, then that's probably the issue. Also, what do you mean that it fixes when you "reboot the MySQL database"? Does it means you just restart the MySQL server, or it means that you need to manually recreate the table? Also, if the XML excerpt above indeed contains an space between "property" and "name", please provide also the except for the hibernate logs, specially the part that it lists all the properties it identified.


问:
What jQuery version to mention in code
I'm using jQuery, and I'm little confused about what version is included at start of my page. From my experience with other software I understand that each new version contains most old features, and offers some new ones. If latests jQuery version is 1.9 for example, why would I mention this:

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../jqm145/jquery.mobile-1.4.5.min.css">
<script src="../jq1-11-3/jquery-1.11.3.js"></script>
<script src="../jqm145/jquery.mobile-1.4.5.min.js"></script>
</code>```

How do I check if a function will work in a specific version of Jquery?

Furthermore, the mobile JQuery version 1.4.5 and "plain" JQuery is 1.11.3. Why is this the case?

答:
It depends from your target audience, and therefore from the browsers you need to support.
You have three options:

If you need to support older browsers like Internet Explorer 6-8,
Opera 12.1x or Safari 5.1+, use: jQuery 1.11.3 + jQuery Mobile 1.4.5

If you need the current stable and most used pair, use: jQuery 2.1.4 + jQuery
Mobile 1.4.5

If you are living on the edge, and would like to actively take part to the
jQuery Mobile development, notify bugs and open issues on github,
use: jQuery 3.2.1 + jQuery Mobile 1.5.0-alpha.1

Title: What jQuery version to mention in code

Body:
I'm using jQuery, and I'm little confused about what version is included at start of my page. From my experience with other software I understand that each new version contains most old features, and offers some new ones. If latests jQuery version is 1.9 for example, why would I mention this:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../jqm145/jquery.mobile-1.4.5.min.css">

How do I check if a function will work in a specific version of Jquery?

Furthermore, the mobile JQuery version 1.4.5 and "plain" JQuery is 1.11.3. Why is this the case?