答:
Consider updating the code as follows:

```<code>import { Injectable } from '@angular/core';
import { Http } from "@angular/http";

@Injectable()
export class DataService {

  constructor(private httpClient: Http) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}
</code>```

Let me know if it works.

Title: Angular Service and HttpClient Type does not exist

Body:
Consider updating the code as follows:

import { Injectable } from '@angular/core';
import { Http } from "@angular/http";

@Injectable()
export class DataService {

  constructor(private httpClient: Http) { }

  getData() {
    // don't use 'any', type your data instead!
    return this.httpClient.get<any>('./assets/data.json');
  }

}

Let me know if it works.


来源: stackexchange

问:
J-Meter - Moodle test scripts
I just learned how to use J-Meter and i am loving work with it.

I have to do load testing for a moodle install .

I wonder if there are any set of jmeter scripts to test moodle that i can re-use or like some kind of benchmark scripts that are somehow advanced and that can help me test the moodle performance.

Thanks in advance for any suggestions and links .

答: J Meter script can not be reused as it requires 1 time recording option.Hence you need to record your script at least 1, then keep running the script with load increase gradually depending on your server capacity.

ContentLicense: CC BY-SA 2.5

Title: J-Meter - Moodle test scripts

ContentLicense: CC BY-SA 3.0


问:
Trace not working in Flash
In have searched the forums and can't find the appropiate answer.  I do not have the "omit traces" option checked in publish settings (I use flash CS5).  Here is my code:

```<code>package
{

 import flash.display.MovieClip;

 public class gr extends MovieClip
 {

  public function gr()
  {
   // constructor code
   var mc:MovieClip = new MovieClip();
   mc.graphics.beginFill(0xFF0000);
   mc.graphics.drawRect(0, 0, 100, 80);
   mc.graphics.endFill();
   mc.x = 200;
   mc.y = 60;
   addChild(mc);
   trace("hi")
  }
 }

}
</code>```

The creation of a movieclip works fine, but the trace doesn't.  This is the main class.

答: In my experience, the compiled as3 clip never shows traces, even when the creation of the clip does. I always have a dynamic textbox somewhere on the stage that I just add text to when I want to view a variable in a compiled clip.</p>

Title: Trace not working in Flash

Body:
In have searched the forums and can't find the appropiate answer.  I do not have the "omit traces" option checked in publish settings (I use flash CS5).  Here is my code:

package
{

 import flash.display.MovieClip;

 public class gr extends MovieClip
 {

  public function gr()
  {
   // constructor code
   var mc:MovieClip = new MovieClip();
   mc.graphics.beginFill(0xFF0000);
   mc.graphics.drawRect(0, 0, 100, 80);
   mc.graphics.endFill();
   mc.x = 200;
   mc.y = 60;
   addChild(mc);
   trace("hi")
  }
 }

}

The creation of a movieclip works fine, but the trace doesn't.  This is the main class.


问:
Submitting form after validating inputs
I have the following registration form :

```<code><form id="register-form" method="post" role="form" style="display: none;"

action="">
    <div class="form-group">
        <input type="text" name="firstname" id="firstname" tabindex="1" class="form-control" placeholder="Firstname" value="" required>
        <span class="error" id="fnError"></span>
    </div>
    <div class="form-group">
        <input type="text" name="lastname" id="lastname" tabindex="1" class="form-control" placeholder="Lastname" value=""required>
        <span class="error" id="lnError"></span>
    </div>
    <div class="form-group">
        <input type="email" name="email2" id="email2" tabindex="1" class="form-control" placeholder="Email Address" value=""required>
    </div>
    <div class="form-group">
        <input type="password" name="password2" id="password2" tabindex="2" class="form-control" placeholder="Password"required>
        <span class="error" id="pass2Error"></span>
    </div>
    <div class="form-group">
        <input type="password" name="confirm_password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password" required>
        <span class="error" id="confError"></span>
    </div>
    <div class="form-group">
        <div class="row">
            <div class="col-sm-6 col-sm-offset-3">
                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
                <span class="throw_error" id="success"></span>
                <div id="divLoader"></div>
            </div>
            <div class="col-sm-6 col-sm-offset-3">
                <span id="result"></span>
            </div>
        </div>
    </div>
</form>
</code>```

And I am using the jquery validation plugin to validate the inputs :

```<code>jQuery.validator.setDefaults({
        debug: false,
        success: "valid"
    });
    $('#register-form').validate({
        rules:{
            firstname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            lastname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            email2:{
                required : true,
                email : true
            },
            password2:{
                required : true,
                minlength : 8,
                maxlength : 15
            },
            confirm_password:{
                required : true,
                minlength : 8,
                maxlength : 15,
                equalTo : "#password2"
            }
        }
    });
</code>```

When I click on the registration button, the validation of the fields is shown (all the errors on each field are shown), and the ajax code that I am using on the button press runs even if there are validation errors.
Here is my button clicked code :

```<code>$('#register-form').submit(function(event){
    var formData={
        'fn':$('#firstname').val(),
        'ln':$('#lastname').val(),
        'email':$('#email2').val(),
        'pass':$('#password2').val(),
        'action':'regUser'
    };
    $.ajax({
        type: 'POST',
        url: 'Index.php',
        data: formData,
        dataType: 'json',
        beforeSend: function () {
            $('#register-submit').attr("disabled","disabled");
            $("#divLoader").addClass("loader");
            console.log('before send');
        },
        success: function (data) {
            if(data.success){
                $('#success').fadeIn(1000).append('<p>'+data.userAdded+'</p>');
            }
            else{
                $('.throw_error').fadeIn(1000).html(data.errors[0]);
            }
        },
        error: function(){
            alert("System currently unavailable, try again later");
        },
        complete: function () {
            $('#register-submit').removeAttr('disabled');
            $('#divLoader').removeClass('loader');
        }
    });
    event.preventDefault();
});
</code>```

What I want is that when I click on the submit button and there are validation problems that the button clicked event will not be triggered, so the AJAX call doesn't start.

答:
You have to put the condition before the ajax call. You have to check the form validation with the function valid() of jquery validate.

So your code will be like this:

```<code>$('#register-form').submit(function(event){
var formData={
    'fn':$('#firstname').val(),
    'ln':$('#lastname').val(),
    'email':$('#email2').val(),
    'pass':$('#password2').val(),
    'action':'regUser'
};
if($(this).valid()) {
    //ajax call  will be inside of this if condition
}
</code>```

Reference link.

And make the debug: true,.

ContentLicense: CC BY-SA 4.0

Title: Submitting form after validating inputs

Body:
I have the following registration form :

<form id="register-form" method="post" role="form" style="display: none;"

action="">

        <input type="text" name="firstname" id="firstname" tabindex="1" class="form-control" placeholder="Firstname" value="" required>

        <input type="text" name="lastname" id="lastname" tabindex="1" class="form-control" placeholder="Lastname" value=""required>

        <input type="email" name="email2" id="email2" tabindex="1" class="form-control" placeholder="Email Address" value=""required>

        <input type="password" name="password2" id="password2" tabindex="2" class="form-control" placeholder="Password"required>

        <input type="password" name="confirm_password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password" required>

                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">

</form>

And I am using the jquery validation plugin to validate the inputs :

jQuery.validator.setDefaults({
        debug: false,
        success: "valid"
    });
    $('#register-form').validate({
        rules:{
            firstname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            lastname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            email2:{
                required : true,
                email : true
            },
            password2:{
                required : true,
                minlength : 8,
                maxlength : 15
            },
            confirm_password:{
                required : true,
                minlength : 8,
                maxlength : 15,
                equalTo : "#password2"
            }
        }
    });

When I click on the registration button, the validation of the fields is shown (all the errors on each field are shown), and the ajax code that I am using on the button press runs even if there are validation errors.
Here is my button clicked code :

$('#register-form').submit(function(event){
    var formData={
        'fn':$('#firstname').val(),
        'ln':$('#lastname').val(),
        'email':$('#email2').val(),
        'pass':$('#password2').val(),
        'action':'regUser'
    };
    $.ajax({
        type: 'POST',
        url: 'Index.php',
        data: formData,
        dataType: 'json',
        beforeSend: function () {
            $('#register-submit').attr("disabled","disabled");
            $("#divLoader").addClass("loader");
            console.log('before send');
        },
        success: function (data) {
            if(data.success){
                $('#success').fadeIn(1000).append('
'+data.userAdded+'
');
            }
            else{
                $('.throw_error').fadeIn(1000).html(data.errors[0]);
            }
        },
        error: function(){
            alert("System currently unavailable, try again later");
        },
        complete: function () {
            $('#register-submit').removeAttr('disabled');
            $('#divLoader').removeClass('loader');
        }
    });
    event.preventDefault();
});

What I want is that when I click on the submit button and there are validation problems that the button clicked event will not be triggered, so the AJAX call doesn't start.

Body:
You have to put the condition before the ajax call. You have to check the form validation with the function valid() of jquery validate.

So your code will be like this:

$('#register-form').submit(function(event){
var formData={
    'fn':$('#firstname').val(),
    'ln':$('#lastname').val(),
    'email':$('#email2').val(),
    'pass':$('#password2').val(),
    'action':'regUser'
};
if($(this).valid()) {
    //ajax call  will be inside of this if condition
}

Reference link.

And make the debug: true,.


问:
Create new element in existing XML Document using Powershell
I have a script that reads from an XML file, performs some web services, from which it gets a response and I'd now like the XML fie to be amended with the webs response as below.

Original XML:

```<code><ItemNum>
    <Key>11233</Key>
    <Item>123.jpg</Item>
    <Item>456.jpg</Item>
    <Item>789.jpg</Item>
    <Detail>Processed on 8-12-2017</Detail>
</ItemNum>
</code>```

The script will process the items from the XML and iterate through the itemlist, similar to below:

```<code>[xml]$xml = Get-Content -Path $xmlPath

Foreach ($websResponse in $websResponseList) {
    <Create New Element>
    <Add Webs Response to Element>
}

$xml.save($xmlPath)
</code>```

The result should be the original XML modified to look like the below:

```<code><ItemNum>
    <Key>11233</Key>
    <Item>123.jpg</Item>
    <Item>456.jpg</Item>
    <Item>789.jpg</Item>
    <Detail>Processed on 8-12-2017</Detail>
    <WebS>00001</WebS>
    <WebS>00002</WebS>
    <WebS>00003</WebS>
</ItemNum>
</code>```

I've read countless articles on working with XML in Powershell and probably some that are very similar what I'm trying to achieve but this is for some reason stumping me so would appreciate any pointers.

答:
You're almost there:</p>

```<code>[xml]$xml = Get-Content -Path $xmlPath

foreach ($websResponse in $websResponseList)
{
    $elem = $xml.CreateElement('WebS','00001') # substitute with data
    $xml.ItemNum.AppendChild($elem)
}
$xml.save($xmlPath)
</code>```

Body:
I have a script that reads from an XML file, performs some web services, from which it gets a response and I'd now like the XML fie to be amended with the webs response as below.

Original XML:

<ItemNum>
    <Key>11233</Key>
    <Item>123.jpg</Item>
    <Item>456.jpg</Item>
    <Item>789.jpg</Item>
    <Detail>Processed on 8-12-2017</Detail>
</ItemNum>

The script will process the items from the XML and iterate through the itemlist, similar to below:

[xml]$xml = Get-Content -Path $xmlPath

Foreach ($websResponse in $websResponseList) {
    <Create New Element>
    <Add Webs Response to Element>
}

$xml.save($xmlPath)

The result should be the original XML modified to look like the below:

<ItemNum>
    <Key>11233</Key>
    <Item>123.jpg</Item>
    <Item>456.jpg</Item>
    <Item>789.jpg</Item>
    <Detail>Processed on 8-12-2017</Detail>
    <WebS>00001</WebS>
    <WebS>00002</WebS>
    <WebS>00003</WebS>
</ItemNum>

I've read countless articles on working with XML in Powershell and probably some that are very similar what I'm trying to achieve but this is for some reason stumping me so would appreciate any pointers.

Body:
You're almost there:

[xml]$xml = Get-Content -Path $xmlPath

foreach ($websResponse in $websResponseList)
{
    $elem = $xml.CreateElement('WebS','00001') # substitute with data
    $xml.ItemNum.AppendChild($elem)
}
$xml.save($xmlPath)


问:
Creating a Query with combination of "CASE WHEN" and "GROUP BY"
i try to create a table, where i create columns with CASE WHEN, which should be grouped by Candidates. I tried it already many times and searched in forum but i don't get the solution.

```<code>SELECT History.ApplicantId
       ,MAX(Interested)
       from (
       SELECT  History.ApplicantId
               ,CASE WHEN (ActivityId = 88) THEN 1 END AS Interested
From History) a
GROUP BY History.ApplicantId
</code>```

So my result should be two columns. The first one is the applicant and the second if he was interested. 1 or NULL.

But i get 'The multi-part identifier "History.ApplicantId" could not be bound'.

What should i do?

Best regards

答:
We can just aggregate in a single level query:

```<code>SELECT
    ApplicantId,
    MAX(CASE WHEN ActivityId = 88 THEN 1 END) AS Interested
FROM History
GROUP BY ApplicantId;
</code>```

This would report 1 should the applicant be interested, and NULL otherwise.

Body:
i try to create a table, where i create columns with CASE WHEN, which should be grouped by Candidates. I tried it already many times and searched in forum but i don't get the solution.

SELECT History.ApplicantId
       ,MAX(Interested)
       from (
       SELECT  History.ApplicantId
               ,CASE WHEN (ActivityId = 88) THEN 1 END AS Interested
From History) a
GROUP BY History.ApplicantId

So my result should be two columns. The first one is the applicant and the second if he was interested. 1 or NULL.

But i get 'The multi-part identifier "History.ApplicantId" could not be bound'.

What should i do?

Best regards

Body:
We can just aggregate in a single level query:

SELECT
    ApplicantId,
    MAX(CASE WHEN ActivityId = 88 THEN 1 END) AS Interested
FROM History
GROUP BY ApplicantId;

This would report 1 should the applicant be interested, and NULL otherwise.


问:
Android: Your CPU does not support VT-x
Your CPU does not support VT-x.
Intel HAXM is required to run this AVD.
Your CPU does not support VT-x.

Unfortunately, your computer does not support hardware accelerated virtualization.
Here are some of your options:
 1) Use a physical device for testing
 2) Develop on a Windows/OSX computer with an Intel processor that supports VT-x and NX
 3) Develop on a Linux computer that supports VT-x or SVM
 4) Use an Android Virtual Device based on an ARM system image
   (This is 10x slower than hardware accelerated virtualization)

What do I do to get around this limitation?

答:
According to Android Documentation, to run an emulator the development system's CPU should support one of the following virtualization extensions technologies:

Intel Virtualization Technology (VT, VT-x, vmx)

AMD Virtualization (AMD-V, SVM) -- only supported for Linux

Your CPU is Intel Pentium B940, which according to the manufacturer does not support Intel Virtualization Technology (VT-x). That's the reason for this error.

The workaround is to use an alternative Android Emulator, e.g. Genymotion.

Title: Android: Your CPU does not support VT-x


问:
Justify the last line of a div?
I don't think the "why?" of this question is important...but what I need to do is to text-align:justify the last line of text from a DIV. Normally, the last line (or the first if there are no other lines, which is the current case) of a div isn't justified, but aligned left. I know it might not make sense at all, but I absolutely need the last line to be justified!

答:
There is a <s>CSS3</s> IE 5.5/6 (thanks, CSS3.com, NOT!) property called text-justify that can do what you want with:

```<code>text-justify: distribute-all-lines;
</code>```

<s>Not sure about browser support.</s> What a ripoff.

Title: Justify the last line of a div?

Body:
There is a <s>CSS3</s> IE 5.5/6 (thanks, CSS3.com, NOT!) property called text-justify that can do what you want with:

text-justify: distribute-all-lines;

<s>Not sure about browser support.</s> What a ripoff.


问:
How can I refer an object pragmatically in R
```<code>a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000
</code>```

I want to Print each series in programmatic way using a for loop.

```<code>for (i in 1:3)
{
print(paste("a_", i, sep = "")
}
</code>```

Kindly Advise.

答:
to go from a text string to a program in R you have to parse it and then eval it.

```<code>for (i in 1:3) {
  print(eval(parse(text = paste0("a_", i))))
}
</code>```

get makes this nicer:

```<code>for (i in 1:3) {
  print(get(paste0("a_", i)))
}
</code>```

Body:
a_1 <- 1:100;
a_2 <- 10:1000;
a_3 <- 100:10000

I want to Print each series in programmatic way using a for loop.

for (i in 1:3)
{
print(paste("a_", i, sep = "")
}

Kindly Advise.

Body:
to go from a text string to a program in R you have to parse it and then eval it.

for (i in 1:3) {
  print(eval(parse(text = paste0("a_", i))))
}

get makes this nicer:

for (i in 1:3) {
  print(get(paste0("a_", i)))
}


问:
Getting a JSON object from javascript to php
I am sending a JSON object from js to post.php

```<code>$.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:json_str}
});
</code>```

but I am not able to retrieve the result in a post.php file

```<code>$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}
</code>```

答:
Try like this   </p>

```<code>var data = {
        people:{user:'Joe Cooper'}
    };

       $.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:JSON.stringify(data)}
});

<?php
$obj = jsonString2Obj($_POST['jsonobject']);

echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}
</code>```

Body:
I am sending a JSON object from js to post.php

$.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:json_str}
});

but I am not able to retrieve the result in a post.php file

$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}

Body:
Try like this

var data = {
        people:{user:'Joe Cooper'}
    };

       $.ajax({
    type:'post',
    url:'post.php',
    data:{jsonobject:JSON.stringify(data)}
});

<?php
$obj = jsonString2Obj($_POST['jsonobject']);

echo $obj->people->user;

function jsonString2Obj($str){
    return json_decode(stripcslashes($str));
}


答: CSS3 offers a solution for this in the form of text-align-last, see http://www.w3.org/TR/2010/WD-css3-text-20101005/#text-align-last

Title: Justify the last line of a div?

Body: I don't think the "why?" of this question is important...but what I need to do is to text-align:justify the last line of text from a DIV. Normally, the last line (or the first if there are no other lines, which is the current case) of a div isn't justified, but aligned left. I know it might not make sense at all, but I absolutely need the last line to be justified!


问:
How to copy visible pivot item data to a cell in Excel VBA

I have country code in pivot report filter. I would like to get the visible piviot item data and place each values in each cell from A1. I used the code below. But All the cell showing only last value in filter. I need to move automatically from A1 .Help me

```<code>Sub Getpivotitem()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim rng As Range

Set rng = Range("A1:X1")
Set ws = Sheets("Sheet1")

Dim pi As PivotItem
For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
    If pi.Visible = True Then
        For Each cell In rng.Columns
        cell.Value = pi
        Next cell
     End If
Next pi

End Sub
</code>```

答:
Your output is being caused by your nested loop. I think this is what you're looking for</p>

```<code>Sub Getpivotitem()

    Dim ws As Worksheet
    Dim str1 As Variant, Data As Variant
    Dim pi As PivotItem
    Dim rng As Range
    Dim j As Long

    Set ws = Sheets("Sheet1")
    Set rng = Range("A1:X1")

    For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
        If pi.Visible = True Then
            j = j + 1
            ws.cells(1, j) = pi
        End If
    Next pi

End Sub
</code>```

Body:
I have country code in pivot report filter. I would like to get the visible piviot item data and place each values in each cell from A1. I used the code below. But All the cell showing only last value in filter. I need to move automatically from A1 .Help me

Sub Getpivotitem()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim rng As Range

Set rng = Range("A1:X1")
Set ws = Sheets("Sheet1")

Dim pi As PivotItem
For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
    If pi.Visible = True Then
        For Each cell In rng.Columns
        cell.Value = pi
        Next cell
     End If
Next pi

End Sub

Body:
Your output is being caused by your nested loop. I think this is what you're looking for

Sub Getpivotitem()

    Dim ws As Worksheet
    Dim str1 As Variant, Data As Variant
    Dim pi As PivotItem
    Dim rng As Range
    Dim j As Long

    Set ws = Sheets("Sheet1")
    Set rng = Range("A1:X1")

    For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
        If pi.Visible = True Then
            j = j + 1
            ws.cells(1, j) = pi
        End If
    Next pi

End Sub


问:
Migrate GIT commits to existing TFS
I have the following scenario:

The client is using the TFS Source control. A repository is already in place there, containing a version A of the application

A GIT repository was created for the TFS repository. This wasn't made using git-tf or any other application, a folder from TFS was copied in the GIT folder manually

Work was done on GIT repository, and now it contains version B of the application

What we want to achieve now, is move all the commits that were made on GIT into the TFS, so that the TFS will contain the version B of the application and to have one (or more) checkins on TFS to see the changes from version A to version B.

What I was able to find so far was that git-tf can be used to achieve this if the GIT repository is made using git-tf from the TFS source. Since this was not the case for us, is there another way to automatically retrieve the files that were modified on GIT and check them in on the TFS?

Thank you,

答:
Yes git-tfs could help you:

'git tfs quick-clone' giving the last common commit

Then add a remote toward your current git repository and fetch
2bis. Eventually, squash all your commits

Use 'git rebase --onto' to replay all the commits onto the commit you fetch from TFVC (I hope you don't have branches)

Use 'git tfs rcheckin' to push the history to tfvc

Title: Migrate GIT commits to existing TFS


问:
What's the correct way to get a list of users in this bash script?
I have a script that checks each user's home directory for the existence of a maildir and archives old emails accordingly. The way I was doing this is basically this:

```<code>for USER in $(ls /home)
do
<function to check for maildir and remove old files>
</code>```

I ran my script through shellcheck and it gave the the warning

SC2045 - Iterating over ls output is fragile. Use globs.

If I change my script to use for USER in /home/*, it changes the value of $USER:

```<code>for USER in $(ls /home); do echo $USER ; done;
</code>```

gives:

```<code>user1
user2
user3
</code>```

But

```<code>for USER in /home/*; do echo $USER ; done;
</code>```

gives:

```<code>/home/user1
/home/user2
/home/user3
</code>```

and breaks my script in later places.

If I start doing things like parsing /etc/passwd for usernames I'd then need to check if they have home directories etc so it would make the script more complicated for the sake of following best practice. I couldn't work out a way to grep -v out the "/home/" part of the variable values from the second example. What's the correct way to do this?

答:
You can use glob loop like this:

```<code>cd /home

for u in */; do
    echo "${u%/}"
done

cd -
</code>```

*/ only lists directories.

Body:
I have a script that checks each user's home directory for the existence of a maildir and archives old emails accordingly. The way I was doing this is basically this:

for USER in $(ls /home)
do
<function to check for maildir and remove old files>

I ran my script through shellcheck and it gave the the warning

SC2045 - Iterating over ls output is fragile. Use globs.

If I change my script to use for USER in /home/*, it changes the value of $USER:

for USER in $(ls /home); do echo $USER ; done;

gives:

user1
user2
user3

But

for USER in /home/*; do echo $USER ; done;

gives:

/home/user1
/home/user2
/home/user3

and breaks my script in later places.

If I start doing things like parsing /etc/passwd for usernames I'd then need to check if they have home directories etc so it would make the script more complicated for the sake of following best practice. I couldn't work out a way to grep -v out the "/home/" part of the variable values from the second example. What's the correct way to do this?

Body:
You can use glob loop like this:

cd /home

for u in */; do
    echo "${u%/}"
done

cd -

*/ only lists directories.


问:
How to group jquery array
I have two arrays that I need to merge together, they look like so:

```<code>var array1 =
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]
</code>```

and

```<code>var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]
</code>```

I would like to merge them based on x where all properties are kept in the final object.

Expected output:

```<code>var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]
</code>```

I've found $.extend and $.merge but haven't managed to successfully achieve what I need.  Any pointers?

答:
While rest of answers are almost correct, but they miss the point of matching x

var array1 = [{
  x: "1/12/2011",
  y: 4149.9
}, {
  x: "2/12/2011",
  y: 4094.5
}, {
  x: "3/12/2011",
  y: 3606.8
}]

var array2 = [{
  x: "1/12/2011",
  z: 3500
}, {
  x: "2/12/2011",
  z: 3600
}, {
  x: "3/12/2011",
  z: 3700
}]

var excpected = array1.map(item => {
  var fromArray2 = array2.filter(array2Item => array2Item.x === item.x)[0];
  item.z = fromArray2.z;
  return item;
})

console.log(excpected);```

Title: How to group jquery array

Body:
I have two arrays that I need to merge together, they look like so:

var array1 =
[
  {x: "1/12/2011", y: 4149.9}
  {x: "2/12/2011", y: 4094.5}
  {x: "3/12/2011", y: 3606.8}
]

and

var array2 =
[
  {x: "1/12/2011", z: 3500}
  {x: "2/12/2011", z: 3600}
  {x: "3/12/2011", z: 3700}
]

I would like to merge them based on x where all properties are kept in the final object.

Expected output:

var excpected =
[
  {x: "1/12/2011", y: 4149.9, z: 3500}
  {x: "2/12/2011", y: 4094.5, z: 3600}
  {x: "3/12/2011", y: 3606.8, z: 3700}
]

I've found $.extend and $.merge but haven't managed to successfully achieve what I need.  Any pointers?


问:
Sqlite FTS4 Get rows with Order of terms in query
My virtual table is:

```<code>CREATE VIRTUAL TABLE docs USING fts4();

INSERT INTO docs(docid, content) VALUES(1, 'sqlite is a database');
INSERT INTO docs(docid, content) VALUES(2, 'my database is sqlite');
</code>```

When I use this query:

```<code>SELECT * FROM docs WHERE docs MATCH 'sqlite AND database';
</code>```

it returns both 2 records in the table because both of them contain the term "sqlite" and the term "database".

Now, I want to search for records that contain the term "sqlite" and the term "database" with this rule:

The order in which the terms appear in the document has to be the same as the order in which they appear in the query (document with docid 1 only).

Is it possible?

答:
FTS queries cannot restrict the order of terms, except for phrase searches, which require consecutive terms (e.g., "sqlite database" would not match sqlite is a database).

You have to restrict the results afterwards:

```<code>SELECT ... WHERE docs MATCH 'sqlite AND database'
             AND content LIKE '%sqlite%database%';
</code>```

Body:
My virtual table is:

CREATE VIRTUAL TABLE docs USING fts4();

INSERT INTO docs(docid, content) VALUES(1, 'sqlite is a database');
INSERT INTO docs(docid, content) VALUES(2, 'my database is sqlite');

When I use this query:

SELECT * FROM docs WHERE docs MATCH 'sqlite AND database';

it returns both 2 records in the table because both of them contain the term "sqlite" and the term "database".

Now, I want to search for records that contain the term "sqlite" and the term "database" with this rule:

The order in which the terms appear in the document has to be the same as the order in which they appear in the query (document with docid 1 only).

Is it possible?

Body:
FTS queries cannot restrict the order of terms, except for phrase searches, which require consecutive terms (e.g., "sqlite database" would not match sqlite is a database).

You have to restrict the results afterwards:

SELECT ... WHERE docs MATCH 'sqlite AND database'
             AND content LIKE '%sqlite%database%';


问:
What's the best way to select multiple M:N relationships in SQL?
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

```<code>books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)
</code>```

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

答:
You're getting exactly what you described, in the fashion any standard mainstream developer would accomplish the same thing. But apparently it doesn't match your mental expectation as to shape and size.

Start by taking 3 books, with varying numbers of authors and subjects, and just list what you would like to see. Then we can discuss how to get there.

I don't think you'll find any square grid that gets you there. Probably you want something more like a tree structure?

```
+ Title 1
+----+ Authors
     + ---- Author 1
     + ---- Author 2
+    + Topics
     + ---- Topic A
etc.
```

Anything along these lines I find is easiest to derive using mapping tools in another abstraction layer; although there are ways to twist relational data that can help, if you have the skills (e.g. analytical cubes and queries, returning dependent secondary queries, etc.) They usually involve proprietary extensions (e.g. LINQ); but you probably don't want to go to the more sophisticated (read: complex) stuff until you've thoroughly mastered stuff like this.

OwnerDisplayName: Ben Blank

Body:
I've embarked on a project which is encouraging me to expand my knowledge of SQL.  I've already learned quite a bit, but I've gotten myself to a point where I can see a problem, but I don't know enough to properly research a solution.  I've hit SO, Google, and the MySQL docs, but either I'm asking the wrong questions or I don't know how to ask the right ones.  My data is structured with three primary tables, one of which has M:N relationships with the other two.  I'm storing those relationships in another pair of tables, as I'm under the impression that's the "best way":

books (book_id INT PRIMARY KEY, book_title VARCHAR)
authors (author_id INT PRIMARY KEY, author_name VARCHAR)
subjects (subject_id INT PRIMARY KEY, subject_name VARCHAR)
book_authors (book_id INT, author_id INT)
book_subjects (book_id INT, subject_id INT)

(The first three tables actually have more than two columns, but they aren't relevant.)

Edit:

Obviously, I suck at asking clear questions, but then I already knew that. :-)

The issue I'm trying to solve is how to most effectively/efficiently get the data from the database into my app. Once I have it there, I can rearrange it however I need, and I trust I can do that regardless of how the data is "shaped" coming out of the database. It would be trivial to do with five separate SELECT * FROM … statements and it would be trivial to do with with the cross-product "frankenjoin" I had posted earlier. However, I know enough about SQL to spot that the former robs the database engine of the opportunity to do its job. I don't know enough about SQL to say whether the latter is equally bad.

So how about this: instead of asking what's wrong with the solution I came up with, what would be your solution? If you had data related this way, how would you select it out of the database? (And for what reasons?) Would you perhaps even arrange the tables differently?

LastEditorDisplayName: Ben Blank

Body:
You're getting exactly what you described, in the fashion any standard mainstream developer would accomplish the same thing. But apparently it doesn't match your mental expectation as to shape and size.

Start by taking 3 books, with varying numbers of authors and subjects, and just list what you would like to see. Then we can discuss how to get there.

I don't think you'll find any square grid that gets you there. Probably you want something more like a tree structure?

+ Title 1
+----+ Authors
     + ---- Author 1
     + ---- Author 2
+    + Topics
     + ---- Topic A
etc.

Anything along these lines I find is easiest to derive using mapping tools in another abstraction layer; although there are ways to twist relational data that can help, if you have the skills (e.g. analytical cubes and queries, returning dependent secondary queries, etc.) They usually involve proprietary extensions (e.g. LINQ); but you probably don't want to go to the more sophisticated (read: complex) stuff until you've thoroughly mastered stuff like this.

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


问:
How to add custom template in a datepicker.?
Im using bootstrap datepicker http://bootstrap-datepicker.readthedocs.io/en/latest/ for my project and I would like to know how can I add the custom icon for a particular day. My requirements is adding icons for events on a particular date.

the image shows the output (icon on 15th day) which i required. Looking forward for a solutions. Thanks in advance. :)

code which i used.

```<code> $('.datepicker').datepicker({
        keyboardNavigation: false,
        forceParse: false,
        templates:{
            leftArrow: '<i class="material-icons icon-30">keyboard_arrow_left</i>',
            rightArrow: '<i class="material-icons icon-30">keyboard_arrow_right</i>',
        },
        beforeShowDay: function(date){
            var d = date;
            var curr_date = d.getDate();
            var curr_month = d.getMonth() + 1; //Months are zero based
            var curr_year = d.getFullYear();
            var formate_date = curr_date + "/" + curr_month + "/" + curr_year
            if ($.inArray(formate_date, specific_date) != -1){
                return {
                    classes: 'addIcon' // Here i want to add an icon for a partiicular date.
                };
            }
        }

    });
</code>```

答:
You can use add class in your specific day using beforeShowDay event

```<code>var specific_date = ["15/12/2017","16/12/2017"];
beforeShowDay: function(date){
    var d = date;
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    var formate_date = curr_date + "/" + curr_month + "/" + curr_year
    if ($.inArray(formate_date, specific_date) != -1){
        return {
            classes: 'addIcon'
        };
    }
    return;
}
</code>```

then you can add anything using css

```<code>.addIcon::after{
    content: "\25CF";
    font-size:10px;
    color: blue;
    position: absolute;
    bottom: -6px;
    left: 12px;
  }
  .day{
    position: relative;
  }
</code>```

Body:
Im using bootstrap datepicker http://bootstrap-datepicker.readthedocs.io/en/latest/ for my project and I would like to know how can I add the custom icon for a particular day. My requirements is adding icons for events on a particular date.

the image shows the output (icon on 15th day) which i required. Looking forward for a solutions. Thanks in advance. :)

code which i used.

 $('.datepicker').datepicker({
        keyboardNavigation: false,
        forceParse: false,
        templates:{
            leftArrow: 'keyboard_arrow_left',
            rightArrow: 'keyboard_arrow_right',
        },
        beforeShowDay: function(date){
            var d = date;
            var curr_date = d.getDate();
            var curr_month = d.getMonth() + 1; //Months are zero based
            var curr_year = d.getFullYear();
            var formate_date = curr_date + "/" + curr_month + "/" + curr_year
            if ($.inArray(formate_date, specific_date) != -1){
                return {
                    classes: 'addIcon' // Here i want to add an icon for a partiicular date.
                };
            }
        }

    });

Body:
You can use add class in your specific day using beforeShowDay event

var specific_date = ["15/12/2017","16/12/2017"];
beforeShowDay: function(date){
    var d = date;
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero based
    var curr_year = d.getFullYear();
    var formate_date = curr_date + "/" + curr_month + "/" + curr_year
    if ($.inArray(formate_date, specific_date) != -1){
        return {
            classes: 'addIcon'
        };
    }
    return;
}

then you can add anything using css

.addIcon::after{
    content: "\25CF";
    font-size:10px;
    color: blue;
    position: absolute;
    bottom: -6px;
    left: 12px;
  }
  .day{
    position: relative;
  }


问:
Xampp control panel is not showing
My Xampp control panel is not showing in the desktop (Windows 10), but can only up the servers through the shortcut (minimized option in the task bar).

As follows:

I have close the application without stopping the servers, will that be the case of this matter?

答:
Here it's the easiest solution.

Right-click xampp.exe and go to xampp folder

Find and delete the following files xampp-control.ini - xampp-control.log

Restart xampp

Title: Xampp control panel is not showing


问:
Split a data.frame column into others columns
I have a big data.frame with some columns, but my 9th column is made of data separated by semicolon :

```<code>    gtf$V9
1                 gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
2  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
3  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
4  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
</code>```

So I would like to cut this column into others columns and merge this later with the other part of the data.frame (the others columns before the 9th column).

I've tried some code without results :

```<code>head(gtf$V9, sep = ";",stringsAsFactors = FALSE)
</code>```

or

```<code>new_df <- matrix(gtf$V9, ncol=7, byrow=TRUE) # sep = ";"
</code>```

The same thing with as.data.frame, data.frame or as.matrix

I have also tried to write.csv and import this with includ a sep=";", but the data.frame is too bigger and my computer is lagging..

Any advice?

答:
you could do strsplit() within a sapply()

If you know how many objects can be in V9 than you can do a for loop over it

```<code>for (i in 1:number_of_max_objects_in_V9) {
 gtf[ncol(gtf)+1] = sapply(1:nrow(gtf), function(x) strsplit(gtf$V9[x],',')[[1]][i])
}
</code>```

if you don't know how many objects can V9 have, then just run a str_count on , in gtf$V9 like this:

```<code>library(stringr)
number_of_max_objects_in_V9 <- max(sapply(1:nrow(gtf), function(x) str_count(gtf$V9,',')))
</code>```

Body:
I have a big data.frame with some columns, but my 9th column is made of data separated by semicolon :

    gtf$V9
1                 gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
2  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
3  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
4  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;

So I would like to cut this column into others columns and merge this later with the other part of the data.frame (the others columns before the 9th column).

I've tried some code without results :

head(gtf$V9, sep = ";",stringsAsFactors = FALSE)

or

new_df <- matrix(gtf$V9, ncol=7, byrow=TRUE) # sep = ";"

The same thing with as.data.frame, data.frame or as.matrix

I have also tried to write.csv and import this with includ a sep=";", but the data.frame is too bigger and my computer is lagging..

Any advice?

Body:
you could do strsplit() within a sapply()

If you know how many objects can be in V9 than you can do a for loop over it

for (i in 1:number_of_max_objects_in_V9) {
 gtf[ncol(gtf)+1] = sapply(1:nrow(gtf), function(x) strsplit(gtf$V9[x],',')[[1]][i])
}

if you don't know how many objects can V9 have, then just run a str_count on , in gtf$V9 like this:

library(stringr)
number_of_max_objects_in_V9 <- max(sapply(1:nrow(gtf), function(x) str_count(gtf$V9,',')))


问:
Can I get Erlang OTP behaviors in C Nodes?
For example, right now I have a C Node (call it CN) which connects to an erlang node (call it EN) and uses a RPC to use OTP behaviors. Hence, to send an event from CN to an event manager on EN I connect CN to EN and do

```<code>args = erl_format("[data_man, {~f, ~f}]", ch.at(0), ch.at(1));
erl_rpc_to(fd, "gen_event", "notify", args);
</code>```

But, then, my C Node really isn't behaving as a node (i.e. why create a node that only uses remote procedure calls?).

Is there a way to directly use OTP behaviors within a C Node?

If there isn't, should I look under the hood at the message formats being used by OTP and send messages using that format (i.e. can I spoof OTP behaviors?)? I don't like this idea, I'll have to watch for changes in the implementation of OTP etc.

I have hard latency limits in my requirements, how does this effect my choice of communication between a C process and Erlang (are RPCs going to bog me down? etc.)?

答:
There is no way to directly use OTP behaviours from C. I also don't think you should mimic the OTP behaviours to use them directly.

You should just first use RPC and then test your code against your performance requirements. If needed, you could always send a simple message to your gen_event process to make it notify itself through its handle_info/2 method.

Body:
For example, right now I have a C Node (call it CN) which connects to an erlang node (call it EN) and uses a RPC to use OTP behaviors. Hence, to send an event from CN to an event manager on EN I connect CN to EN and do

args = erl_format("[data_man, {~f, ~f}]", ch.at(0), ch.at(1));
erl_rpc_to(fd, "gen_event", "notify", args);

But, then, my C Node really isn't behaving as a node (i.e. why create a node that only uses remote procedure calls?).

Is there a way to directly use OTP behaviors within a C Node?

If there isn't, should I look under the hood at the message formats being used by OTP and send messages using that format (i.e. can I spoof OTP behaviors?)? I don't like this idea, I'll have to watch for changes in the implementation of OTP etc.

I have hard latency limits in my requirements, how does this effect my choice of communication between a C process and Erlang (are RPCs going to bog me down? etc.)?


问:
Reload Angular 4+ route with the same URL parameter
I've been doing some research into reloading an Angular 4+ route and it looks as if the preferred method is to instead listen to URL parameter changes within the component and re-initialise the component there instead.

The issue I'm having is in trying to find a DRY (don't repeat yourself) approach to make this work across multiple components, when the URL would be identical (including parameters). In AngularJS this was simple with UI-router.

Use case:

I have a notification panel which can "float" above any route, when a notification is clicked it needs to go to the content it relates to - this can be many different types of content.

For example: /posts/:id or /groups/:id or /users/:id

If the user is already looking at that content it doesn't reload and refresh to reflect the message of the notification. I.e "John Doe commented on your post" (the user could be looking at an outdated version of that post) or "Jane Doe accepted your request to join Some Group" (the user could be looking at the guest view of that group).

I did look into using window.location.reload() when detecting that the route is the same, and that works, but it's highly undesirable due to the overhead it causes (angular reinitialising, auth check, socket reconnection, etc).

Any suggestions would be greatly appreciated!

答:
In this case your route doesn't change, just your parameters change.

To solve this problem you need to subscribe to the ActivatedRoute params.

```<code>export class MyClass implements OnInit {
   constructor(private activatedRoute: ActivatedRoute ) {
        this.activatedRoute.params.subscribe((params)=>{
          console.log('updatedParams', params);
        });
    }
}
</code>```

Body:
In this case your route doesn't change, just your parameters change.

To solve this problem you need to subscribe to the ActivatedRoute params.

export class MyClass implements OnInit {
   constructor(private activatedRoute: ActivatedRoute ) {
        this.activatedRoute.params.subscribe((params)=>{
          console.log('updatedParams', params);
        });
    }
}


答:
You can array#concat your array and then use array#reduce to merge them based on value of x.

var array1 = [ {x: "1/12/2011", y: 4149.9}, {x: "2/12/2011", y: 4094.5}, {x: "3/12/2011", y: 3606.8} ],
    array2 = [ {x: "1/12/2011", z: 3500}, {x: "2/12/2011", z: 3600}, {x: "3/12/2011", z: 3700} ];

var result = array1
              .concat(array2)
              .reduce((r, o) => {
                r[o.x] = Object.assign({},r[o.x] || {}, o);
                return r;
              },{});
var output = Object.values(result);
console.log(output);```

Title: How to group jquery array


问:
saving swifty json array to user defaults
i have a json data which gives the following information:

```<code>let data = [
  {
    "QuestionTitle" : "Entomology is the science that studies",
    "Id" : 205,
    "Options" : [
      { "Option" : "Insects", "Id" : 810 },
      { "Option" : "The origin and history of technical and scientific terms", "Id" : 811 },
      { "Option" : "The formation of rocks", "Id" : 812 },
      { "Option" : "Behavior of human beings", "Id" : 809 }
    ]
  },
  {
    "QuestionTitle" : "A train running at the speed of 60 km\/hr crosses a pole in 9 seconds. What is the length of the train?",
    "Id" : 199,
    "Options" : [
      { "Option" : "120 metres", "Id" : 785 },
      { "Option" : "324 metres", "Id" : 787 },
      { "Option" : "180 metres", "Id" : 786 },
      { "Option" : "150 metres", "Id" : 788 }
    ]
  }
]
</code>```

I am using swiftyjson. I want to save the entire array using nsuserdefaults.

```<code>GlobalVar.defaults.set(json, forKey: "questionArray")
GlobalVar.defaults.synchronize()
</code>```

However, I get an error

"[User Defaults] Attempt to set a non-property-list object".

Please assist i am new to swift. I have also checked other similar questions but seems to not work.

答:
Swift 4.0 | Xcode 9.1 | SwiftyJSON

We can save array of dictionary directly, no problem.
Only, the problem is, how to retrieve it?

It barely downcast to array of dictionary (say [[String : Any]]). for this, we required SwiftyJSON pods import SwiftyJSON // Don't forget this

```<code>let arrayOfDictionary = [
                         {
                           "VersionNumber" : "1.0.0.0",
                                  "FormID" : "18"
                          },
                         {
                           "VersionNumber" : "1.0.0.3",
                                  "FormID" : "19"
                          }
                         ]
</code>```

Saving it directly to UserDefaults like :

```<code>UserDefaults.standard.set(saveFormDetails, forKey: "FormDetails")
</code>```

Retrieving from UserDefaults :

```<code>let savedFormDetailsData = JSON.init(rawValue:UserDefaults.standard.array(forKey: "FormDetails"))
</code>```

Now, savedFormDetailsData is the array of dictionary back [PropertyList Type], for further we do :

```<code>for form in 0..<arrayOfDictionary.count {
    print("FormID :", savedFormDetailsData?[form]["FormID"])
    print("VersionNumber :", savedFormDetailsData?[form]["VersionNumber"])
}
</code>```

Body:
i have a json data which gives the following information:

let data = [
  {
    "QuestionTitle" : "Entomology is the science that studies",
    "Id" : 205,
    "Options" : [
      { "Option" : "Insects", "Id" : 810 },
      { "Option" : "The origin and history of technical and scientific terms", "Id" : 811 },
      { "Option" : "The formation of rocks", "Id" : 812 },
      { "Option" : "Behavior of human beings", "Id" : 809 }
    ]
  },
  {
    "QuestionTitle" : "A train running at the speed of 60 km\/hr crosses a pole in 9 seconds. What is the length of the train?",
    "Id" : 199,
    "Options" : [
      { "Option" : "120 metres", "Id" : 785 },
      { "Option" : "324 metres", "Id" : 787 },
      { "Option" : "180 metres", "Id" : 786 },
      { "Option" : "150 metres", "Id" : 788 }
    ]
  }
]

I am using swiftyjson. I want to save the entire array using nsuserdefaults.

GlobalVar.defaults.set(json, forKey: "questionArray")
GlobalVar.defaults.synchronize()

However, I get an error

"[User Defaults] Attempt to set a non-property-list object".

Please assist i am new to swift. I have also checked other similar questions but seems to not work.

Body:
Swift 4.0 | Xcode 9.1 | SwiftyJSON

We can save array of dictionary directly, no problem.
Only, the problem is, how to retrieve it?

It barely downcast to array of dictionary (say [[String : Any]]). for this, we required SwiftyJSON pods import SwiftyJSON // Don't forget this

let arrayOfDictionary = [
                         {
                           "VersionNumber" : "1.0.0.0",
                                  "FormID" : "18"
                          },
                         {
                           "VersionNumber" : "1.0.0.3",
                                  "FormID" : "19"
                          }
                         ]

Saving it directly to UserDefaults like :

UserDefaults.standard.set(saveFormDetails, forKey: "FormDetails")

Retrieving from UserDefaults :

let savedFormDetailsData = JSON.init(rawValue:UserDefaults.standard.array(forKey: "FormDetails"))

Now, savedFormDetailsData is the array of dictionary back [PropertyList Type], for further we do :

for form in 0..<arrayOfDictionary.count {
    print("FormID :", savedFormDetailsData?[form]["FormID"])
    print("VersionNumber :", savedFormDetailsData?[form]["VersionNumber"])
}


问:
Why am I unable to delete objects (JavaScript)?
I've got the below code and I can't seem to find a way to remove the mainThumbs from the thumbs object. I've tried with splice(0,(mainThumbs.length - 1)), shift, delete thumbs[0] and nothing seems to work. The functions render the following error 'Uncaught TypeError: thumbs.shift() is not a function' while the delete thumbs[0] just returns the thumbs whole and untouched.

```<code>var thumbs      = document.querySelectorAll('.thumbnail');
var mainThumbs  = document.querySelectorAll('.main-thumbnail');

for(var i = 0; i < mainThumbs.length; i++){
    delete thumbs[0];

    console.log(thumbs);
}
</code>```

This is how mainThumbs looks like:

```<code>(3) [div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail]
</code>```

This is what the console outputs for thumbs:

```<code>(12) [div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.modal-open, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail]
</code>```

and the typeOf thumbs and mainThumbs is object

Can anyone explain why I can't seem to be able to remove the mainThumbs from the thumbs object?
I would also like a solution with splice rather than delete or shift as I find it to be more accurate.

答:
document.querySelectorAll does not return an array. In some ways the object is array-like, but not in all.

Your approach to this problem is over-complicated though. Instead of getting all the elements that are .thumbnail and then trying to remove the ones which are .main-thumbnail, just make one search using the negation pseudo-class:

```<code>var non_main_thumbs = document.querySelectorAll('.thumbnail:not(.main-thumbnail)');
</code>```

Body:
I've got the below code and I can't seem to find a way to remove the mainThumbs from the thumbs object. I've tried with splice(0,(mainThumbs.length - 1)), shift, delete thumbs[0] and nothing seems to work. The functions render the following error 'Uncaught TypeError: thumbs.shift() is not a function' while the delete thumbs[0] just returns the thumbs whole and untouched.

var thumbs      = document.querySelectorAll('.thumbnail');
var mainThumbs  = document.querySelectorAll('.main-thumbnail');

for(var i = 0; i < mainThumbs.length; i++){
    delete thumbs[0];

    console.log(thumbs);
}

This is how mainThumbs looks like:

(3) [div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail]

This is what the console outputs for thumbs:

(12) [div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.main-thumbnail, div.thumbnail.modal-open, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail, div.thumbnail]

and the typeOf thumbs and mainThumbs is object

Can anyone explain why I can't seem to be able to remove the mainThumbs from the thumbs object?
I would also like a solution with splice rather than delete or shift as I find it to be more accurate.

Body:
document.querySelectorAll does not return an array. In some ways the object is array-like, but not in all.

Your approach to this problem is over-complicated though. Instead of getting all the elements that are .thumbnail and then trying to remove the ones which are .main-thumbnail, just make one search using the negation pseudo-class:

var non_main_thumbs = document.querySelectorAll('.thumbnail:not(.main-thumbnail)');


问:
How to inspect a closure in php?
I have a function that is being passed a Closure. I want to find out the name of the method that closure is derived from. When I call print_r, it outputs this:

```<code>Closure Object
(
  [static] => Array
    (
      [listener] => Event_Subscriber_Calq@vendor_product_created
      [container] => Illuminate\Foundation\Application Object
...
</code>```

How do I acess that listener value? I tried ->static, ::$static, getStatic(), I can't think of any way to get the value.

Currently, my plan is to use output buffering to capture the output from a var_dump. I can't use print_r for this, because the closure contains a reference to and object that references itself, and print_r takes ages to handle the recursion. I also can't use var_export, because it does not include the value I want in the output. So, this is my solution:

```<code>ob_start();
var_dump($closure);
$data = ob_get_clean();
$data = preg_replace('#^([^\n]*\n){4}#', '', $data);
$data = preg_replace('#\n.*#', '', $data);
$data = preg_replace('#.*string.[0-9]+. "(.*)".*#', '\1', $data);
list($class, $method) = explode('@', $data);
</code>```

Which is horrible. Is there another way to do this? Maybe using reflection?

答:
I know this post is old, but in case someone is looking for info,
you need to use ReflectionFunction:

```<code>$r = new ReflectionFunction($closure);
var_dump($r, $r->getStaticVariables(), $r->getParameters());
</code>```

Regards,
Alex

Title: How to inspect a closure in php?

Body:
I have a function that is being passed a Closure. I want to find out the name of the method that closure is derived from. When I call print_r, it outputs this:

Closure Object
(
  [static] => Array
    (
      [listener] => Event_Subscriber_Calq@vendor_product_created
      [container] => Illuminate\Foundation\Application Object
...

How do I acess that listener value? I tried ->static, ::$static, getStatic(), I can't think of any way to get the value.

Currently, my plan is to use output buffering to capture the output from a var_dump. I can't use print_r for this, because the closure contains a reference to and object that references itself, and print_r takes ages to handle the recursion. I also can't use var_export, because it does not include the value I want in the output. So, this is my solution:

ob_start();
var_dump($closure);
$data = ob_get_clean();
$data = preg_replace('#^([^\n]*\n){4}#', '', $data);
$data = preg_replace('#\n.*#', '', $data);
$data = preg_replace('#.*string.[0-9]+. "(.*)".*#', '\1', $data);
list($class, $method) = explode('@', $data);

Which is horrible. Is there another way to do this? Maybe using reflection?

Body:
I know this post is old, but in case someone is looking for info,
you need to use ReflectionFunction:

$r = new ReflectionFunction($closure);
var_dump($r, $r->getStaticVariables(), $r->getParameters());

Regards,
Alex


问:
Can an author's unique "literary style" be used to identify him/her as the author of a text?
Let's imagine, I have two English language texts written by the same person.
Is it possible to apply some Markov chain algorithm to analyse each: create some kind of fingerprint based on statistical data, and compare fingerprints gotten from different texts?
Let's say, we have a library with 100 texts. Some person wrote text number 1 and some other as well, and we need to guess which one by analyzing his/her writing style.
Is there any known algorithm doing it? Can be Markov chains applied here?</p>

答: You might start with a visit to the Apache Mahout web site. There is a giant literature on classification and clustering. Essentially, you want to run a clustering algorithm, and then hope that 'which writer' determines the clusters.</p>


问:
hibernate foreign key is updating all fields in ref table
I am new to this forum and hibernate. I am having a problem with hibernate many-to-one mapping.

```<code>@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "DTE_ID")
@NotNull
private Dte raisedByDte;
</code>```

This is the code I am using in main object and foreign key is DTE_ID. But when I am trying to save it is updating all fields in referenced table. My reference object is as follows:

```<code>@Entity
@Table(name = "DTE_MASTERS",  uniqueConstraints = @UniqueConstraint(columnNames = "DTE_NAME"))
public class Dte {

   @Id
   @Column(name="DTE_ID", updatable = false, nullable = false)
   private int dte_id;
   @Column(name="DTE_NAME")
   private String dte_name;

   public Dte() {
      super();
      // TODO Auto-generated constructor stub
   }
   public Dte(int dte_id, String dte_name) {
      super();
      this.dte_id = dte_id;
      this.dte_name = dte_name;
   }
   public int getDte_id() {
      return dte_id;
   }
   public void setDte_id(int dte_id) {
      this.dte_id = dte_id;
   }
   public String getDte_name() {
      return dte_name;
   }
   public void setDte_name(String dte_name) {
      this.dte_name = dte_name;
   }
</code>```

I want to restrict the update of DTE_MASTERS when I am inserting ..can some body please guide me through this?

答:
You have to remove the cascade option from the mapping. It enforces the same operation as was performed on the parent object.
I am guessing that you are doing merge() on the main object.. and with that option, the merge() (which would result in an update if the entity is not new) will also be invoked on the Dte dependency:

```<code>@ManyToOne(fetch = FetchType.EAGER)
</code>```

Also, keep in mind that if you any non-transient field within the Dte entity once its loaded with the main entity, all of the changes will be commited implicilty upon the transaction end.

In order to prevent that you would need to perform session.evict(dte); so that any changes will not get persisted in the database even if they were performed in within the transactional method.

Body:
I am new to this forum and hibernate. I am having a problem with hibernate many-to-one mapping.

@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name = "DTE_ID")
@NotNull
private Dte raisedByDte;

This is the code I am using in main object and foreign key is DTE_ID. But when I am trying to save it is updating all fields in referenced table. My reference object is as follows:

@Entity
@Table(name = "DTE_MASTERS",  uniqueConstraints = @UniqueConstraint(columnNames = "DTE_NAME"))
public class Dte {

   @Id
   @Column(name="DTE_ID", updatable = false, nullable = false)
   private int dte_id;
   @Column(name="DTE_NAME")
   private String dte_name;

   public Dte() {
      super();
      // TODO Auto-generated constructor stub
   }
   public Dte(int dte_id, String dte_name) {
      super();
      this.dte_id = dte_id;
      this.dte_name = dte_name;
   }
   public int getDte_id() {
      return dte_id;
   }
   public void setDte_id(int dte_id) {
      this.dte_id = dte_id;
   }
   public String getDte_name() {
      return dte_name;
   }
   public void setDte_name(String dte_name) {
      this.dte_name = dte_name;
   }

I want to restrict the update of DTE_MASTERS when I am inserting ..can some body please guide me through this?

Body:
You have to remove the cascade option from the mapping. It enforces the same operation as was performed on the parent object.
I am guessing that you are doing merge() on the main object.. and with that option, the merge() (which would result in an update if the entity is not new) will also be invoked on the Dte dependency:

@ManyToOne(fetch = FetchType.EAGER)

Also, keep in mind that if you any non-transient field within the Dte entity once its loaded with the main entity, all of the changes will be commited implicilty upon the transaction end.

In order to prevent that you would need to perform session.evict(dte); so that any changes will not get persisted in the database even if they were performed in within the transactional method.


问:
How to extract some data from url using Python
I have an url as follows:

```<code>https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400
</code>```

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

```<code>furl(url).args['category'] // gives PASSENGER
</code>```

But here I do not have the name of the parameter.

How can I do that?

答:
The string that you are after is not a query parameter, it is part of the URL path.

In the general case you can use the urllib.parse module to parse the URL into its components, then access the path. Then extract the required part of the path:

```<code>import base64
from urllib.parse import urlparse, parse_qs

parsed_url = urlparse(url)
s = parsed_url.path.split('/')[-2]    # second last component of path
>>> s
'ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0='
>>> base64.b64decode(s)
b'eLNfekw2jMDqWm0CDoFWzK+DAchq8p0eglRxD4+g2LxdArxObu3WZQ=='
</code>```

The keys and values of the query string can also be processed into a dictionary and accessed by key:

```<code>params = parse_qs(parsed_url.query)
>>> params
{'category': ['PASSENGER'], 'make': ['30'], 'model': ['124'], 'regmonth': ['3'], 'regdate': ['2015-03'], 'body': ['443,4781'], 'facelift': ['252'], 'seats': ['4'], 'bodyHeight': ['443'], 'bodyLength': ['443'], 'weight': ['-1'], 'engine': ['1394'], 'wheeldrive': ['196'], 'transmission': ['400']}
>>> params['category']
['PASSENGER']
</code>```

Body:
I have an url as follows:

https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

furl(url).args['category'] // gives PASSENGER

But here I do not have the name of the parameter.

How can I do that?

Body:
The string that you are after is not a query parameter, it is part of the URL path.

In the general case you can use the urllib.parse module to parse the URL into its components, then access the path. Then extract the required part of the path:

import base64
from urllib.parse import urlparse, parse_qs

parsed_url = urlparse(url)
s = parsed_url.path.split('/')[-2]    # second last component of path
>>> s
'ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0='
>>> base64.b64decode(s)
b'eLNfekw2jMDqWm0CDoFWzK+DAchq8p0eglRxD4+g2LxdArxObu3WZQ=='

The keys and values of the query string can also be processed into a dictionary and accessed by key:

params = parse_qs(parsed_url.query)
>>> params
{'category': ['PASSENGER'], 'make': ['30'], 'model': ['124'], 'regmonth': ['3'], 'regdate': ['2015-03'], 'body': ['443,4781'], 'facelift': ['252'], 'seats': ['4'], 'bodyHeight': ['443'], 'bodyLength': ['443'], 'weight': ['-1'], 'engine': ['1394'], 'wheeldrive': ['196'], 'transmission': ['400']}
>>> params['category']
['PASSENGER']


问:
Get elements to align
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

```<code>var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});
</code>```

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boards-container">
  <div class="boards">
      <div class="board">
        <p>1st Event</p>
        <p>2nd Event</p>
        <p>3rd Event 3rd Event 3rd Event 3rd Event 3rd Event</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st News</p>
      </div>
      <div class="board">
        (This should align at bottom)
        <p>1st Gallery</p>
        <p>2nd Gallery</p>
        <p>3rd Gallery</p>
      </div>
  </div>
</div></code>```

NEED ANSWER TO WORK IN IE9+ aswell

答:
Depending on your overall desired outcome.
It might be as simple as setting some css on those boards - position:absolute and bottom:0</p>

Title: Get elements to align

Body:
I'm currently working on some black boards on my website and sometimes the content isn't the same size in each black board.

so what I've currently got is as following:

Achieved this by using the following code:

var biggestHeight = 0;
$('.board .content').each(function(){
    if(biggestHeight === 0) biggestHeight = $(this).height();
    if(biggestHeight < $(this).height()) bigghestHeight = $(this).height();
});
biggestHeight = biggestHeight + 15;
$('.board .content').css({
    "height" : biggestHeight + "px",
});

I want the boards to be like this: but I want the boards to be different sizes depending on the content size, however I want the boards to be aligned at the bottom behind the grass like the first picture.

Simple example to reproduce the problem (Not exactly reproduced):

.board{
  display: inline-block;
  background: gray;
  width: 30%;
  float: left;
  margin-left: 5px;
}
#boards-container{
  position: relative;
  width: 400px;
}
#boards-container .boards{
  position: absolute
}

1st Event

2nd Event

3rd Event 3rd Event 3rd Event 3rd Event 3rd Event

        (This should align at bottom)

1st News

        (This should align at bottom)

1st Gallery

2nd Gallery

3rd Gallery

NEED ANSWER TO WORK IN IE9+ aswell


问:
Ignore Sundays from jQuery date range picker
I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/

I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.

I tried to do something with beforeShowDay option :

```<code>beforeShowDay: function(t) {
  var valid = t.getDay() !== 0; //disable sunday
  var _class = '';
  // var _tooltip = valid ? '' : 'weekends are disabled';
  return [valid, _class];
}
</code>```

but it only "disables" all Sundays whereas I want to remove / hide them:

Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/

EDIT:
Updated fiddle with @Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/

答:
You can also do it by setting a custom css class and use it in beforeShowDay like below

```<code>.hideSunDay{
   display:none;
  }

   beforeShowDay: function(t) {
      var valid = t.getDay() !== 0; //disable sunday
      var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
      // var _tooltip = valid ? '' : 'weekends are disabled';
      return [valid, _class];
    }
</code>```

But it only hides the sundays beginning from current day.

Here is a working fiddle

https://jsfiddle.net/dnbd01do/16/

Body:
I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/

I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.

I tried to do something with beforeShowDay option :

beforeShowDay: function(t) {
  var valid = t.getDay() !== 0; //disable sunday
  var _class = '';
  // var _tooltip = valid ? '' : 'weekends are disabled';
  return [valid, _class];
}

but it only "disables" all Sundays whereas I want to remove / hide them:

Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/

EDIT:
Updated fiddle with @Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/

Body:
You can also do it by setting a custom css class and use it in beforeShowDay like below

.hideSunDay{
   display:none;
  }

   beforeShowDay: function(t) {
      var valid = t.getDay() !== 0; //disable sunday
      var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
      // var _tooltip = valid ? '' : 'weekends are disabled';
      return [valid, _class];
    }

But it only hides the sundays beginning from current day.

Here is a working fiddle

https://jsfiddle.net/dnbd01do/16/


问:
Vagrant : An AMI must be configured via "ami" (region: #{region})
I got an error as below when run vagrant command,

```<code> # vagrant up --provider=aws
</code>```

There are errors in the configuration of this machine. Please fix
the following errors and try again:

AWS Provider:
* An AMI must be configured via "ami" (region: #{region})

I'm using Vagrant 2.0.1 with vagrant-aws 0.7.2

Vagrant file:

```<code>Vagrant.configure("2") do |config|
    require 'vagrant-aws'
    Vagrant.configure('2') do |config|
        config.vm.box = 'Vagarent'
        config.vm.provider 'aws' do |aws, override|
        aws.access_key_id = "xxxxxxxxxxxxxxxxxx"
        aws.secret_access_key = "xxxxxxxxxxxxxxxxxxxxxxxx"
        aws.keypair_name = 'ssh-keypair-name'
        aws.instance_type = "t2.micro"
        aws.region = 'us-west-2a'
        aws.ami = 'ami-1122298f0'
        aws.security_groups = ['default']
        override.ssh.username = 'ubuntu'
        override.ssh.private_key_path = '~/.ssh/ssh-keypair-file'
      end
    end
</code>```

How to solve it?

答:
Going through "vagrant-aws" documentation, following worked for me.

Installed "vagrant-aws" plugin with shell:

```<code>vagrant plugin install vagrant-aws
</code>```

Added AWS compatible 'dummy-box' named "aws" added in config.vm.box = "aws":

```<code>vagrant box add aws https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box
</code>```

Created following Vagrant file:

```<code># Require the AWS provider plugin
require 'vagrant-aws'
Vagrant.configure(2) do |config|
  config.vm.box = "aws"
  config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"

  config.vm.provider :aws do |aws, override|
     aws.access_key_id = ENV['AWS_ACCESS_KEY']
     aws.secret_access_key = ENV['AWS_SECRET_KEY']
     aws.region = "us-east-1"
     #aws.availability_zone = "us-east-1c"

     # EC2 Instance AMI
     aws.ami =  "ami-aa2ea6d0" # Ubuntu 16.04 in US-EAST
     aws.keypair_name = "awswindows" #change as per your key
     aws.instance_type = "t2.micro"
     aws.block_device_mapping = [{ 'DeviceName' => '/dev/sda1', 'Ebs.VolumeSize' => 10 }]
     aws.security_groups = ["YOUR_SG"]
     aws.tags = {
        'Name' => 'Vagrant EC2 Instance'
        }
    # Credentials to login to EC2 Instance
    override.ssh.username = "ubuntu"
    override.ssh.private_key_path = ENV['AWS_PRIVATE_KEY']
  end

end
</code>```

Fired vagrant up --provider=aws.

Check once and let me know if you face any issue.

Body:
I got an error as below when run vagrant command,

 # vagrant up --provider=aws

There are errors in the configuration of this machine. Please fix
the following errors and try again:

AWS Provider:
* An AMI must be configured via "ami" (region: #{region})

I'm using Vagrant 2.0.1 with vagrant-aws 0.7.2

Vagrant file:

Vagrant.configure("2") do |config|
    require 'vagrant-aws'
    Vagrant.configure('2') do |config|
        config.vm.box = 'Vagarent'
        config.vm.provider 'aws' do |aws, override|
        aws.access_key_id = "xxxxxxxxxxxxxxxxxx"
        aws.secret_access_key = "xxxxxxxxxxxxxxxxxxxxxxxx"
        aws.keypair_name = 'ssh-keypair-name'
        aws.instance_type = "t2.micro"
        aws.region = 'us-west-2a'
        aws.ami = 'ami-1122298f0'
        aws.security_groups = ['default']
        override.ssh.username = 'ubuntu'
        override.ssh.private_key_path = '~/.ssh/ssh-keypair-file'
      end
    end

How to solve it?

Body:
Going through "vagrant-aws" documentation, following worked for me.

Installed "vagrant-aws" plugin with shell:

vagrant plugin install vagrant-aws

Added AWS compatible 'dummy-box' named "aws" added in config.vm.box = "aws":

vagrant box add aws https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box

Created following Vagrant file:

# Require the AWS provider plugin
require 'vagrant-aws'
Vagrant.configure(2) do |config|
  config.vm.box = "aws"
  config.vm.box_url = "https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box"

  config.vm.provider :aws do |aws, override|
     aws.access_key_id = ENV['AWS_ACCESS_KEY']
     aws.secret_access_key = ENV['AWS_SECRET_KEY']
     aws.region = "us-east-1"
     #aws.availability_zone = "us-east-1c"

     # EC2 Instance AMI
     aws.ami =  "ami-aa2ea6d0" # Ubuntu 16.04 in US-EAST
     aws.keypair_name = "awswindows" #change as per your key
     aws.instance_type = "t2.micro"
     aws.block_device_mapping = [{ 'DeviceName' => '/dev/sda1', 'Ebs.VolumeSize' => 10 }]
     aws.security_groups = ["YOUR_SG"]
     aws.tags = {
        'Name' => 'Vagrant EC2 Instance'
        }
    # Credentials to login to EC2 Instance
    override.ssh.username = "ubuntu"
    override.ssh.private_key_path = ENV['AWS_PRIVATE_KEY']
  end

end

Fired vagrant up --provider=aws.

Check once and let me know if you face any issue.


问:
Unexpected non-void return value in void function swift 4 using json serialisation
I am currently trying to clean up my code on a project by writing a generic function that can be used multiple times. However i need my function to return an array. My error is "Unexpected non-void return value in void function"

Here is my code

```<code>func JSONSerialisation(JsonUrl: String) -> NSArray{
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if error != nil
        {
            print("error")

        }
        else
        {
            if let content = data
            {
                do
                {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        return Json //Error occurs here
                    }

                }
                catch
                {

                }

            }

        }

    }
    task.resume()

}
</code>```

There are a few questions like this on Stack Overflow but so far none of them have been able to fix my problem as they all say add -> NSArray.

Thanks in advance

答:
You can't return data directly from an asynchronous task. Use a closure

Create a Function using a closure like.

```<code>func jsonSerialisation(jsonUrl: String, completion block: @escaping ((NSArray) -> ())){
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if let e = error{
            print(e.localizedDescription)
        }
        else{
            if let content = data{
                do {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        block(Json)
                    }
                }
                catch let error{
                    print(error.localizedDescription)
                }
            }
        }
    }
    task.resume()
}
</code>```

And Call :

```<code>jsonSerialisation(jsonUrl: "Your Url") { (json) in
    print(json)
}
</code>```

This is helpful

Body:
I am currently trying to clean up my code on a project by writing a generic function that can be used multiple times. However i need my function to return an array. My error is "Unexpected non-void return value in void function"

Here is my code

func JSONSerialisation(JsonUrl: String) -> NSArray{
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if error != nil
        {
            print("error")

        }
        else
        {
            if let content = data
            {
                do
                {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        return Json //Error occurs here
                    }

                }
                catch
                {

                }

            }

        }

    }
    task.resume()

}

There are a few questions like this on Stack Overflow but so far none of them have been able to fix my problem as they all say add -> NSArray.

Thanks in advance

Body:
You can't return data directly from an asynchronous task. Use a closure

Create a Function using a closure like.

func jsonSerialisation(jsonUrl: String, completion block: @escaping ((NSArray) -> ())){
    let url = URL(string: JsonUrl)
    let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
        if let e = error{
            print(e.localizedDescription)
        }
        else{
            if let content = data{
                do {
                    if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
                        block(Json)
                    }
                }
                catch let error{
                    print(error.localizedDescription)
                }
            }
        }
    }
    task.resume()
}

And Call :

jsonSerialisation(jsonUrl: "Your Url") { (json) in
    print(json)
}

This is helpful


问:
Quotation marks not shown on display
In my string xml file I have a line like this:

```<code><string name="infoHeader">random "text" here</string>
</code>```

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

```<code><string name="infoHeader">random "text" here</string>
</code>```

And then used:

```<code>String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);
</code>```

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

答:
Try this:

```<code>  Value:  \"Hello\"
</code>```

in the resources window, or

```<code><string name="hello">\"Hello\"</string>
</code>```

in the xml file

Title: Quotation marks not shown on display

Body:
In my string xml file I have a line like this:

<string name="infoHeader">random "text" here</string>

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

<string name="infoHeader">random "text" here</string>

And then used:

String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

Body:
Try this:

  Value:  \"Hello\"

in the resources window, or

<string name="hello">\&quot;Hello\&quot;</string>

in the xml file


问:
Is there any way to edit Information_schema in mysql
I know information schema is read only but I ran into a problem.
I've imported mysql database. Information_schema db also got copied. Its 'views' table has a definer set. I wish to change this as this is causing problems to access some tables.

It gives me access denied to root which has all the permissions and I also tried running mysql with --skip-grant-tables option but with no help.

Is there any way I can change the definer?

Note: its Innodb

答:
As mentioned in the manual:

Inside INFORMATION_SCHEMA there are several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.

Hence they are read only and can't be manipulated.


问:
Unit Tests not discovered in Visual Studio 2017
I have been struggling with VS 2017 since I installed it. Now it seems Unit Tests will only run from the command line "dotnet test."

My project is .NET Core 1.1.1. I have the SDK and the framework update for 1.1.1 installed.

I have tried the sample at MSDN (https://msdn.microsoft.com/en-us/library/ms182532.aspx) which also fails exactly the same way.

All NuGet packages for the tests and the main project are current. And both the test project and the main project build without errors. An the tests run successfully from the command line.

Has anyone gotten Unit Tests to run in VS 2017, if so how?

Thanks,
John

Update - Extend

Here is an example of a simple test project that is not working on GitHub. This is an example with xUnit but I have tried NUnit and visual studio built in MS tests. No matter what testing or what changes I make I cannot get the VS test runner to find any tests.

What I've Tried

Deleting VS test cache files DEL %TEMP%\VisualStudioTestExplorerExtensions

Restarting VS

Closing/Opening test explorer

for xUnit installed Microsoft.DotNet.InternalAbstractions (see SO post)

for NUnit ensure adapter installed and same version (3) as NUnit package

test -> test settings -> default processor architecture is set to x86

The Question

Can anyone please provide a working example of a .Net Core 1.1.0 solution in VS2017 (.csproj project files) where the VS test explorer successfully finds the unit tests OR show me the issue in the example given.

答:
In my case, it was a project I had upgraded the test project from an earlier .NET version. in the app.config I had assemblybindings to previous versions of the dependant assemblies.

After fixing the assemblybindings in the app.config, my tests got discovered.


答:
```<code># example dataset (only variable of interest included)
df = data.frame(V9=c("gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)

df %>%
  mutate(id = row_number()) %>%                  # flag row ids (will need those to reshape data later)
  separate_rows(V9, sep="; ") %>%                # split strings and create new rows
  separate(V9, c("name","value"), sep=" ") %>%   # separate column name from value
  mutate(value = gsub(";","",value)) %>%         # remove ; when necessary
  spread(name, value)                            # reshape data

#   id  conf_hi  conf_lo       cov exon_number         FPKM     frac gene_id transcript_id
# 1  1 9.805420 4.347062 25.616962        <NA> 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 2  2 9.805420 4.347062 25.616962           1 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 3  3 9.805420 4.347062 25.616962           2 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 4  4 9.805420 4.347062 25.616962           3 7.0762407256 1.000000  CUFF.1      CUFF.1.1
</code>```

You can join this dataset back to your initial dataset using the row ids (id). You need to create an id in your original dataset as well.

Title: Split a data.frame column into others columns

Body:
I have a big data.frame with some columns, but my 9th column is made of data separated by semicolon :

    gtf$V9
1                 gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
2  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
3  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;
4  gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;

So I would like to cut this column into others columns and merge this later with the other part of the data.frame (the others columns before the 9th column).

I've tried some code without results :

head(gtf$V9, sep = ";",stringsAsFactors = FALSE)

or

new_df <- matrix(gtf$V9, ncol=7, byrow=TRUE) # sep = ";"

The same thing with as.data.frame, data.frame or as.matrix

I have also tried to write.csv and import this with includ a sep=";", but the data.frame is too bigger and my computer is lagging..

Any advice?

Body:
# example dataset (only variable of interest included)
df = data.frame(V9=c("gene_id CUFF.1; transcript_id CUFF.1.1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 1; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 2; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;",
                "gene_id CUFF.1; transcript_id CUFF.1.1; exon_number 3; FPKM 7.0762407256; frac 1.000000; conf_lo 4.347062; conf_hi 9.805420; cov 25.616962;"),
                stringsAsFactors = F)

library(dplyr)
library(tidyr)

df %>%
  mutate(id = row_number()) %>%                  # flag row ids (will need those to reshape data later)
  separate_rows(V9, sep="; ") %>%                # split strings and create new rows
  separate(V9, c("name","value"), sep=" ") %>%   # separate column name from value
  mutate(value = gsub(";","",value)) %>%         # remove ; when necessary
  spread(name, value)                            # reshape data

#   id  conf_hi  conf_lo       cov exon_number         FPKM     frac gene_id transcript_id
# 1  1 9.805420 4.347062 25.616962        <NA> 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 2  2 9.805420 4.347062 25.616962           1 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 3  3 9.805420 4.347062 25.616962           2 7.0762407256 1.000000  CUFF.1      CUFF.1.1
# 4  4 9.805420 4.347062 25.616962           3 7.0762407256 1.000000  CUFF.1      CUFF.1.1

You can join this dataset back to your initial dataset using the row ids (id). You need to create an id in your original dataset as well.


问:
How to check whether optional function parameter is set
Is there an easy way in Python to check whether the value of an optional parameter comes from its default value, or because the user has set it explicitly at the function call?</p>

答:
I've seen this pattern a few times (e.g. library unittest, py-flags, jinja):

```<code>class Default:
    def __repr__( self ):
        return "DEFAULT"

DEFAULT = Default()
</code>```

...or the equivalent one-liner...:

```<code>DEFAULT = type( 'Default', (), { '__repr__': lambda x: 'DEFAULT' } )()
</code>```

Unlike DEFAULT = object(), this assists type-checking and provides information when errors occur -- frequently either the string representation ("DEFAULT") or the class name ("Default") are used in error messages.

Body:
I've seen this pattern a few times (e.g. library unittest, py-flags, jinja):

class Default:
    def __repr__( self ):
        return "DEFAULT"

DEFAULT = Default()

...or the equivalent one-liner...:

DEFAULT = type( 'Default', (), { '__repr__': lambda x: 'DEFAULT' } )()

Unlike DEFAULT = object(), this assists type-checking and provides information when errors occur -- frequently either the string representation ("DEFAULT") or the class name ("Default") are used in error messages.