问:
Rails - good way to convert string to array if not array rails
I receive a param and want it to be either a string like this :

```<code>"abc,efg"
</code>```

or an Array like this

```<code>["abc","efg"]
</code>```

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

```<code>if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")
</code>```

答:
Apologies for piling on. But I thought I would offer a slight tweak to the answer proposed by SickLickWill (which doesn't quite handle the Array case correctly):

```<code>ids = params[:id].split(',').flatten
</code>```

This will handle the String case just fine:

```<code>:001 > params = {id: "abc,efg"}
:002 > ids = params[:id].split(',').flatten
 => ["abc", "efg"]
</code>```

As well as the Array case:

```<code>:003 > params = {id: ["abc","efg"]}
:004 > ids = params[:id].split(',').flatten
 => ["abc", "efg"]
</code>```

If there's any chance the id param will be nil, then this barfs:

```<code>:005 > params = {}
 => {}
:006 > ids = params[:id].split(',').flatten
NoMethodError: undefined method `split' for nil:NilClass
</code>```

So, you could put in a conditional test:

```<code>:007 > ids = params[:id].split(',').flatten if params[:id]
 => nil
</code>```

Or, use try:

```<code>:008 > ids = params[:id].try(:split, ',').try(:flatten)
 => nil
</code>```

Body:
I receive a param and want it to be either a string like this :

"abc,efg"

or an Array like this

["abc","efg"]

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")

Body:
Apologies for piling on. But I thought I would offer a slight tweak to the answer proposed by SickLickWill (which doesn't quite handle the Array case correctly):

ids = params[:id].split(',').flatten

This will handle the String case just fine:

:001 > params = {id: "abc,efg"}
:002 > ids = params[:id].split(',').flatten
 => ["abc", "efg"]

As well as the Array case:

:003 > params = {id: ["abc","efg"]}
:004 > ids = params[:id].split(',').flatten
 => ["abc", "efg"]

If there's any chance the id param will be nil, then this barfs:

:005 > params = {}
 => {}
:006 > ids = params[:id].split(',').flatten
NoMethodError: undefined method `split' for nil:NilClass

So, you could put in a conditional test:

:007 > ids = params[:id].split(',').flatten if params[:id]
 => nil

Or, use try:

:008 > ids = params[:id].try(:split, ',').try(:flatten)
 => nil


来源: stackexchange

问:
Asp.net C# How to redirect to another page if the current page has query string
I am stucked here. I have  page and opened it via request.query string. Hence called products.aspx?Id=483.

So my question is how am I going to redirect from this page to a page that still requires variable to be passed in, in this case the page details.aspx?Id=56

It fails to do so. How am I going to do this guys. Any help I will appreciate.

答:
Answer to pass the value you need to code it like this: + IdOrHiddenField1.value);

```<code>// Your new value is passed here to the next page after the plus sign
Response.Redirect("newPage.aspx?id=" + IdOrHiddenField1.value);
</code>```

There are two ways you can do this,

Response.Redirect: The Redirect method of the Response object
provides a way to implement client-side redirection. Response.Redirect("http://www.yourwebpage.com");

Server.Transfer: The Transfer method of the Server object performs
redirection using the server and avoiding HTTP requests. Server.Transfer("/myPageWithString.aspx");

```<code>Response.BufferOutput = true;
string id = HttpContext.Current.Request.QueryString["id"];
//check for empty string
if (!string.IsNullOrEmpty(id)) {
    Response.Redirect("/myPageWithString.aspx?id=" + IdOrHiddenField1.value);
}
else if (Parse.Int.... == "some blah...")
{
    Response.Redirect("/myPageWithString.aspx?id=" + IdOrHiddenField1.value);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Answer to pass the value you need to code it like this: + IdOrHiddenField1.value);

// Your new value is passed here to the next page after the plus sign
Response.Redirect("newPage.aspx?id=" + IdOrHiddenField1.value);

There are two ways you can do this,

Response.Redirect: The Redirect method of the Response object
provides a way to implement client-side redirection. Response.Redirect("http://www.yourwebpage.com");

Server.Transfer: The Transfer method of the Server object performs
redirection using the server and avoiding HTTP requests. Server.Transfer("/myPageWithString.aspx");

Response.BufferOutput = true;
string id = HttpContext.Current.Request.QueryString["id"];
//check for empty string
if (!string.IsNullOrEmpty(id)) {
    Response.Redirect("/myPageWithString.aspx?id=" + IdOrHiddenField1.value);
}
else if (Parse.Int.... == "some blah...")
{
    Response.Redirect("/myPageWithString.aspx?id=" + IdOrHiddenField1.value);
}


问:
Dynamically populate variable number of sprites on grid layout group
As the title suggests, I'm trying to populate a UI panel with a GridLayoutGroup component at runtime with sprites from the resources folder. The problem is that the sprites do not auto-align to the grid cells, instead getting drawn on the center of the panel.

I've tried the approach mentioned here but it does not work for me. Here is the script I've attached to the gui with the GridLayoutGroup:

public class SpriteList : MonoBehaviour
{
    public GameObject gridPanel;
    public const string sortingLayer = "Foreground";

    // Use this for initialization
    void Start()
    {
        Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
        RectTransform gridRT = gridPanel.GetComponent<RectTransform>();

        for (int i = 0; i < spriteArray.Length; i++)
        {
            GameObject cellObject = new GameObject();
            cellObject.AddComponent<SpriteRenderer>();
            cellObject.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
            cellObject.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;

            GameObject sprite = (GameObject) Instantiate(cellObject);
            sprite.transform.SetParent(gridPanel.transform, false);
            LayoutRebuilder.ForceRebuildLayoutImmediate(
                    gridPanel.GetComponent<RectTransform>());
            sprite.transform.localScale = new Vector3(30, 30, 1);
    }
}
```

<p>Changing the settings of the <code>GridLayoutGroup</code> do not modify the behaviour I'm seeing at all.</p>

<p>Since everything I see online seems to indicate that the key is the line </p>

<pre class="lang-c# prettyprint-override"><code>sprite.transform.SetParent(gridPanel.transform, false);
</code>```

which I use, what am I missing?

Much gratitude!

答:
Your objects should have a 'Layout Element' component attached.

After setting the parent of the objects call LayoutRebuilder.ForceRebuildLayoutImmediate() on the parent.

Body:
As the title suggests, I'm trying to populate a UI panel with a GridLayoutGroup component at runtime with sprites from the resources folder. The problem is that the sprites do not auto-align to the grid cells, instead getting drawn on the center of the panel.

I've tried the approach mentioned here but it does not work for me. Here is the script I've attached to the gui with the GridLayoutGroup:

public class SpriteList : MonoBehaviour
{
    public GameObject gridPanel;
    public const string sortingLayer = "Foreground";

    // Use this for initialization
    void Start()
    {
        Sprite[] spriteArray = Resources.LoadAll<Sprite>("Sprites");
        RectTransform gridRT = gridPanel.GetComponent<RectTransform>();

        for (int i = 0; i < spriteArray.Length; i++)
        {
            GameObject cellObject = new GameObject();
            cellObject.AddComponent<SpriteRenderer>();
            cellObject.GetComponent<SpriteRenderer>().sprite = spriteArray[i];
            cellObject.GetComponent<SpriteRenderer>().sortingLayerName = sortingLayer;

            GameObject sprite = (GameObject) Instantiate(cellObject);
            sprite.transform.SetParent(gridPanel.transform, false);
            LayoutRebuilder.ForceRebuildLayoutImmediate(
                    gridPanel.GetComponent<RectTransform>());
            sprite.transform.localScale = new Vector3(30, 30, 1);
    }
}

Changing the settings of the GridLayoutGroup do not modify the behaviour I'm seeing at all.

Since everything I see online seems to indicate that the key is the line

sprite.transform.SetParent(gridPanel.transform, false);

which I use, what am I missing?

Much gratitude!


问:
Excluding lines conditional upon multiple fields with awk
I have a pretty simple awk question:

I have the following file test1.txt

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5
</code>```

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5
</code>```

I'm looking for an awk code that would do something like:

```<code>awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt
</code>```

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

答:
another awk one-liner

```<code>$ awk '$2!="op2" || 2>$3 || $3>4' file

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5
</code>```

Body:
I have a pretty simple awk question:

I have the following file test1.txt

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5

I'm looking for an awk code that would do something like:

awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

Body:
another awk one-liner

$ awk '$2!="op2" || 2>$3 || $3>4' file

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5


问:
Parse nested Json array in Android using Volley
this is my JSON - https://api.edamam.com/search?q=chicken.

I am trying to get only the 'label' which is the food name and 'image' which is food photo.

This is my code below.

```<code>JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>()

    {

        @Override
        public void onResponse( JSONObject response) {

            try {;

               JSONArray jsonArray = response.getJSONArray("hits");

                for (int i = 0; i < jsonArray.length(); i++)
                {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String recipe = jsonObject.optString("recipe");
                    String name = jsonObject.optString("label");
                    String label = jsonObject.optString("image");

                    txtDisplay.setText(recipe + name + label);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", "Error");
        }
    });

    queue.add(obreq);
}
</code>```

}

This code returns me the JSON data, but it returns all the data.

Can anyone please provide sample code so that it returns specific values only.

Thanks

答:
Here is a small function that extracts only what is needed i.e label and image into List<FoodModel> object which can be used in list view or recyclerview to display items.

```<code> private List<FoodModel> getFoodList(String json) throws JSONException {
    List<FoodModel> foodModels = new ArrayList<>();
    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("hits");
    for (int count = 0; count < jsonArray.length(); count++) {
        JSONObject innerObject = jsonArray.getJSONObject(count);
        JSONObject recipe = innerObject.getJSONObject("recipe");
        FoodModel foodModel = new FoodModel();
        foodModel.setImage(recipe.getString("label"));
        foodModel.setLabel(recipe.getString("label"));
        foodModels.add(foodModel);
    }
    return foodModels;
}
</code>```

FoodModel goes here

```<code> public class FoodModel {

    private String label;
    private String image;

    public String getLabel() {
        return label;
    }

    public void setLabel(final String label) {
        this.label = label;
    }

    public String getImage() {
        return image;
    }

    public void setImage(final String image) {
        this.image = image;
    }
}
</code>```

Body:
this is my JSON - https://api.edamam.com/search?q=chicken.

I am trying to get only the 'label' which is the food name and 'image' which is food photo.

This is my code below.

JsonObjectRequest(Request.Method.GET,url,null,new Response.Listener<JSONObject>()

    {

        @Override
        public void onResponse( JSONObject response) {

            try {;

               JSONArray jsonArray = response.getJSONArray("hits");

                for (int i = 0; i < jsonArray.length(); i++)
                {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String recipe = jsonObject.optString("recipe");
                    String name = jsonObject.optString("label");
                    String label = jsonObject.optString("image");

                    txtDisplay.setText(recipe + name + label);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", "Error");
        }
    });

    queue.add(obreq);
}

}

This code returns me the JSON data, but it returns all the data.

Can anyone please provide sample code so that it returns specific values only.

Thanks

Body:
Here is a small function that extracts only what is needed i.e label and image into List<FoodModel> object which can be used in list view or recyclerview to display items.

 private List<FoodModel> getFoodList(String json) throws JSONException {
    List<FoodModel> foodModels = new ArrayList<>();
    JSONObject jsonObject = new JSONObject(json);
    JSONArray jsonArray = jsonObject.getJSONArray("hits");
    for (int count = 0; count < jsonArray.length(); count++) {
        JSONObject innerObject = jsonArray.getJSONObject(count);
        JSONObject recipe = innerObject.getJSONObject("recipe");
        FoodModel foodModel = new FoodModel();
        foodModel.setImage(recipe.getString("label"));
        foodModel.setLabel(recipe.getString("label"));
        foodModels.add(foodModel);
    }
    return foodModels;
}

FoodModel goes here

 public class FoodModel {

    private String label;
    private String image;

    public String getLabel() {
        return label;
    }

    public void setLabel(final String label) {
        this.label = label;
    }

    public String getImage() {
        return image;
    }

    public void setImage(final String image) {
        this.image = image;
    }
}


问:
Tokenizer efficiency question
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

```<code>bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}
</code>```

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

```<code> getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..
</code>```

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers

答:
Traditionally, compiler construction classes teach you to read tokens, one by one, as you parse. The reason for that, is that back in the days, memory resources were scarce. You had kilobytes to your disposal, and not gigabytes as you do today.

Having said that, I don't mean to recommend you to read all tokens in advance, and then parse from your list of tokens. Input is of arbitrary size. If you hog too much memory, the system will become slow. Since it looks like you only need one token in the lookahead, I'd read one at a time from the input stream. The operating system will buffer and cache the input stream for you, so it'll be fast enough for most purposes.

ContentLicense: CC BY-SA 2.5

Title: Tokenizer efficiency question

Body:
I'm writing a compiler front end for a project and I'm trying to understand what's the best method of tokenize the source code.
I can't choose between two ways:

1) the tokenizer read all tokens:

bool Parser::ReadAllTokens()
{
  Token token;
  while( m_Lexer->ReadToken( &token ) )
  {
    m_Tokens->push_back( token );
    token.Reset(); // reset the token values..
  }

  return !m_Tokens->empty();
}

and then the parsing phase begins, operating on the m_Tokens list. In this way the methods getNextToken(), peekNextToken() and ungetToken() are relatively easy to implement by iterator, and the parsing code is well written and clear ( not broken by getNextToken() i.e. :

 getNextToken();
 useToken();
 getNextToken();
 peekNextToken();
 if( peeked is something )
  ungetToken();
 ..
 ..

)

2) the parsing phase begins and when needed, the token is created and used ( the code seems not so clear )

What's the best method??and why??and the efficiency??
thanks in advance for the answers


问:
Error when trying to create site collection using CSOM PowerShell
I am trying to run a PowerShell script that would generate the site colletion on the SharePoint tenant. However, whenever I am trying to execute the site collection creation, I get an error:

Exception calling "ExecuteQuery" with "0" argument(s): "Unknown Error"
  At C:\projects\SP\Scripts\Taxonomy\Add-NavigationTerms1.ps1:120 char:5
  +     $TenantContext.ExecuteQuery()
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ServerException

How would I go around this error? How can I fix it? Thank you very much for all your help!

Here is the code:

```<code>param (
    [Parameter(Mandatory = $false)]
    [string]    $sourceWeb = '',
    [string]    $destinationWeb = '',
    [Parameter(Mandatory = $false)]
    [string]    $sourceListName = 'CurrentSites', #$sourceListName = 'O365 Sites',
    [Parameter(Mandatory = $false)]
    [string]    $sharepointAdmin = ''
)

<#
Add-Type -Path "C:/Program Files/SharePoint Client Components/Assemblies/Microsoft.Online.SharePoint.Client.Tenant.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.UserProfiles.dll"
#>

$path = 'C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/15/ISAPI/'
$simpleLinkUrlPropertyName = '_Sys_Nav_SimpleLinkUrl'
$assemblies = 'Microsoft.SharePoint.Client.dll',
'Microsoft.SharePoint.Client.Runtime.dll',
'Microsoft.SharePoint.Client.Taxonomy.dll'

$assemblies | % { Add-Type -Path (Join-Path $path $_) }

Add-Type -Path "C:/Program Files/SharePoint Client Components/Assemblies/Microsoft.Online.SharePoint.Client.Tenant.dll"

#$context = New-Object Microsoft.SharePoint.Client.ClientContext($sourceWeb)
#$password = Read-Host -Prompt 'Please enter your password' -AsSecureString
#$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sharepointAdmin,$password)

$password = ''

#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

Function Get-SPOContext([string]$Url, [string]$UserName, [string]$Password) {
        $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
        $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
        $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
        return $context
}

Function Get-ListItems([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {

        $list = $Context.Web.Lists.GetByTitle($listTitle)
        $Context.Load($list)
        $Context.ExecuteQuery()

        $qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
        $items = $list.GetItems($qry)
        $Context.Load($items)
        $Context.ExecuteQuery()
        return $items
}

Function Create-Site-Collection([String]$url, [String]$title) {
        $TenantURL = ''
        $Title = 'New Published Collection List';

        [string]
        $TenantUserName = '';

        [Security.SecureString]
        #$TenantPassword = ConvertTo-SecureString 'Anew6731' -AsPlainText -Force
        $TenantPassword = convertto-securestring "Anew6731" -asplaintext -force

        #Open the Tenant Administration Context with the Tenant Admin Url
        $TenantContext = Get-SPOContext -Url $TenantUrl -UserName $TenantUserName -Password "Anew6731"

        #$TenantContext = New-Object Microsoft.SharePoint.Client.ClientContext($TenantUrl)
        #$TenantCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($TenantUserName, $TenantPassword)
        #$TenantContext.Credentials = $TenantCredentials

        #Get the tenant object
        $Tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($TenantContext)

        #Set the Site Creation Properties values
        $TenantProperties = New-Object Microsoft.Online.SharePoint.TenantAdministration.SiteCreationProperties
        #$TenantProperties.Url = $url
        $TenantProperties.Template = "CMSPUBLISHING#0 "
        $TenantProperties.Owner = $TenantUserName
        $TenantProperties.StorageMaximumLevel = 1000
        $TenantProperties.UserCodeMaximumLevel = 300
        $TenantProperties.Title = $title

        $TenantContext.Load($Tenant)
        $TenantContext.ExecuteQuery()

        #$TenantContext.Load($TenantProperties)
        #$TenantContext.ExecuteQuery()

        #Create the site using the properties

        $Tenant.CreateSite($TenantProperties) | Out-Null

        Write-Host "Creating site collection "
        #Create the site in the tennancy
        #$TenantContext.Load($Tenant)
        #$TenantContext.Load($spOnlineOperation)
        $TenantContext.ExecuteQuery()
        #$TenantContext.Dispose()
}

$UserName = $sharepointAdmin
#$Password = Read-Host -Prompt "Enter the password"
$Url = $sourceWeb

$context = Get-SPOContext -Url $Url -UserName $UserName -Password $Password $items = Get-ListItems -Context $context -ListTitle "O365 Sites"

foreach ($item in $items) {
        $Context.Load($item)
        $Context.ExecuteQuery()
        Write-Host $item["NEWURL"]
        Write-Host $item["Title"]
        #Write-Host $item.FieldValues
        Create-Site-Collection -URL $item["NEWURL"] -Title $item["Title"]
        #Write-Hsost $item.DisplayName

}

$context.Dispose()
</code>```

答:
I am honestly not sure what went wrong but this code/method worked just fine</p>

```<code>Function Create-Site-Collection([String]$fullUrl, [Microsoft.SharePoint.Client.ClientContext] $TenantContext)
{
    Write-Host "Now configuring the new Site Collection"

    #Get the tenant object
    $tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($TenantContext)

    #Set the Site Creation Properties values
    $properties = New-Object Microsoft.Online.SharePoint.TenantAdministration.SiteCreationProperties
    $properties.Url = $fullUrl
    $properties.Template =  "BLANKINTERNETCONTAINER#0"
    $properties.Owner = $AdminSiteUsername
    $properties.StorageMaximumLevel = 1000
    #$properties.UserCodeMaximumLevel = 100
    $properties.TimeZoneId = 10 # (UTC-05:00) Eastern Time (US and Canada)

    #Create the site using the properties
    $tenant.CreateSite($properties) | Out-Null

    $TenantContext.ExecuteQuery()

    Write-Host "Creating site collection"
    #Create the site in the tennancy
    try
    {
    $TenantContext.ExecuteQuery()
    Write-Host "Site Creation request completed. Note that the creation process is asynchronous and provisioning may take a short while."
    }
    Catch [Exception]
    {
        Write-host $_.Exception.Message -f Red
    }
}
</code>```

Body:
I am trying to run a PowerShell script that would generate the site colletion on the SharePoint tenant. However, whenever I am trying to execute the site collection creation, I get an error:

Exception calling "ExecuteQuery" with "0" argument(s): "Unknown Error"
  At C:\projects\SP\Scripts\Taxonomy\Add-NavigationTerms1.ps1:120 char:5
  +     $TenantContext.ExecuteQuery()
  +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : ServerException

How would I go around this error? How can I fix it? Thank you very much for all your help!

Here is the code:

param (
    [Parameter(Mandatory = $false)]
    [string]    $sourceWeb = '',
    [string]    $destinationWeb = '',
    [Parameter(Mandatory = $false)]
    [string]    $sourceListName = 'CurrentSites', #$sourceListName = 'O365 Sites',
    [Parameter(Mandatory = $false)]
    [string]    $sharepointAdmin = ''
)

<#
Add-Type -Path "C:/Program Files/SharePoint Client Components/Assemblies/Microsoft.Online.SharePoint.Client.Tenant.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:/Program Files/Common Files/microsoft shared/Web Server Extensions/16/ISAPI/Microsoft.SharePoint.Client.UserProfiles.dll"
#>

$path = 'C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/15/ISAPI/'
$simpleLinkUrlPropertyName = '_Sys_Nav_SimpleLinkUrl'
$assemblies = 'Microsoft.SharePoint.Client.dll',
'Microsoft.SharePoint.Client.Runtime.dll',
'Microsoft.SharePoint.Client.Taxonomy.dll'

$assemblies | % { Add-Type -Path (Join-Path $path $_) }

Add-Type -Path "C:/Program Files/SharePoint Client Components/Assemblies/Microsoft.Online.SharePoint.Client.Tenant.dll"

#$context = New-Object Microsoft.SharePoint.Client.ClientContext($sourceWeb)
#$password = Read-Host -Prompt 'Please enter your password' -AsSecureString
#$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sharepointAdmin,$password)

$password = ''

#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
#[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")

Function Get-SPOContext([string]$Url, [string]$UserName, [string]$Password) {
        $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
        $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
        $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
        return $context
}

Function Get-ListItems([Microsoft.SharePoint.Client.ClientContext]$Context, [String]$ListTitle) {

        $list = $Context.Web.Lists.GetByTitle($listTitle)
        $Context.Load($list)
        $Context.ExecuteQuery()

        $qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
        $items = $list.GetItems($qry)
        $Context.Load($items)
        $Context.ExecuteQuery()
        return $items
}

Function Create-Site-Collection([String]$url, [String]$title) {
        $TenantURL = ''
        $Title = 'New Published Collection List';

        [string]
        $TenantUserName = '';

        [Security.SecureString]
        #$TenantPassword = ConvertTo-SecureString 'Anew6731' -AsPlainText -Force
        $TenantPassword = convertto-securestring "Anew6731" -asplaintext -force

        #Open the Tenant Administration Context with the Tenant Admin Url
        $TenantContext = Get-SPOContext -Url $TenantUrl -UserName $TenantUserName -Password "Anew6731"

        #$TenantContext = New-Object Microsoft.SharePoint.Client.ClientContext($TenantUrl)
        #$TenantCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($TenantUserName, $TenantPassword)
        #$TenantContext.Credentials = $TenantCredentials

        #Get the tenant object
        $Tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($TenantContext)

        #Set the Site Creation Properties values
        $TenantProperties = New-Object Microsoft.Online.SharePoint.TenantAdministration.SiteCreationProperties
        #$TenantProperties.Url = $url
        $TenantProperties.Template = "CMSPUBLISHING#0 "
        $TenantProperties.Owner = $TenantUserName
        $TenantProperties.StorageMaximumLevel = 1000
        $TenantProperties.UserCodeMaximumLevel = 300
        $TenantProperties.Title = $title

        $TenantContext.Load($Tenant)
        $TenantContext.ExecuteQuery()

        #$TenantContext.Load($TenantProperties)
        #$TenantContext.ExecuteQuery()

        #Create the site using the properties

        $Tenant.CreateSite($TenantProperties) | Out-Null

        Write-Host "Creating site collection "
        #Create the site in the tennancy
        #$TenantContext.Load($Tenant)
        #$TenantContext.Load($spOnlineOperation)
        $TenantContext.ExecuteQuery()
        #$TenantContext.Dispose()
}

$UserName = $sharepointAdmin
#$Password = Read-Host -Prompt "Enter the password"
$Url = $sourceWeb

$context = Get-SPOContext -Url $Url -UserName $UserName -Password $Password $items = Get-ListItems -Context $context -ListTitle "O365 Sites"

foreach ($item in $items) {
        $Context.Load($item)
        $Context.ExecuteQuery()
        Write-Host $item["NEWURL"]
        Write-Host $item["Title"]
        #Write-Host $item.FieldValues
        Create-Site-Collection -URL $item["NEWURL"] -Title $item["Title"]
        #Write-Hsost $item.DisplayName

}

$context.Dispose()

Body:
I am honestly not sure what went wrong but this code/method worked just fine

Function Create-Site-Collection([String]$fullUrl, [Microsoft.SharePoint.Client.ClientContext] $TenantContext)
{
    Write-Host "Now configuring the new Site Collection"

    #Get the tenant object
    $tenant = New-Object Microsoft.Online.SharePoint.TenantAdministration.Tenant($TenantContext)

    #Set the Site Creation Properties values
    $properties = New-Object Microsoft.Online.SharePoint.TenantAdministration.SiteCreationProperties
    $properties.Url = $fullUrl
    $properties.Template =  "BLANKINTERNETCONTAINER#0"
    $properties.Owner = $AdminSiteUsername
    $properties.StorageMaximumLevel = 1000
    #$properties.UserCodeMaximumLevel = 100
    $properties.TimeZoneId = 10 # (UTC-05:00) Eastern Time (US and Canada)

    #Create the site using the properties
    $tenant.CreateSite($properties) | Out-Null

    $TenantContext.ExecuteQuery()

    Write-Host "Creating site collection"
    #Create the site in the tennancy
    try
    {
    $TenantContext.ExecuteQuery()
    Write-Host "Site Creation request completed. Note that the creation process is asynchronous and provisioning may take a short while."
    }
    Catch [Exception]
    {
        Write-host $_.Exception.Message -f Red
    }
}


问:
Windows API functions
Are they standard code c or c++ code? what are they?</p>

答:
They're standard C code, if you're programming against pure Windows API.

A C++ based wrapper called MFC is available.

All of this is being pushed out in favor of .NET framework.

Title: Windows API functions


问:
"PWC6345: There is an error in invoking javac." error when using Jetty WTP plugin to deploy a JSP page on Jetty
I'm trying to deploy a JSP-page on Jetty, using the Jetty WTP plugin for Eclipse. But I get the error below. It looks like Jetty can't find javac. Is there any settings I have to do for the Jetty WTP plugin in Eclipse or how do I fix this?

The JSP page works fine if I export my project as a .war-file to jetty\webapps and then start Jetty manually using java -jar start.jar. But it doesn't work if I deploy using the Jetty WTP plugin for Eclipse as described.

I have my JAVA_HOME set to C:\Program Files (x86)\Java\jdk1.7.0_01 and I use Jetty 8.0.4 on Windows 7.

Servlets is working fine with the current setup. Any suggestions on how to solve this for JSP pages?

```<code>HTTP ERROR 500
Problem accessing /MyJavaWeb/formProcess. Reason:

    PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required

Caused by:
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
    at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
    at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:520)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:271)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:98)
    at com.example.FormProcessServlet.doPost(FormProcessServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:483)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:346)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:442)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:941)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:801)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:224)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
    at java.lang.Thread.run(Unknown Source)
</code>```

答:
I added this line to 'eclipse.ini' file which is present inside eclipse folder.

-vm
C:\Program Files\Java\jdk1.8.0_131\bin\javaw.exe

and I also change the JRE path in eclipse

windows -> preferences -> java -> Installed JREs

and provided path upto jdk

C:\Program Files\Java\jdk1.8.0_131

Body:
I'm trying to deploy a JSP-page on Jetty, using the Jetty WTP plugin for Eclipse. But I get the error below. It looks like Jetty can't find javac. Is there any settings I have to do for the Jetty WTP plugin in Eclipse or how do I fix this?

The JSP page works fine if I export my project as a .war-file to jetty\webapps and then start Jetty manually using java -jar start.jar. But it doesn't work if I deploy using the Jetty WTP plugin for Eclipse as described.

I have my JAVA_HOME set to C:\Program Files (x86)\Java\jdk1.7.0_01 and I use Jetty 8.0.4 on Windows 7.

Servlets is working fine with the current setup. Any suggestions on how to solve this for JSP pages?

HTTP ERROR 500
Problem accessing /MyJavaWeb/formProcess. Reason:

    PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required

Caused by:
org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
    at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
    at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:520)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:271)
    at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:98)
    at com.example.FormProcessServlet.doPost(FormProcessServlet.java:39)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:558)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:488)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:483)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:973)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:417)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:907)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:110)
    at org.eclipse.jetty.server.Server.handle(Server.java:346)
    at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:442)
    at org.eclipse.jetty.server.HttpConnection$RequestHandler.content(HttpConnection.java:941)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:801)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:224)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:51)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:586)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:44)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:598)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:533)
    at java.lang.Thread.run(Unknown Source)


问:
CSS selector for parent with blank element
I'm trying to make a selector for all
 elements containing a blank
 element:

li>p:blank {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
  <p>Size</p>
  <p></p> <!-- blank -->
</li>

<li>
  <p>Color</p>
  <p>Blue</p> <!-- NOT blank -->
</li></code>```

Is this possible?

答:
Yes!  However- the pseudo class is :empty not :blank:

li>p:empty {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
  <p>Size</p>
  <p></p> <!-- blank -->
</li>

<li>
  <p>Color</p>
  <p>Blue</p> <!-- NOT blank -->
</li></code>```

Body:
I'm trying to make a selector for all
 elements containing a blank
 element:

li>p:blank {
  display: none;
}

Size

Color

Blue

Is this possible?

Body:
Yes!  However- the pseudo class is :empty not :blank:

li>p:empty {
  display: none;
}

<li>
  <p>Size</p>
  <p></p> <!-- blank -->
</li>

<li>
  <p>Color</p>
  <p>Blue</p> <!-- NOT blank -->
</li>


问:
pandoc filter in lua and walk_block
I'm trying to apply a LUA filter that would only alter the body of a document, leaving the Metadata untouched. And it's harder than I thought.

The filter should prepend and append text to inline elements as well as block elements. If it works for the inline element, here Code, it fails for the block element CodeBlock.

```<code>function Pandoc(doc)
  blocks = {}
  for k,block in pairs(doc.blocks) do
    table.insert(blocks, pandoc.walk_block(block, {
      -- Doesn't work!?
      CodeBlock = function(el)
        return {
          pandoc.Para({pandoc.Str("Before")}),
          el,
          pandoc.Para({pandoc.Str("After")})}
      end,
      -- Works!
      Code = function(el)
        return {pandoc.Str("Before"), el, pandoc.Str("After")}
      end,
    }))
  end

  return pandoc.Pandoc(blocks, doc.meta)
end
</code>```

What am I missing? Cheers,

答:
The issue here is that walk_block and walk_inline process the content of an element, not the element itself.

If wrapper is your filter table, this should do what you want:

```<code>function Pandoc (doc)
  local div = pandoc.Div(doc.blocks)
  local blocks = pandoc.walk_block(div, wrapper).content
  return pandoc.Pandoc(blocks, doc.meta)
end
</code>```

An alternative solution would be to save and restore the metadata, like so:

```<code>local meta = {}
return {
  { Meta = function(m) meta = m; return {} end },
  wrapper,
  { Meta = function(_) return meta; end },
}
</code>```

This is probably more efficient, as serializing/deserializing only metadata and Code/CodeBlock elements is likely faster than doing the same for the full document.

Title: pandoc filter in lua and walk_block

Body:
I'm trying to apply a LUA filter that would only alter the body of a document, leaving the Metadata untouched. And it's harder than I thought.

The filter should prepend and append text to inline elements as well as block elements. If it works for the inline element, here Code, it fails for the block element CodeBlock.

function Pandoc(doc)
  blocks = {}
  for k,block in pairs(doc.blocks) do
    table.insert(blocks, pandoc.walk_block(block, {
      -- Doesn't work!?
      CodeBlock = function(el)
        return {
          pandoc.Para({pandoc.Str("Before")}),
          el,
          pandoc.Para({pandoc.Str("After")})}
      end,
      -- Works!
      Code = function(el)
        return {pandoc.Str("Before"), el, pandoc.Str("After")}
      end,
    }))
  end

  return pandoc.Pandoc(blocks, doc.meta)
end

What am I missing? Cheers,

Body:
The issue here is that walk_block and walk_inline process the content of an element, not the element itself.

If wrapper is your filter table, this should do what you want:

function Pandoc (doc)
  local div = pandoc.Div(doc.blocks)
  local blocks = pandoc.walk_block(div, wrapper).content
  return pandoc.Pandoc(blocks, doc.meta)
end

An alternative solution would be to save and restore the metadata, like so:

local meta = {}
return {
  { Meta = function(m) meta = m; return {} end },
  wrapper,
  { Meta = function(_) return meta; end },
}

This is probably more efficient, as serializing/deserializing only metadata and Code/CodeBlock elements is likely faster than doing the same for the full document.


问:
Function returns only the first element during iteration
this is what I have so far:

```<code>def sort_contacts(sort_contacts):
    contacts = sorted(sort_contacts.items())

    for (k, v) in contacts:
        return list([(k,)+ v])

from test import testEqual

testEqual(sort_contacts({"Summitt, Pat":("1-865-355-4320","pat@greatcoaches.com"),
"Rudolph, Wilma": ("1-410-5313-584", "wilma@olympians.com")}),
[('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com'),
('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')])
testEqual(sort_contacts({"Dinesen, Isak": ("1-718-939-2548", "isak@storytellers.com")}),
[('Dinesen, Isak', '1-718-939-2548', 'isak@storytellers.com')])

###############
</code>```

here is the result

```<code>Test Failed: expected [('Rudolph, Wilma', '1-410-5313-584','wilma@olympians.com'), ('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')] but got [('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com')]
    Pass
</code>```

How can I fix it so that it grabs more than one key and value in the library of contacts

答:
The issue here is the way you return your data. Consider a simple example:

```<code>In [263]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         return [(k, ) + v]
     ...:

In [264]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[264]: [('a', 'b', 'c')]
</code>```

What's happening is that the return statement returns the first item back to the caller. Once the function returns, it does not resume execution and return any more items as you might expect. Because of this, you only see one item returned.

There are two possibilities as a solution. You could either return everything in a list, or use the yield syntax.

Option 1

return <list>

```<code>In [271]: def foo(data):
     ...:     return[(k,) + v for  k, v in sorted(data.items())]
     ...:

In [272]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[272]: [('a', 'b', 'c'), ('d', 'e', 'f')]
</code>```

Option 2

yield

```<code>In [269]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         yield (k, ) + v
     ...:

In [270]: list(foo({'a' : ('b', 'c'), 'd' : ('e', 'f')}))
Out[270]: [('a', 'b', 'c'), ('d', 'e', 'f')]
</code>```

Note that list(...) is needed around the function call because yield results in a generator being returned, which you must iterate over to get your final list result.

Body:
this is what I have so far:

def sort_contacts(sort_contacts):
    contacts = sorted(sort_contacts.items())

    for (k, v) in contacts:
        return list([(k,)+ v])

from test import testEqual

testEqual(sort_contacts({"Summitt, Pat":("1-865-355-4320","pat@greatcoaches.com"),
"Rudolph, Wilma": ("1-410-5313-584", "wilma@olympians.com")}),
[('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com'),
('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')])
testEqual(sort_contacts({"Dinesen, Isak": ("1-718-939-2548", "isak@storytellers.com")}),
[('Dinesen, Isak', '1-718-939-2548', 'isak@storytellers.com')])

###############

here is the result

Test Failed: expected [('Rudolph, Wilma', '1-410-5313-584','wilma@olympians.com'), ('Summitt, Pat', '1-865-355-4320', 'pat@greatcoaches.com')] but got [('Rudolph, Wilma', '1-410-5313-584', 'wilma@olympians.com')]
    Pass

How can I fix it so that it grabs more than one key and value in the library of contacts

Body:
The issue here is the way you return your data. Consider a simple example:

In [263]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         return [(k, ) + v]
     ...:

In [264]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[264]: [('a', 'b', 'c')]

What's happening is that the return statement returns the first item back to the caller. Once the function returns, it does not resume execution and return any more items as you might expect. Because of this, you only see one item returned.

There are two possibilities as a solution. You could either return everything in a list, or use the yield syntax.

Option 1

return <list>

In [271]: def foo(data):
     ...:     return[(k,) + v for  k, v in sorted(data.items())]
     ...:

In [272]: foo({'a' : ('b', 'c'), 'd' : ('e', 'f')})
Out[272]: [('a', 'b', 'c'), ('d', 'e', 'f')]

Option 2

yield

In [269]: def foo(data):
     ...:     for k, v in sorted(data.items()):
     ...:         yield (k, ) + v
     ...:

In [270]: list(foo({'a' : ('b', 'c'), 'd' : ('e', 'f')}))
Out[270]: [('a', 'b', 'c'), ('d', 'e', 'f')]

Note that list(...) is needed around the function call because yield results in a generator being returned, which you must iterate over to get your final list result.


问:
Pandas Series not plotting to timeseries chart
I have a data set of house prices - House Price Data. When I use a subset of the data in a Numpy array, I can plot it in this nice timeseries chart:

However, when I use the same data in a Panda Series, the chart goes all lumpy like this:

How can I create a smooth time series line graph (like the first image) using a Panda Series?

Here is what I am doing to get the nice looking time series chart (using Numpy array)(after importing numpy as np, pandas as pd and matplotlib.pyplot as plt):

```<code>data = pd.read_csv('HPI.csv', index_col='Date', parse_dates=True) #pull in csv file, make index the date column and parse the dates
brixton = data[data['RegionName'] == 'Lambeth'] # pull out a subset for the region Lambeth
prices = brixton['AveragePrice'].values # create a numpy array of the average price values
plt.plot(prices) #plot
plt.show() #show
</code>```

Here is what I am doing to get the lumpy one using a Panda series:

```<code>data = pd.read_csv('HPI.csv', index_col='Date', parse_dates=True)
brixton = data[data['RegionName'] == 'Lambeth']
prices_panda = brixton['AveragePrice']
plt.plot(prices_panda)
plt.show()
</code>```

How do I make this second graph show as a nice smooth proper time series?

* This is my first StackOverflow question so please shout if I have left anything out or not been clear *

Any help greatly appreciated

答:
When you did parse_dates=True, pandas read the dates in its default method, which is month-day-year. Your data is formatted according to the British convention, which is day-month-year. As a result, instead of having a data point for the first of every month, your plot is showing data points for the first 12 days of January, and a flat line for the rest of each year. You need to reformat the dates, such as

data.index = pd.to_datetime({'year':data.index.year,'month':data.index.day,'day':data.index.month})

Body:
I have a data set of house prices - House Price Data. When I use a subset of the data in a Numpy array, I can plot it in this nice timeseries chart:

However, when I use the same data in a Panda Series, the chart goes all lumpy like this:

How can I create a smooth time series line graph (like the first image) using a Panda Series?

Here is what I am doing to get the nice looking time series chart (using Numpy array)(after importing numpy as np, pandas as pd and matplotlib.pyplot as plt):

data = pd.read_csv('HPI.csv', index_col='Date', parse_dates=True) #pull in csv file, make index the date column and parse the dates
brixton = data[data['RegionName'] == 'Lambeth'] # pull out a subset for the region Lambeth
prices = brixton['AveragePrice'].values # create a numpy array of the average price values
plt.plot(prices) #plot
plt.show() #show

Here is what I am doing to get the lumpy one using a Panda series:

data = pd.read_csv('HPI.csv', index_col='Date', parse_dates=True)
brixton = data[data['RegionName'] == 'Lambeth']
prices_panda = brixton['AveragePrice']
plt.plot(prices_panda)
plt.show()

How do I make this second graph show as a nice smooth proper time series?

* This is my first StackOverflow question so please shout if I have left anything out or not been clear *

Any help greatly appreciated


问:
Better understanding about battery session from Google Play Console Vitals
I would like to get a better understanding about battery session from Google Play Console Vitals monitoring dashboard.

In the new Google Play Console Vitals, the excessive wakeups are monitored. Here is the explanation given by Google :

Percentage of battery sessions during which more than 10 wakeups
  occurred per hour. A battery session is the period between two full
  charges of a device. Data is collected only when the device is
  off-charger.

What is considered as a faulty session?

If for one hour I get 14 wake ups and 0 for the next 5 hours, will the battery session be considered as faulty?

Is the period that the device is in doze mode included in the battery session?

答:
AFAIK, it is only one factor to consider in the battery session. According to this blog titled : Android vitals: Increase engagement and installs through improved app performance, you have to consider Stability, Render Time and Battery Usage (under battery usage you have to check stuck wake locks and excessive wakeups).

As previously stated, number of wake ups is considered but also the data behind those wake ups should acknowledged.

Here is a list for reference that could help:

Best Practices

Stuck Partial Wake Locks

Excessive Wakeups

Hope this helps.


问:
Mobile app moment is not a function
I have updated SDK to 6.3.0.GA and started getting "moment is not a function".  I have checked Resources folder, moment.js is zero byte. Please help how to fix this.</p>

答: Clean Project; delete build and resources directories. Build project again and "moment is not a function" disappears</p>

Title: Mobile app moment is not a function


问:
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I keep track of the indices which summed up to sum[i]. I know I could declare extra space but my Sums array already has a size of 64 million, and hence I couldn't complete my O(N^2) solution. Please advice if I can do some optimization or if I need some totally different technique.</p>

答:
I combined the suggestions by @Matthieu M. and @Chris Hopman, and (after much trial and error) I came up with this algorithm that should be O(n log n + log (n-k)! + k) in time and O(log(n-k)) in space (the stack). That should be O(n log n) overall. It's in Python, but it doesn't use any Python-specific features.</p>

```<code>import bisect

def binsearch(r, q, i, j): # O(log (j-i))
    return bisect.bisect_left(q, r, i, j)

def binfind(q, m, i, j):
    while i + 1 < j:
        r = m - (q[i] + q[j])
        if r < q[i]:
            j -= 1
        elif r > q[j]:
            i += 1
        else:
            k = binsearch(r, q, i + 1, j - 1)  # O(log (j-i))
            if not (i < k < j):
                return None
            elif q[k] == r:
                return (i, k, j)
            else:
                return (
                    binfind(q, m, i + 1, j)
                    or
                    binfind(q, m, i, j - 1)
                    )

def find_sumof3(q, m):
    return binfind(sorted(q), m, 0, len(q) - 1)
</code>```

Body:
I combined the suggestions by @Matthieu M. and @Chris Hopman, and (after much trial and error) I came up with this algorithm that should be O(n log n + log (n-k)! + k) in time and O(log(n-k)) in space (the stack). That should be O(n log n) overall. It's in Python, but it doesn't use any Python-specific features.

import bisect

def binsearch(r, q, i, j): # O(log (j-i))
    return bisect.bisect_left(q, r, i, j)

def binfind(q, m, i, j):
    while i + 1 < j:
        r = m - (q[i] + q[j])
        if r < q[i]:
            j -= 1
        elif r > q[j]:
            i += 1
        else:
            k = binsearch(r, q, i + 1, j - 1)  # O(log (j-i))
            if not (i < k < j):
                return None
            elif q[k] == r:
                return (i, k, j)
            else:
                return (
                    binfind(q, m, i + 1, j)
                    or
                    binfind(q, m, i, j - 1)
                    )

def find_sumof3(q, m):
    return binfind(sorted(q), m, 0, len(q) - 1)


问:
Google Script - onEdit(e) not triggering
I have a google sheet with some script running behind it.  I've had to separate some of the tabs out to individual workbooks, and have been updating the script accordingly.  One of the functions I had was an onEdit(e) trigger, that was no longer running in the new workbook.  As part of my testing, I've simplified it to just:

```<code>function onEdit(e) {
  Logger.log("TEST");
}
</code>```

No matter the changes I make in the sheet this is attached to, the Logger.log never writes.

I've done some research, especially into the simple trigger restrictions, and one of those relates to openByURL, which I am using elsewhere in the script.

```<code>var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');
</code>```

Even though the onEdit(e) doesn't directly relate, is the presence of the openByUrl within the script what is preventing the onEdit(e) from running?  If so, are there ways to get around that, so that I can trigger actions based on an edit, but also be able to pull data from an alternate workbook?

答:
Regarding the Logger, can you try:

Logger.log(["TEST"]); instead of Logger.log("TEST");

Your login line does not work for me either but works with the brackets.

Body:
I have a google sheet with some script running behind it.  I've had to separate some of the tabs out to individual workbooks, and have been updating the script accordingly.  One of the functions I had was an onEdit(e) trigger, that was no longer running in the new workbook.  As part of my testing, I've simplified it to just:

function onEdit(e) {
  Logger.log("TEST");
}

No matter the changes I make in the sheet this is attached to, the Logger.log never writes.

I've done some research, especially into the simple trigger restrictions, and one of those relates to openByURL, which I am using elsewhere in the script.

var otherBook = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/etcetc/edit');

Even though the onEdit(e) doesn't directly relate, is the presence of the openByUrl within the script what is preventing the onEdit(e) from running?  If so, are there ways to get around that, so that I can trigger actions based on an edit, but also be able to pull data from an alternate workbook?


问:
How to print out words under words in python?
If you don't understand my title just ignore it and read this instead....
so this is my code...

```<code>   alphabets=["a", "b","c", "d","e","f"]
   nums=["one","two"]

   for num in nums[:2]:
       print(num.title())
       print(alphabets[:3])
</code>```

the output is like this......

```<code>    one
    ['a','b','c']
    two
    ['d','e','f']
</code>```

I don't know what to do I already tried tons of different things. All I need is to get all the code in eight lines and I am expecting to get the output something like this...

```<code>    one
    ['a','b','c']
    two
    ['a','b','c']
</code>```

the only problemis the second line outputs the same thing "a,b,and c" instead i want like "d,e,and f". Please Help! Thanks in advance!

答:
A very simple solution and, maybe, unpythonic:</p>

```<code>alphabets=["a", "b","c", "d","e","f"]
nums=["one","two"]

i = 0
for num in nums[:2]:
    print(num.title())
    print(alphabets[i:i+3])
    i = i + 3
</code>```

Body:
If you don't understand my title just ignore it and read this instead....
so this is my code...

   alphabets=["a", "b","c", "d","e","f"]
   nums=["one","two"]

   for num in nums[:2]:
       print(num.title())
       print(alphabets[:3])

the output is like this......

    one
    ['a','b','c']
    two
    ['d','e','f']

I don't know what to do I already tried tons of different things. All I need is to get all the code in eight lines and I am expecting to get the output something like this...

    one
    ['a','b','c']
    two
    ['a','b','c']

the only problemis the second line outputs the same thing "a,b,and c" instead i want like "d,e,and f". Please Help! Thanks in advance!

Body:
A very simple solution and, maybe, unpythonic:

alphabets=["a", "b","c", "d","e","f"]
nums=["one","two"]

i = 0
for num in nums[:2]:
    print(num.title())
    print(alphabets[i:i+3])
    i = i + 3


问:
How to join two cache into the Model
I need to join two list cached into my Model, to build a new cached list

I've tried the code below but cached_groups is producing an empty result. Any ideas?

```<code>  def cached_favgroups
    Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
  end

  def cached_groups_all
    Rails.cache.fetch([self, "groups"])
  end

  def cached_groups
    Rails.cache.fetch(self.cached_groups_all - self.cached_favgroups )
  end
</code>```

答:
You need to add a block to the fetch method.   Try this:

```<code>def cached_groups
  Rails.cache.fetch([self, "groups_all_favgroups"]) do
    self.cached_groups_all - self.cached_favgroups
  end
end
</code>```

Title: How to join two cache into the Model

Body:
I need to join two list cached into my Model, to build a new cached list

I've tried the code below but cached_groups is producing an empty result. Any ideas?

  def cached_favgroups
    Rails.cache.fetch([self, "fav_groups"]) {fav_groups.to_a}
  end

  def cached_groups_all
    Rails.cache.fetch([self, "groups"])
  end

  def cached_groups
    Rails.cache.fetch(self.cached_groups_all - self.cached_favgroups )
  end

Body:
You need to add a block to the fetch method.   Try this:

def cached_groups
  Rails.cache.fetch([self, "groups_all_favgroups"]) do
    self.cached_groups_all - self.cached_favgroups
  end
end


问:
SQL Server Code Reuse Via Stored Procedures - Good or Bad Practice?
I'm currently considering design options for a reporting application based on an existing dataset.

There are several clear opportunities for code reuse given that many of the reports need to use the same base data set (Edited).

The tempation is to create some base stored procedure that I can reuse throughout this system, however, the contract I was on 6 months ago or so showed me what the down side of this practice - multiple layers of - large stored procedure calls returning subsets of data in, making it very very difficult to workout what was going on, debug and test.

I'm these days of the opinion that code reuse does not necessarily enhance maintainability in database design.

I'm looking for some insight on this from a more experienced SQL Server dev than myself?

Thanks in advance.

答:
Code reuse in TSQL needs to be taken on a case by case base. You need to get into the habit of checking the execution plans for all the queries you write to determine whether the plan looks reasonable or not.

Joining Views onto Views can work fine or can cause inefficiencies depending on their definition.

Inline Table Valued Functions can be an extremely good way of reusing code. They avoid possible predicate pushing issues with Views and as they get expanded out by the query optimiser they allow you to apply filters to the results more efficiently than trying to do the same thing with a multi statement TVF or a stored procedure resultset.


问:
Regexp to extract studyinstanceuid from dump
I need to capture numbers and dots between brackets on lines containing the string 0020,000d, for example:

```<code>I: (0020,000d) UI [1.2.410.200001.1104.20160720104648421 ] #  38, 1 StudyInstanceUID
</code>```

Using this regexp 0020,000d.*\[([\.0-9]+)\] I can match the needed value only if it doesn't have a space inside the brackets. How can I match the needed value ignoring any other character?.

Edit
If I use this regexp 0020,000d.*\[([\.0-9(\s|^\s))]+)\] I can capture numbers and dots and/or spaces, now if the string contains a space how can I capture in a group everything but the space?.

To clarify, I want to extract the 1.2.410.200001.1104.20160720104648421 string.

答:
Codifying my (apparently helpful) answer from the comments:

You just need to allow zero or more spaces after the numbers-and-dots sequence before the closing bracket:

```<code>0020,000d.*\[([.0-9]+) *\]
</code>```

Also, please note that you don't need to escape a dot in a character class.

Body:
I need to capture numbers and dots between brackets on lines containing the string 0020,000d, for example:

I: (0020,000d) UI [1.2.410.200001.1104.20160720104648421 ] #  38, 1 StudyInstanceUID

Using this regexp 0020,000d.*\[([\.0-9]+)\] I can match the needed value only if it doesn't have a space inside the brackets. How can I match the needed value ignoring any other character?.

Edit
If I use this regexp 0020,000d.*\[([\.0-9(\s|^\s))]+)\] I can capture numbers and dots and/or spaces, now if the string contains a space how can I capture in a group everything but the space?.

To clarify, I want to extract the 1.2.410.200001.1104.20160720104648421 string.

Body:
Codifying my (apparently helpful) answer from the comments:

You just need to allow zero or more spaces after the numbers-and-dots sequence before the closing bracket:

0020,000d.*\[([.0-9]+) *\]

Also, please note that you don't need to escape a dot in a character class.


答:
To be as generic as possible, you can use a dictionary:

```<code>alphabets=["a", "b","c", "d","e","f"]
nums=["one","two"]
converter = {"one":1, "two":2, "three":3, "four":4} #can be expanded upon
new_alpha = {a:b for a, b in zip(nums, [alphabets[i:i+len(nums)+1] for i in range(0, len(alphabets), len(nums)+1)])}
for a, b in sorted(new_alpha.items(), key=lambda x:converter[x[0]]):
    print(a)
    print(b)
</code>```

Output:

```<code>one
['a', 'b', 'c']
two
['d', 'e', 'f']
</code>```

Title: How to print out words under words in python?

Body:
To be as generic as possible, you can use a dictionary:

alphabets=["a", "b","c", "d","e","f"]
nums=["one","two"]
converter = {"one":1, "two":2, "three":3, "four":4} #can be expanded upon
new_alpha = {a:b for a, b in zip(nums, [alphabets[i:i+len(nums)+1] for i in range(0, len(alphabets), len(nums)+1)])}
for a, b in sorted(new_alpha.items(), key=lambda x:converter[x[0]]):
    print(a)
    print(b)

Output:

one
['a', 'b', 'c']
two
['d', 'e', 'f']


问:
Fsharp: Passing N Parameters for a function
I'm trying to create a function that takes in a variable amount of parameters but I can't seem to find any viable solution for F#.

```<code>let expression = (fun a b -> a || b)
let expressionTriple = (fun a b c -> (a || b) && c)

// This doesn't work because expression can either be a function that takes fixed arguments
let truthTable numPredicates expression =
    if numPredicates = 2 then
        expression true true
    else
        expression true true false

truthTable 2 expression
truthTable 3 expressionTriple
</code>```

How can I pass in a variable amount of arguments into the expression function?

答:
```<code>let expression = (fun [a; b] -> a || b)
let expressionTriple = (fun [a; b; c] -> (a || b) && c)

let truthTable numPredicates expression =
   if numPredicates = 2 then
      expression [true; true]
   else
      expression [true; true; false]

truthTable 2 expression
truthTable 3 expressionTriple
</code>```

Body:
I'm trying to create a function that takes in a variable amount of parameters but I can't seem to find any viable solution for F#.

let expression = (fun a b -> a || b)
let expressionTriple = (fun a b c -> (a || b) && c)

// This doesn't work because expression can either be a function that takes fixed arguments
let truthTable numPredicates expression =
    if numPredicates = 2 then
        expression true true
    else
        expression true true false

truthTable 2 expression
truthTable 3 expressionTriple

How can I pass in a variable amount of arguments into the expression function?


问:
R: Find outliers with mvBACON
I'm new to R and working on an assignment were I am supposed to replicate the results from a linear regression (time series data with 1360 observations and 52 variables (11 variables in the regression model)). In the original study the researchers identified outliers with the Hadi method. It seems that this is done best in R with the mvBacon function, is this correct? I cannot seem to find a good answer on how to use this though, could anyone please tell me how I can use this function to find the outliers?
(I would very much appreciate an answer that is explained as simply as possible since R is very new to me).
Thank you very much!</p>

答:
Yes, the mvBACON is for outlier identification based on some distance. The default one is the Mahalanobis distance.
The following code will walk you through a simple example on the mtcars subdataset on how to identify outliers with mvBACON:

```<code># load packages
library(dplyr)
library(magrittr)

# Use mtcars (sub)dataset and plot it
data <- mtcars %>% select(mpg, disp)
plot(data, main = "mtcars")
</code>```

```<code># Add some outliers and plot again
data <- rbind(data,
              data.frame(mpg = c(1, 80), disp = c(800, 1000)))
plot(data, main = "mtcars")
</code>```

```<code># Use mvBacon to calculate the distances and get the ouliers
# install.packages("robustX) # uncomment line to install package
library(robustX)

#compute distance - default is Mahalonobis
distances <- mvBACON(data)

# Plot it again...
plot(data, main = "mtcars")

# ...with highlighting the outliers
points(data[!distances$subset, ], col = "red", pch = 19)
</code>```

```<code># Some fine tuning, since many of the outliers seem to be still good for regression
distances <- mvBACON(data, alpha = 0.6)

# update plot
plot(data, main = "mtcars")
points(data[!distances$subset, ], col = "red", pch = 19)
</code>```

Title: R: Find outliers with mvBACON

Body:
Yes, the mvBACON is for outlier identification based on some distance. The default one is the Mahalanobis distance.
The following code will walk you through a simple example on the mtcars subdataset on how to identify outliers with mvBACON:

# load packages
library(dplyr)
library(magrittr)

# Use mtcars (sub)dataset and plot it
data <- mtcars %>% select(mpg, disp)
plot(data, main = "mtcars")

# Add some outliers and plot again
data <- rbind(data,
              data.frame(mpg = c(1, 80), disp = c(800, 1000)))
plot(data, main = "mtcars")

# Use mvBacon to calculate the distances and get the ouliers
# install.packages("robustX) # uncomment line to install package
library(robustX)

#compute distance - default is Mahalonobis
distances <- mvBACON(data)

# Plot it again...
plot(data, main = "mtcars")

# ...with highlighting the outliers
points(data[!distances$subset, ], col = "red", pch = 19)

# Some fine tuning, since many of the outliers seem to be still good for regression
distances <- mvBACON(data, alpha = 0.6)

# update plot
plot(data, main = "mtcars")
points(data[!distances$subset, ], col = "red", pch = 19)

ContentLicense: CC BY-SA 4.0


问:
VBA - How to select specific charts in excel and paste them on single slide in power point
I have the following code:

```<code>Sub Export_Allcahrts_ppt()
  Dim mypowerpoint As PowerPoint.Application
  Dim mypowerpoint_pres As PowerPoint.Presentation
  Dim myslide As PowerPoint.Slide
  Dim mychart As ChartObject

  Set mypowerpoint = New PowerPoint.Application
  mypowerpoint.Visible = msoTrue
  Set mypowerpoint_pres = mypowerpoint.Presentations.Add
  Set myslide = mypowerpoint_pres.Slides.Add(1, ppLayoutBlank)
  For Each mychart In Sheet1.ChartObjects
    mychart.Copy
    myslide.Shapes.PasteSpecial ppPasteBitmap
    With myslide.Shapes(myslide.Shapes.Count)
      .Top = 100
      .Height = 200
      .Left = 30
    End With
  Next
End Sub
</code>```

How to select specific charts like chart 1 in sheet 1, chart 2 in sheet 2 in excel and paste them on a single slide in powerpoint?

答:
This will iterate through all sheets in workbook, then just check for the charts you are looking for.  If the charts are named like chart1 on sheet1, then.....</p>

```<code>Set wb as activeworkbook
For Each sht In wb.Worksheets
  For Each cht In sht.ChartObjects
    'check for name of chart, if statements or a case select statement.
    if cht.name = "Chart" & sht.index then

        'Copy to PPT
    end if

  Next cht
Next sht
</code>```

Body:
I have the following code:

Sub Export_Allcahrts_ppt()
  Dim mypowerpoint As PowerPoint.Application
  Dim mypowerpoint_pres As PowerPoint.Presentation
  Dim myslide As PowerPoint.Slide
  Dim mychart As ChartObject

  Set mypowerpoint = New PowerPoint.Application
  mypowerpoint.Visible = msoTrue
  Set mypowerpoint_pres = mypowerpoint.Presentations.Add
  Set myslide = mypowerpoint_pres.Slides.Add(1, ppLayoutBlank)
  For Each mychart In Sheet1.ChartObjects
    mychart.Copy
    myslide.Shapes.PasteSpecial ppPasteBitmap
    With myslide.Shapes(myslide.Shapes.Count)
      .Top = 100
      .Height = 200
      .Left = 30
    End With
  Next
End Sub

How to select specific charts like chart 1 in sheet 1, chart 2 in sheet 2 in excel and paste them on a single slide in powerpoint?

Body:
This will iterate through all sheets in workbook, then just check for the charts you are looking for.  If the charts are named like chart1 on sheet1, then.....

Set wb as activeworkbook
For Each sht In wb.Worksheets
  For Each cht In sht.ChartObjects
    'check for name of chart, if statements or a case select statement.
    if cht.name = "Chart" & sht.index then

        'Copy to PPT
    end if

  Next cht
Next sht


问:
Python Variables across Class functions - how to call them?
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

```<code>class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined
</code>```

答:
how do I reference this variable across other functions in the class

Several things I see wrong here. First of all, you are calling running_sum on the class itself which doesn't make sense since you are declaring running_sum as an attribute of an instance of Test. Second, from the way you formatted your question, it seems that test_function is outside of the class Test which doesn't make sense since you are passing self to it, implying it is an instance method. To resolve you could do this:

```<code>class Test:
    def __init__(self):
        self.running_sum = 0
    def test_function(self):
        print(self.running_sum)
</code>```

Then again this also is weird... Why would you need a "test_function" when you can simply test the value of running_sum by simply doing:

```<code>x = Test()
x.running_sum
</code>```

Body:
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()

Error:

Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined

Body:
how do I reference this variable across other functions in the class

Several things I see wrong here. First of all, you are calling running_sum on the class itself which doesn't make sense since you are declaring running_sum as an attribute of an instance of Test. Second, from the way you formatted your question, it seems that test_function is outside of the class Test which doesn't make sense since you are passing self to it, implying it is an instance method. To resolve you could do this:

class Test:
    def __init__(self):
        self.running_sum = 0
    def test_function(self):
        print(self.running_sum)

Then again this also is weird... Why would you need a "test_function" when you can simply test the value of running_sum by simply doing:

x = Test()
x.running_sum


问:
Django 1.9.1 - make migrations can't detect changes
I have Django 1.9.1 installed:

```<code>>>> django.__version__
'1.9.1'
</code>```

And I had my model defined in main.models:

```<code>from __future__ import unicode_literals
from django.db import models

class Collection:
    name = models.CharField(max_length=1024)
    desc = models.TextField()
    snap = models.ImageField()
    f = models.FileField()

    def __str__(self):
        return self.name;
</code>```

And I had already added "main" to INSTALLED_APPS in settings:

```<code>INSTALLED_APPS = [
    'main',
    ... # Other Django stuff
]
</code>```

And when I run

```<code>python manage.py makemigrations
</code>```

I get the following:

```<code>➜ python manage.py makemigrations
No changes detected
</code>```

I've searched through the internet and it seems like no one has encountered a problem like this... Any help will be greatly appreciated!! Thanks!

答: The Connection class needs to inherit from models.Model.

Body:
I have Django 1.9.1 installed:

>>> django.__version__
'1.9.1'

And I had my model defined in main.models:

from __future__ import unicode_literals
from django.db import models

class Collection:
    name = models.CharField(max_length=1024)
    desc = models.TextField()
    snap = models.ImageField()
    f = models.FileField()

    def __str__(self):
        return self.name;

And I had already added "main" to INSTALLED_APPS in settings:

INSTALLED_APPS = [
    'main',
    ... # Other Django stuff
]

And when I run

python manage.py makemigrations

I get the following:

➜ python manage.py makemigrations
No changes detected

I've searched through the internet and it seems like no one has encountered a problem like this... Any help will be greatly appreciated!! Thanks!


问:
ASP.NET code to receive IM using lync SDK 2013 (c#)
I am a beginner in this field and learning how to send and receive IM using lync SDK 2013.
i have gone through and understood how to send IM using lync SDK 2013.
Now I want to learn how to receive IM using the same.
can anyone help me with the code ?</p>

答:
Unfortunately, the Lync 2013 client SDK has a hard dependency on the Lync 2013 client application. That is, you app can only run on a computer where the Lync 2013 client is installed and can run. This is because the SDK depends on the SIP protocol stack that lives in the client.
If you want to send and receive IM in an ASP.NET app, you'll need to use our Skype Web SDK, as was indicated in the first answer.</p>


问:
Can I Send a Web Notification on a Specific Time?
I am trying to implement notifications that do not need the interaction of the backend to be shown. The use of this is to put a remind me button, that would send a notification on certain time of the day (that the user specified). I am pretty new to service workers but I understand that they work asynchronously. That being said, is there any way in which I could do something like the following pseudocode?

```<code>function timeLeft(time){
    setTimeout(() => showNotification(), time);
}
</code>```

This would work if I put it on a regular javascript file and the user has the browser still open.

It does not need to be exactly like that, it just needs to solve my problem. Thank you un advance.

答:
First you need to have an ID for each browser. If you use the Push API, then you can use the browser endpoint.

When a user adds a reminder, you must store the tuple (endpoint, send_at, reminder) in your database on your server

Run a cron job on your server (or create a scheduled job with Sidekiq, etc.) in order to send the reminder at the correct time (using the Push API)

Otherwise you can use a service which allows you to create scheduled notifications: see this example on my blog.

Body:
I am trying to implement notifications that do not need the interaction of the backend to be shown. The use of this is to put a remind me button, that would send a notification on certain time of the day (that the user specified). I am pretty new to service workers but I understand that they work asynchronously. That being said, is there any way in which I could do something like the following pseudocode?

function timeLeft(time){
    setTimeout(() => showNotification(), time);
}

This would work if I put it on a regular javascript file and the user has the browser still open.

It does not need to be exactly like that, it just needs to solve my problem. Thank you un advance.


问:
How to generate a random number in Swift?
I realize the Swift book provided an implementation of a random number generator.  Is the best practice to copy and paste this implementation? Or is there a library that does this that we can use now?</p>

答:
Details

xCode 9.1, Swift 4

Math oriented solution (1)

```<code>import Foundation

class Random {

    subscript<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
        get {
            return rand(min-1, max+1)
        }
    }
}

let rand = Random()

func rand<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
    let _min = min + 1
    let difference = max - _min
    return T(arc4random_uniform(UInt32(difference))) + _min
}
</code>```

Usage of solution (1)

```<code>let x = rand(-5, 5)       // x = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
let x = rand[0, 10]       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

Programmers oriented solution (2)

Do not forget to add Math oriented solution (1) code here

```<code>import Foundation

extension CountableRange where Bound : BinaryInteger {

    var random: Bound {
        return rand(lowerBound-1, upperBound)
    }
}

extension CountableClosedRange where Bound : BinaryInteger {

    var random: Bound {
        return rand[lowerBound, upperBound]
    }
}
</code>```

Usage of solution (2)

```<code>let x = (-8..<2).random           // x = [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
let x = (0..<10).random           // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let x = (-10 ... -2).random       // x = [-10, -9, -8, -7, -6, -5, -4, -3, -2]
</code>```

Full Sample

Do not forget to add solution (1) and solution (2) codes here

```<code>private func generateRandNums(closure:()->(Int)) {

    var allNums = Set<Int>()
    for _ in 0..<100 {
        allNums.insert(closure())
    }
    print(allNums.sorted{ $0 < $1 })
}

generateRandNums {
    (-8..<2).random
}

generateRandNums {
    (0..<10).random
}

generateRandNums {
    (-10 ... -2).random
}

generateRandNums {
    rand(-5, 5)
}
generateRandNums {
    rand[0, 10]
}
</code>```

Sample result

Body:
Details

xCode 9.1, Swift 4

Math oriented solution (1)

import Foundation

class Random {

    subscript<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
        get {
            return rand(min-1, max+1)
        }
    }
}

let rand = Random()

func rand<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
    let _min = min + 1
    let difference = max - _min
    return T(arc4random_uniform(UInt32(difference))) + _min
}

Usage of solution (1)

let x = rand(-5, 5)       // x = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
let x = rand[0, 10]       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Programmers oriented solution (2)

Do not forget to add Math oriented solution (1) code here

import Foundation

extension CountableRange where Bound : BinaryInteger {

    var random: Bound {
        return rand(lowerBound-1, upperBound)
    }
}

extension CountableClosedRange where Bound : BinaryInteger {

    var random: Bound {
        return rand[lowerBound, upperBound]
    }
}

Usage of solution (2)

let x = (-8..<2).random           // x = [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
let x = (0..<10).random           // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let x = (-10 ... -2).random       // x = [-10, -9, -8, -7, -6, -5, -4, -3, -2]

Full Sample

Do not forget to add solution (1) and solution (2) codes here

private func generateRandNums(closure:()->(Int)) {

    var allNums = Set<Int>()
    for _ in 0..<100 {
        allNums.insert(closure())
    }
    print(allNums.sorted{ $0 < $1 })
}

generateRandNums {
    (-8..<2).random
}

generateRandNums {
    (0..<10).random
}

generateRandNums {
    (-10 ... -2).random
}

generateRandNums {
    rand(-5, 5)
}
generateRandNums {
    rand[0, 10]
}

Sample result


问:
Tool to find duplicate sections in a text (XML) file?
I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?

I'd be fine with a tool that does this generally for text documents.

答:
Here is a first attempt, written in Python and using only standard libraries. You can improve it in many ways (trim leading and ending whitespaces, computing a hash of the text to decrease memory requirments, better displaying of the elements, with their line number, etc):

import xml.etree.ElementTree as ElementTree
import sys

def print_elem(element):
    return "<%s>" % element.tag

if len(sys.argv) != 2:
    print >> sys.stderr, "Usage: %s filename" % sys.argv[0]
    sys.exit(1)
filename = sys.argv[1]
tree = ElementTree.parse(filename)
root = tree.getroot()
chunks = {}
iter = root.findall('.//*')
for element in iter:
    if element.text in chunks:
        chunks[element.text].append(element)
    else:
        chunks[element.text] = [element,]
for text in chunks:
    if len(chunks[text]) > 1:
        print "\"%s\" is a duplicate: found in %s" % \
              (text, map(print_elem, chunks[text]))
```

<p>If you give it this XML file:</p>

```<foo>
<bar>Hop</bar><quiz>Gaw</quiz>

<und>Hop</und>

```

<p>it will output:</p>

```"Hop" is a duplicate: found in ['<bar>', '<und>']
```

OwnerDisplayName: parsifal

Body:
Here is a first attempt, written in Python and using only standard libraries. You can improve it in many ways (trim leading and ending whitespaces, computing a hash of the text to decrease memory requirments, better displaying of the elements, with their line number, etc):

import xml.etree.ElementTree as ElementTree
import sys

def print_elem(element):
    return "<%s>" % element.tag

if len(sys.argv) != 2:
    print >> sys.stderr, "Usage: %s filename" % sys.argv[0]
    sys.exit(1)
filename = sys.argv[1]
tree = ElementTree.parse(filename)
root = tree.getroot()
chunks = {}
iter = root.findall('.//*')
for element in iter:
    if element.text in chunks:
        chunks[element.text].append(element)
    else:
        chunks[element.text] = [element,]
for text in chunks:
    if len(chunks[text]) > 1:
        print "\"%s\" is a duplicate: found in %s" % \
              (text, map(print_elem, chunks[text]))

If you give it this XML file:

<foo>
<bar>Hop</bar><quiz>Gaw</quiz>
<sub>
<und>Hop</und>
</sub>

it will output:

"Hop" is a duplicate: found in ['<bar>', '<und>']

OwnerDisplayName: bortzmeyer

LastEditorDisplayName: bortzmeyer


问:
convert Promise based function to an observable based function
What is the simplest way to do something like this in an observable approach way?</p>

```<code>async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs
</code>```

答:
After searching a little more I end up with this approach which I'm not sure be the simplest one:</p>

```<code>function observableBased() {
    return Observable.create((observable) => {
        // some async jobs
        // then
        observable.next();
    })
}

observableBased().subscriber(()=>{
    // do other jobs
})
</code>```

Body:
What is the simplest way to do something like this in an observable approach way?

async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs

Body:
After searching a little more I end up with this approach which I'm not sure be the simplest one:

function observableBased() {
    return Observable.create((observable) => {
        // some async jobs
        // then
        observable.next();
    })
}

observableBased().subscriber(()=>{
    // do other jobs
})


问:
How to omit parts of a line while reading a text file in MATLAB (2016 and above)
I need to develop a MATLAB code to read a text file.
The lines have the following form:

```<code>|     1 |   1   |      6.000 |    454.000 |      423 |

|     1 |   1   |     11.000 |   -454.000 |      426 |

|     1 |   1   |     45.000 |    454.000 |      428 |
</code>```

Is there a way to omit the vertical bars (and just keep the numbers?)

Thanks a lot!

答:
MATLAB offers multiple different file IO options

For example, you could use textscan:

```<code>fID = fopen('test.txt');
test = textscan(fID, '%*u %u %u %f %f %u', 'Delimiter', '|');
fclose(fID);
</code>```

Which returns an n x 5 cell array of your columns that you can manipulate/concatenate as desired.

Or you could use readtable:

```<code>mydata = readtable('test.txt', 'Delimiter', '|', 'Format', '%*u %u %u %f %f %u');
</code>```

Which returns an n x 5 table of your data.

Body:
I need to develop a MATLAB code to read a text file.
The lines have the following form:

|     1 |   1   |      6.000 |    454.000 |      423 |

|     1 |   1   |     11.000 |   -454.000 |      426 |

|     1 |   1   |     45.000 |    454.000 |      428 |

Is there a way to omit the vertical bars (and just keep the numbers?)

Thanks a lot!

Body:
MATLAB offers multiple different file IO options

For example, you could use textscan:

fID = fopen('test.txt');
test = textscan(fID, '%*u %u %u %f %f %u', 'Delimiter', '|');
fclose(fID);

Which returns an n x 5 cell array of your columns that you can manipulate/concatenate as desired.

Or you could use readtable:

mydata = readtable('test.txt', 'Delimiter', '|', 'Format', '%*u %u %u %f %f %u');

Which returns an n x 5 table of your data.


问:
Puppeteer installation has error
I have problem with puppeteer. I cannot install it on my debian 8.7.1.
These are the steps:

1.install chrome:

```<code>wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
sudo apt-get -f install
sudo dpkg -i google-chrome-stable_current_amd64.deb
</code>```

2.install nodejs & puppeteer:

```<code>apt-get install curl
curl -sL https://deb.nodesource.com/setup_8.x | bash -
sudo apt-get install -y nodejs
npm i puppeteer
</code>```

When I run npm i puppeteer, the errors are:

```<code>> puppeteer@0.11.0 install /root/node_modules/puppeteer
> node install.js

ERROR: Failed to download Chromium r499413! Set "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variable to skip download.
Error: Download failed: server returned code 403. URL:  https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/499413 /chrome-linux.zip
at ClientRequest.https.get.response (/root/node_modules/puppeteer/utils/ChromiumDownloader.js:195:21)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at ClientRequest.emit (events.js:210:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:565:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
at TLSSocket.socketOnData (_http_client.js:454:20)
at emitOne (events.js:115:13)
at TLSSocket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! puppeteer@0.11.0 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@0.11.0 install script.
npm ERR! This is probably not a problem with npm. There is likely   additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-10-04T12_32_37_607Z-debug.log
</code>```

I run the command npm config set PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true to  skip download but it wants to download chromium yet.

Any idea to solve this problem?

答:
Error: spawn EACCES

This roughly means that puppeteer cannot execute Chrome due to permissions issues. If you're having troubles I have a docker image here that you can use and interact with remotely. The issue with Chrome and many linux distros is that installation is quite a challenge to solve.

Title: Puppeteer installation has error

Body:
I have problem with puppeteer. I cannot install it on my debian 8.7.1.
These are the steps:

1.install chrome:

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
sudo apt-get -f install
sudo dpkg -i google-chrome-stable_current_amd64.deb

2.install nodejs & puppeteer:

apt-get install curl
curl -sL https://deb.nodesource.com/setup_8.x | bash -
sudo apt-get install -y nodejs
npm i puppeteer

When I run npm i puppeteer, the errors are:

> puppeteer@0.11.0 install /root/node_modules/puppeteer
> node install.js

ERROR: Failed to download Chromium r499413! Set "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variable to skip download.
Error: Download failed: server returned code 403. URL:  https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/499413 /chrome-linux.zip
at ClientRequest.https.get.response (/root/node_modules/puppeteer/utils/ChromiumDownloader.js:195:21)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at ClientRequest.emit (events.js:210:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:565:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
at TLSSocket.socketOnData (_http_client.js:454:20)
at emitOne (events.js:115:13)
at TLSSocket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! puppeteer@0.11.0 install: `node install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the puppeteer@0.11.0 install script.
npm ERR! This is probably not a problem with npm. There is likely   additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-10-04T12_32_37_607Z-debug.log

I run the command npm config set PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true to  skip download but it wants to download chromium yet.

Any idea to solve this problem?