问:
Use the increased navigation-bar title in iOS 11
iOS 11 Beta 1 uses the increased navigation-bar title for almost all system-apps (it started doing this in iOS 10 and the Music app). I am wondering if Apple has a public API for this coming in iOS 11, or whether it will stay private for now.

The behavior is that the title has an increased font-size, is left aligned and will move to the navigation-bar once the user scrolls down. I've attached some screens showing this behavior in the Messages app here:

Although I could not find any reference in the UINavigationController and UINavigationBar so far, maybe someone knows some more details!

答:
UINavigationBar has a prefersLargeTitles: Bool property. Docs here.

```<code>class UINavigationBar {
   var prefersLargeTitles: Bool
}
</code>```

UINavigationItem has a largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode property. Docs here.

```<code>class UINavigationItem {
   var largeTitleDisplayMode: LargeTitleDisplayMode
}
</code>```

Both of these can be modified in the Interface Builder.

To turn on this behavior set navigationController.navigationBar.prefersLargeTitles to true. Then you can control each individual view controller in the navigation controller stack by setting navigationItem.largeTitleDisplayMode.

The general design guidelines by Apple are that large titles shouldn't be used everywhere (for example, the Clock app does not use them), and it's generally preferred that only the first level of the navigation controller uses the large titles. However, these are just general guidelines.

Large titles are introduced in What's New in Cocoa Touch video (7:37).

Body:
UINavigationBar has a prefersLargeTitles: Bool property. Docs here.

class UINavigationBar {
   var prefersLargeTitles: Bool
}

UINavigationItem has a largeTitleDisplayMode: UINavigationItem.LargeTitleDisplayMode property. Docs here.

class UINavigationItem {
   var largeTitleDisplayMode: LargeTitleDisplayMode
}

Both of these can be modified in the Interface Builder.

To turn on this behavior set navigationController.navigationBar.prefersLargeTitles to true. Then you can control each individual view controller in the navigation controller stack by setting navigationItem.largeTitleDisplayMode.

The general design guidelines by Apple are that large titles shouldn't be used everywhere (for example, the Clock app does not use them), and it's generally preferred that only the first level of the navigation controller uses the large titles. However, these are just general guidelines.

Large titles are introduced in What's New in Cocoa Touch video (7:37).


来源: stackexchange

问:
Generating SAS to access Azure storage
I am trying to write a Bash script that would take backup of an Azure App service and save the backup into a container in Azure storage.

To do so, I need a SAS to access the storage and to generate one I would use the following command:

```<code>az storage blob generate-sas -c containername --account-name storage-account-name -n blob-name
</code>```

The problem here is, I also need to provide the blob name for the above command to work, but I would like my backup to be stored directly in the container.

But if I am using Powershell and follow the document here it doesn't require a blob storage name to create a SAS.

So I was wondering if there's a way to generate SAS using Azure-CLI that is valid on the container level and not on the blob level.

答:
I agree with Gaurav. Yes, you could generate SAS that is valid on the container level. You also could use the following commands to generate it. It works on bash shell.

```<code>groupname=<>
accountname=<>
containername=<>
##generate connection-string
StorageAccountConnectionString=`az storage account show-connection-string --name $accountname --resource-group $groupname --output tsv`
##generate sas
sas=`az storage container generate-sas --connection-string $StorageAccountConnectionString -n $containername --permissions rl --expiry 'Y-m-dTH:M:SZ' --output tsv`

#usage example

groupname=shui
accountname=shui
containername=shui
##generate connection-string
StorageAccountConnectionString=`az storage account show-connection-string --name $accountname --resource-group $groupname --output tsv`
##generate sas
sas=`az storage container generate-sas --connection-string $StorageAccountConnectionString -n $containername --permissions rl --expiry '2018-06-30' --output tsv`
echo $sas
se=2018-06-30&sp=rl&sv=2016-05-31&sr=c&sig=GTdFdruu2DxzSoIKCb0K7YQpBPaJdHSaXLUPSOzTcZ4%3E
</code>```

You also could use Azure CLI 2.0 to get storage key.

```<code>#usage example
az storage account keys list -n shuihdi -g shui4 --output tsv|head -n 1|awk '{print $3}'
5NQdibPibJrxQ3StybPb1kMsAL8NVdL3GT3KWcodWL96vhBNz5fYRKuXmYWkHxPxvxGnmJTOAY2rizgnJa4qmQ==
</code>```

ContentLicense: CC BY-SA 3.0

Title: Generating SAS to access Azure storage

Body:
I am trying to write a Bash script that would take backup of an Azure App service and save the backup into a container in Azure storage.

To do so, I need a SAS to access the storage and to generate one I would use the following command:

az storage blob generate-sas -c containername --account-name storage-account-name -n blob-name

The problem here is, I also need to provide the blob name for the above command to work, but I would like my backup to be stored directly in the container.

But if I am using Powershell and follow the document here it doesn't require a blob storage name to create a SAS.

So I was wondering if there's a way to generate SAS using Azure-CLI that is valid on the container level and not on the blob level.

Body:
I agree with Gaurav. Yes, you could generate SAS that is valid on the container level. You also could use the following commands to generate it. It works on bash shell.

groupname=<>
accountname=<>
containername=<>
##generate connection-string
StorageAccountConnectionString=`az storage account show-connection-string --name $accountname --resource-group $groupname --output tsv`
##generate sas
sas=`az storage container generate-sas --connection-string $StorageAccountConnectionString -n $containername --permissions rl --expiry 'Y-m-dTH:M:SZ' --output tsv`

#usage example

groupname=shui
accountname=shui
containername=shui
##generate connection-string
StorageAccountConnectionString=`az storage account show-connection-string --name $accountname --resource-group $groupname --output tsv`
##generate sas
sas=`az storage container generate-sas --connection-string $StorageAccountConnectionString -n $containername --permissions rl --expiry '2018-06-30' --output tsv`
echo $sas
se=2018-06-30&sp=rl&sv=2016-05-31&sr=c&sig=GTdFdruu2DxzSoIKCb0K7YQpBPaJdHSaXLUPSOzTcZ4%3E

You also could use Azure CLI 2.0 to get storage key.

#usage example
az storage account keys list -n shuihdi -g shui4 --output tsv|head -n 1|awk '{print $3}'
5NQdibPibJrxQ3StybPb1kMsAL8NVdL3GT3KWcodWL96vhBNz5fYRKuXmYWkHxPxvxGnmJTOAY2rizgnJa4qmQ==


问:
How to Count Number of in in a field
I have a data base named nominator which has some fields

it have a in field named 'noinatedUnder' how can i show the number of inS to that field

this is the Raw text of
SELECT FROM Nominator

```<code>{
    "result": [
        {
            "@type": "d",
            "@rid": "#73:2",
            "@version": 2,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "JJRXW",
            "Email": "testuser@test.com",
            "Name": "nijeesh",
            "Phone": "7894561234",
            "school": "#65:2",
            "in_noinatedUnder": [
                "#161:1",
                "#162:1",
                "#163:1",
                "#164:0",
                "#165:0",
                "#166:0",
                "#167:0",
                "#168:0",
                "#161:0",
                "#162:0",
                "#163:0"
            ],
            "@fieldTypes": "school=x,in_noinatedUnder=g"
        },
        {
            "@type": "d",
            "@rid": "#74:0",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "SU7SV",
            "Email": "npms@school.com",
            "Name": "pon muthu",
            "Phone": "7778455215",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        },
        {
            "@type": "d",
            "@rid": "#75:1",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "4DZ86",
            "Email": "sivaraj@testschool.com",
            "Name": "sivaraj",
            "Phone": "7788899445",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        },
        {
            "@type": "d",
            "@rid": "#76:1",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "HFQJ1",
            "Email": "klndk@knvd.com",
            "Name": "dbhbsd",
            "Phone": "8656548745",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        }
    ],
    "notification": "Query executed in 6.12 sec. Returned 4 record(s)"
}
</code>```

in this on the first entry there is 11 entrys in the in->nominated under area and 0 on everything else  how to select this number using sql for each field

that is it should print

```<code>-----------
count |                                                                           ----------
11
0
0
0
</code>```

i did got the result using php

```<code>    $query = "select * from `Nominator`";
    $result = runquery($query);
    $a = array();

    for($i=0;$i<sizeof($result);$i++)
    {
    echo '<p>';
        echo isset($result[$i]->oData->in_noinatedUnder)?sizeof($result[$i]->oData->in_noinatedUnder):0;

    echo '</p>';
    }

function runquery($query)
{
    $client = new PhpOrient();
    $client->hostname = 'localhost';
    $client->port = 2424;
    $client->username = 'root';
    $client->password = 'hello';
    $client->connect();
    $client->dbOpen('tabe');

    $result = $client->query($query);

    $json = json_decode(json_encode($result));

    if (sizeof($json) > 0) {
        return $json;
    } else {
        return false;
    }

}
</code>```

So is there any way to get the count directly from sql it self, like select count(*) from nominator gives count of nominators

答:
To get the number of vertexes in in try this query:

```<code>select in().size() from <class-name>
</code>```

Hope it helps.

Regards

Title: How to Count Number of in in a field

Body:
I have a data base named nominator which has some fields

it have a in field named 'noinatedUnder' how can i show the number of inS to that field

this is the Raw text of
SELECT FROM Nominator

{
    "result": [
        {
            "@type": "d",
            "@rid": "#73:2",
            "@version": 2,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "JJRXW",
            "Email": "testuser@test.com",
            "Name": "nijeesh",
            "Phone": "7894561234",
            "school": "#65:2",
            "in_noinatedUnder": [
                "#161:1",
                "#162:1",
                "#163:1",
                "#164:0",
                "#165:0",
                "#166:0",
                "#167:0",
                "#168:0",
                "#161:0",
                "#162:0",
                "#163:0"
            ],
            "@fieldTypes": "school=x,in_noinatedUnder=g"
        },
        {
            "@type": "d",
            "@rid": "#74:0",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "SU7SV",
            "Email": "npms@school.com",
            "Name": "pon muthu",
            "Phone": "7778455215",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        },
        {
            "@type": "d",
            "@rid": "#75:1",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "4DZ86",
            "Email": "sivaraj@testschool.com",
            "Name": "sivaraj",
            "Phone": "7788899445",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        },
        {
            "@type": "d",
            "@rid": "#76:1",
            "@version": 1,
            "@class": "Nominator",
            "isTemp": "true",
            "id": "HFQJ1",
            "Email": "klndk@knvd.com",
            "Name": "dbhbsd",
            "Phone": "8656548745",
            "school": "#65:2",
            "@fieldTypes": "school=x"
        }
    ],
    "notification": "Query executed in 6.12 sec. Returned 4 record(s)"
}

in this on the first entry there is 11 entrys in the in->nominated under area and 0 on everything else  how to select this number using sql for each field

that is it should print

-----------
count |                                                                           ----------
11
0
0
0

i did got the result using php

    $query = "select * from `Nominator`";
    $result = runquery($query);
    $a = array();

    for($i=0;$i<sizeof($result);$i++)
    {
    echo '
';
        echo isset($result[$i]->oData->in_noinatedUnder)?sizeof($result[$i]->oData->in_noinatedUnder):0;

    echo '
';
    }

function runquery($query)
{
    $client = new PhpOrient();
    $client->hostname = 'localhost';
    $client->port = 2424;
    $client->username = 'root';
    $client->password = 'hello';
    $client->connect();
    $client->dbOpen('tabe');

    $result = $client->query($query);

    $json = json_decode(json_encode($result));

    if (sizeof($json) > 0) {
        return $json;
    } else {
        return false;
    }

}

So is there any way to get the count directly from sql it self, like select count(*) from nominator gives count of nominators

Body:
To get the number of vertexes in in try this query:

select in().size() from <class-name>

Hope it helps.

Regards


问:
How to show and hide preferences on Android dynamically?
Is there a way to dynamically show and hide preferences?  In my case, I have a checkbox preference that would disable or enable one of 2 preference groups ("with-" and "without-handicap" groups).  While this would be the ideal GUI in a desktop environment, the "with-handicap" takes up nearly the whole screen, while the other, "without-handicap" takes up only a small portion of the screen.

Rather than showing both groups at the same time, I'd like to show only one of them at a time, and dynamically show or hide the 2 groups when the checkbox changes.  Is there a way to do this?

答: I recommend using V7 preference, it has setVisible() method. But I have not tried it yet.

ContentLicense: CC BY-SA 2.5


问:
Filtering chooser intent
I want to get emails from users. I am trying to filter the chooser intent but i am stuck at some point.

Chooser intent brings the user's contacts. I just want to show the installed email apps, with 'to' field auto filled of course.

How can I remove user's contacts and show email apps only?

any help would be greatly appreciated.

here is my code so far:

```<code>    List<Intent> emailAppLauncherIntents = new ArrayList<>();

    Intent emailAppIntent = new Intent(Intent.ACTION_SENDTO);
    emailAppIntent.setData(Uri.parse("mailto:test@mail.com"));
    emailAppIntent.putExtra(Intent.EXTRA_EMAIL, "");
    emailAppIntent.putExtra(Intent.EXTRA_SUBJECT, "Feedback on "+getContext().getPackageName());
    emailAppIntent.putExtra(Intent.EXTRA_TEXT, mailBody);

    PackageManager packageManager = getActivity().getPackageManager();

    List<ResolveInfo> emailApps = packageManager.queryIntentActivities(emailAppIntent, PackageManager.MATCH_ALL);

    for (ResolveInfo resolveInfo : emailApps) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
        emailAppLauncherIntents.add(launchIntent);
    }

    Intent chooserIntent = Intent.createChooser(new Intent(), "Select email app:");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailAppLauncherIntents.toArray(new Parcelable[emailAppLauncherIntents.size()]));
    startActivity(chooserIntent);
</code>```

答:
Changing the MIME type is the answer

Use

```<code>intent.setType("message/rfc822");
</code>```

Title: Filtering chooser intent

Body:
I want to get emails from users. I am trying to filter the chooser intent but i am stuck at some point.

Chooser intent brings the user's contacts. I just want to show the installed email apps, with 'to' field auto filled of course.

How can I remove user's contacts and show email apps only?

any help would be greatly appreciated.

here is my code so far:

    List<Intent> emailAppLauncherIntents = new ArrayList<>();

    Intent emailAppIntent = new Intent(Intent.ACTION_SENDTO);
    emailAppIntent.setData(Uri.parse("mailto:test@mail.com"));
    emailAppIntent.putExtra(Intent.EXTRA_EMAIL, "");
    emailAppIntent.putExtra(Intent.EXTRA_SUBJECT, "Feedback on "+getContext().getPackageName());
    emailAppIntent.putExtra(Intent.EXTRA_TEXT, mailBody);

    PackageManager packageManager = getActivity().getPackageManager();

    List<ResolveInfo> emailApps = packageManager.queryIntentActivities(emailAppIntent, PackageManager.MATCH_ALL);

    for (ResolveInfo resolveInfo : emailApps) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent launchIntent = packageManager.getLaunchIntentForPackage(packageName);
        emailAppLauncherIntents.add(launchIntent);
    }

    Intent chooserIntent = Intent.createChooser(new Intent(), "Select email app:");
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, emailAppLauncherIntents.toArray(new Parcelable[emailAppLauncherIntents.size()]));
    startActivity(chooserIntent);

Body:
Changing the MIME type is the answer

Use

intent.setType("message/rfc822");


问:
Overriding Java System Library with newer class on Mac
I'm trying to compile and run a Java3D project on my mac and having some trouble. I'm using Eclipse. The program depends on an old version of Java3D, but even after I add the correct Jars in Eclipse it still is looking in the default system location instead.

When running my program in Eclipse, I get this issue:

Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: javax.media.j3d.BranchGroup.pickAllSorted(IILjavax/media/j3d/PickShape;)[Ljavax/media/j3d/PickInfo;
 at com.sun.j3d.utils.pickfast.PickTool.pickAllSorted(PickTool.java:410)

BranchGroup.pickAllSorted does not exist in the Mac Default JRE System Library (JVM 1.6.0), but it does exist in the correct JAVA3D jars that I have included. I've added them to my buildpath, AND they are referenced above the JRE system library in Properties-Java Build Path-Order and Export. This seems like it should be the solution but it doesn't work.

I've been trying for a while and cannot get it to work. One possible lead I had was to try putting the .jars in /Library/Java/Extensions. When I do this, I instead get an OpenGL error and my program doesn't open at all, but its doing something I guess.

Thanks for the help.

答: When launching the program, try using either the -Xbootclasspath or the -Xbootclasspath/a switch to add your jars to the classpath. See the java tool documentation.


问:
Resource ownership in REST API
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

```<code>{
   name: 'My Game',
   sport: 'Football'
   ...
}
</code>```

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.

答:
I think first you have to solve a concept issue related to resource responsability, because a resource that returns game information, shouldn't return security information like "see or not see a button".

So, I would create a specific resource to return security information like this.
In this specific security resource, for the mentioned case above, I wouldn't pass any parameter by the URL and through the authentication hash I would get user id to verify if he is a game owner returning a simple response like true or false to know if that user can see that button.

Obviously, that resource could answer much many security information about other screens and buttons.

A resource like:

```<code>GET /security/buttons/{buttonId}
</code>```

And in the future:

```<code>GET /security/screens/{screenId}
GET /security/functionalities/{functionalityId}
GET /security/actions/{actionId}
.
.
.
</code>```

Title: Resource ownership in REST API

Body:
In the following scenario:

A User can create Games.

A User who creates a game is called Owner.

Games have their own unique id globally.

Other Users can join Games they don't own, these are called Players.

One would send a request to /game/{id} to get the Game data, which should be the same for every client, something like:

{
   name: 'My Game',
   sport: 'Football'
   ...
}

Let's say that we have to show a "Settings" link for the Game owner in the Main Game Screen. This "Settings" link can't be displayed for regular Players.

Both Player and Owner can see the Main Game Screen.

How can I verify the ownership of this resource to show different components to the users?

I think that adding the ownerId to the response would be a liability since one could change the value on the client side, is that right?

Also, adding an isOwner field would make it impossible to cache the response.

Body:
I think first you have to solve a concept issue related to resource responsability, because a resource that returns game information, shouldn't return security information like "see or not see a button".

So, I would create a specific resource to return security information like this.
In this specific security resource, for the mentioned case above, I wouldn't pass any parameter by the URL and through the authentication hash I would get user id to verify if he is a game owner returning a simple response like true or false to know if that user can see that button.

Obviously, that resource could answer much many security information about other screens and buttons.

A resource like:

GET /security/buttons/{buttonId}

And in the future:

GET /security/screens/{screenId}
GET /security/functionalities/{functionalityId}
GET /security/actions/{actionId}
.
.
.


问:
IOError: [Errno 2] No such file or directory: 'Users/myname/PycharmProjects/sensorLogProject/Data/PickUpPhoneAccelerometer1.csv'
I get that error with the following script:

```<code>with open(os.path.join("Users", "myname", "PycharmProjects",
           "sensorLogProject", "Data", f), 'rU') as my_file:
</code>```

Even though when I use PyCharm to get the path, it returns:

```<code>/Users/myname/PycharmProjects/sensorLogProject/Data/PickUpPhoneAccelerometer1.csv
</code>```

Edit: /Data is a Python Package not a directory if that helps

答:
```<code>with open(os.path.join("/Users", "myname", "PycharmProjects",
       "sensorLogProject", "Data", f), 'rU') as my_file:
</code>```

I was missing the first character.

Body:
I get that error with the following script:

with open(os.path.join("Users", "myname", "PycharmProjects",
           "sensorLogProject", "Data", f), 'rU') as my_file:

Even though when I use PyCharm to get the path, it returns:

/Users/myname/PycharmProjects/sensorLogProject/Data/PickUpPhoneAccelerometer1.csv

Edit: /Data is a Python Package not a directory if that helps

Body:
with open(os.path.join("/Users", "myname", "PycharmProjects",
       "sensorLogProject", "Data", f), 'rU') as my_file:

I was missing the first character.


问:
I'm can't quite wrap my head around this code for checking for a perfect square
I'm a novice as may be obvious, in advanced c++ at my school and I was working on home work and was having issues with try to figure out how to decide if an integer is a perfect square or not when I stumbled across this piece of code. </p>

```<code>if (num <= 0 || sqrt(num) != static_cast<int>(sqrt(num)))
      throw "Error: The number is not a perfect square.\n";

    return sqrt(num);
</code>```

<p>If possible  as an exception function I just don't quite understand how the piece after || works. And would just like to know for future reference. </p>

答:
This last part checks if the number is an integer.

sqrt(num) will return a number that might have a decimal, and static_cast<int>(sqrt(num))) will return an integer.

If the number has a decimal,
static_cast<int>(sqrt(num))) will take the decimal out. If the casted value was for example

4.32

the static cast would take out the decimal and return

4

The if statement checks if the square root of the number is the same as the version  with the decimal taken out

If the square root does not equal the square root with the decimal taken out, then it isn't a perfect square

With the number 4.32 as example again

if( sqrt(num) != static_cast<int>(sqrt(num)) )

would be turned into

if( 4.32 != static_cast<int>(4.32))

which would be turned into

if(4.32 != 4)

Body:
I'm a novice as may be obvious, in advanced c++ at my school and I was working on home work and was having issues with try to figure out how to decide if an integer is a perfect square or not when I stumbled across this piece of code.

if (num <= 0 || sqrt(num) != static_cast<int>(sqrt(num)))
      throw "Error: The number is not a perfect square.\n";

    return sqrt(num);

If possible  as an exception function I just don't quite understand how the piece after || works. And would just like to know for future reference.


问:
Find DocumentId through Discovery GUI tool
I want to train my Discovery collection where I have already uploaded over 200 documents. I uploaded these documents through the GUI. Looking through the Discovery documentation, I know that I have will have to make API calls to train my collection since the training API has not been exposed through the GUI yet. As part of the training API calls I need to include a document that looks like this:

```<code>{
  "natural_language_query": "{natural_language_query}",
  "filter": "{filter_definition}"
  "examples": [
    {
      "document_id": "{document_id_1}",
      "cross_reference": "{cross_reference_1}",
      "relevance": 0
    },
    {
      "document_id": "{document_id_2}",
      "cross_reference": "{cross_reference_2}",
      "relevance": 0
    }
  ]
}
</code>```

My question is how should I get the documentIds for the documents that I have already uploaded? Is there a way to find this through the GUI? Or perhaps an API call that will return something like:

```<code>{
  "document_name" = "MyDocument1",
  "documentId" = "the_document_id_for_MyDocument1"
},

...

{
  "document_name" = "MyDocumentN",
  "documentId" = "the_document_id_for_MyDocumentN"
}
</code>```

Or would the only way to get the documentIds would be to create a new collection and upload all of the documents through API calls directly and track the documentIds as I get them back?

答:
Using the GUI, perform the following steps:

Input term(_id) in the "Group query results (Aggregation)"
textbox.

Under "Fields to return", select "Specify" to input
extracted_metadata

Note, that query and filter inputs should remain empty

Body:
I want to train my Discovery collection where I have already uploaded over 200 documents. I uploaded these documents through the GUI. Looking through the Discovery documentation, I know that I have will have to make API calls to train my collection since the training API has not been exposed through the GUI yet. As part of the training API calls I need to include a document that looks like this:

{
  "natural_language_query": "{natural_language_query}",
  "filter": "{filter_definition}"
  "examples": [
    {
      "document_id": "{document_id_1}",
      "cross_reference": "{cross_reference_1}",
      "relevance": 0
    },
    {
      "document_id": "{document_id_2}",
      "cross_reference": "{cross_reference_2}",
      "relevance": 0
    }
  ]
}

My question is how should I get the documentIds for the documents that I have already uploaded? Is there a way to find this through the GUI? Or perhaps an API call that will return something like:

{
  "document_name" = "MyDocument1",
  "documentId" = "the_document_id_for_MyDocument1"
},

...

{
  "document_name" = "MyDocumentN",
  "documentId" = "the_document_id_for_MyDocumentN"
}

Or would the only way to get the documentIds would be to create a new collection and upload all of the documents through API calls directly and track the documentIds as I get them back?


问:
SQL to find why PK canidate has duplicates on unkeyed table
If my title hurts your head... I'm with you. I don't want to get into why this table exists except that it is part of a legacy system, also the system does "record level access"(RLA) and this I know will be an issue for many tables, anyways the RLA is mentioned because adding a column will change the table format and then many very old programs will no longer work...

Apparently adding a PK has been shown not to change the table format. So I've been told that a certain set of keys is guarantied to be unique, well what do you know... it isn't. And now I need to show where they aren't.

All I can think of is:

Get the cross product where the table matches on it's primary key.

Somehow get a count column onto the result set for the number of entries where the PK matches it self.

Filter that result set for values where count id greater than 2.

I'm going to see if I expand the PK sufficiently I'll actually find something unique.

答:
```<code>SELECT * FROM (SELECT ID, COUNT(*) CNT FROM MY_TABLE GROUP BY ID) WHERE CNT > 1
</code>```


问:
Why and how VSCode fresh install thinks it has TypeScript?
Using Windows 10 Enterprise,

After spending a few hours on this and experiment on a few VMs,

Fact #1

When I open a .ts file in vscode, it thinks that it actually has TypeScript 2.3.4 per below screenshot:

Fact#2
However, when I try to run a .ts file in VSCode (control-shift-b) I get this error:

```<code>'tsc' is not recognized as an internal or external command,
</code>```

Fact#3

When I search all my HDD, tsc.cmd only exists as part of Visual Studio 2015 at below location. But it is not part of VSCode

```<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\node_modules\.bin\tsc.cmd
</code>```

Fact#4
The typescript documentation falsely states that

“VS Code ships with a recent stable version of the TypeScript language
  service”

https://code.visualstudio.com/Docs/languages/typescript

Fact#5

Going through some other SO posts:
Does VS Code install TypeScript, and if so: where? I know that I have to manually install TypeScript and deal with the below version conflict warning

"Version mismatch! global tsc (2.1.5) != VS Code's language service
  (2.2.1). Inconsistent compiler errors might occur"

Explained here: https://code.visualstudio.com/Docs/languages/typescript

Question:

Why and how VSCode fresh install thinks it has TypeScript 2.3.4 shown in the above screenshot?

答:
VS Code ships with the TypeScript language service:

VS Code ships with a recent stable version of the TypeScript language service and it may not match the version of TypeScript installed globally on your computer or locally in your workspace. The active version of the TypeScript language service is displayed in the Status Bar when viewing a TypeScript or JavaScript file:

This is the API that allows for intellisense, syntax highlighting, etc.--not the compiler itself.

Body:
Using Windows 10 Enterprise,

After spending a few hours on this and experiment on a few VMs,

Fact #1

When I open a .ts file in vscode, it thinks that it actually has TypeScript 2.3.4 per below screenshot:

Fact#2
However, when I try to run a .ts file in VSCode (control-shift-b) I get this error:

'tsc' is not recognized as an internal or external command,

Fact#3

When I search all my HDD, tsc.cmd only exists as part of Visual Studio 2015 at below location. But it is not part of VSCode

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Web\External\node_modules\.bin\tsc.cmd

Fact#4
The typescript documentation falsely states that

“VS Code ships with a recent stable version of the TypeScript language
  service”

https://code.visualstudio.com/Docs/languages/typescript

Fact#5

Going through some other SO posts:
Does VS Code install TypeScript, and if so: where? I know that I have to manually install TypeScript and deal with the below version conflict warning

"Version mismatch! global tsc (2.1.5) != VS Code's language service
  (2.2.1). Inconsistent compiler errors might occur"

Explained here: https://code.visualstudio.com/Docs/languages/typescript

Question:

Why and how VSCode fresh install thinks it has TypeScript 2.3.4 shown in the above screenshot?


答:
The code below should work. The idea is that you want to take a list, a, and create a dictionary with the key set to first element in each sublist of a. The value associated with that list is a list containing the second element in that sublist of a. Then we loop through the second list b and do the same. Finally, we iterate over the dictionary that we created, D, and turn that into a list.

```<code>a = [[1,2], [3,4], [5,6]]
b = [[1,20],[3,40],[5, 50]]
D = {}
for i in a:
    D[i[0]] = [i[1]]

for i in b:
    D[i[0]].append(i[1])

finalList = []
for d in D:
    finalList.append([d, D[d][0], D[d][1]])

print(finalList)
>>> [[1, 2, 10], [3, 4, 40], [5, 6, 50]]
</code>```

Note, this program assumes that the two corresponding sublists are guaranteed to have equal first elements. If this is not the case or the two lists a and b are not equal, you'll need an if statement on line 8 to check if the key value i[0] is in the list.

Title: Merge two multidimensional lists into one list in Python

Body:
I have two lists:

a_list =
[['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......]

b_list =
[['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......]

I need to merge a_list with b_list so it becomes:

combined_list =
[['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......]

How would I achieve this?

Body:
The code below should work. The idea is that you want to take a list, a, and create a dictionary with the key set to first element in each sublist of a. The value associated with that list is a list containing the second element in that sublist of a. Then we loop through the second list b and do the same. Finally, we iterate over the dictionary that we created, D, and turn that into a list.

a = [[1,2], [3,4], [5,6]]
b = [[1,20],[3,40],[5, 50]]
D = {}
for i in a:
    D[i[0]] = [i[1]]

for i in b:
    D[i[0]].append(i[1])

finalList = []
for d in D:
    finalList.append([d, D[d][0], D[d][1]])

print(finalList)
>>> [[1, 2, 10], [3, 4, 40], [5, 6, 50]]

Note, this program assumes that the two corresponding sublists are guaranteed to have equal first elements. If this is not the case or the two lists a and b are not equal, you'll need an if statement on line 8 to check if the key value i[0] is in the list.


问:
No matching function to call objc_getassociatedobject in ios
I'm trying to develop an IOS application works with objC++. I am using this GUI framework for designing my GUI. But, the problem is that XCode does not seem to recognise its own library objc/runtime.h or objc_getassociatedobject methods. It is an Objective-C method and it is rather surprising that i get this error. XCode gives error No matching function to call objc_getassociatedobject even though i #import <objc/runtime.h>.

答: objc_getAssociatedObject()'s second parameter has type const void *, whereas you are trying to pass a NSString *. C++ is pretty strict about implicit type conversions and it is not happy about such a conversion.


问:
perl -> Parsing json string of hash
so I took a curl output of a json formatted output and assigned it to a variable.

```<code>my $catcherJSON = decode_json $response->content;
print Dumper $catcherJSON;
</code>```

When I view the $catcherJSON, I want to see an array of hashes, but I just get a massive string of json.

```<code>$VAR1 = [
      {
        'priority' => 5,
        'ingestPath' => '/vg/24CHVOD_en',
...
...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>
...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>

...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>

 ...
 ...},
      {
        'priority' => 5,
        'ingestPath' =>
  ....
  ...
      }
    ];
</code>```

The hashes repeat (There are about 300 unique results) and I'm trying to figure out in perl how I can split this 1 string into my array of hashes simply.

Any way that I can easily convert this into a proper array of hashes so I can iterate through it?

Thanks in advance.

答:
Any way that I can easily convert this into a proper array of hashes so I can iterate through it?

You've already done it.

so I took a curl output of a json formatted output and assigned it to a variable.

```<code>my $catcherJSON = decode_json $response->content;`
</code>```

That's not correct.

You took the JSON formatted string from $response->content, decoded the JSON into a Perl data structure, and stored it in $catcherJSON.

When I view the $catcherJSON, I want to see an array of hashes, but I just get a massive string of json.

$catcherJSON is not a string of JSON. $catcherJSON is a Perl array of hashes. You've already decoded the JSON into a Perl data structure with decode_json. It's been formatted by Dumper() back into Perl code so you can read it.

Your code is fine, you have what you want. For example, $catcherJSON->[0]{ingestPath} will be '/vg/24CHVOD_en'.

Title: perl -> Parsing json string of hash

Body:
so I took a curl output of a json formatted output and assigned it to a variable.

my $catcherJSON = decode_json $response->content;
print Dumper $catcherJSON;

When I view the $catcherJSON, I want to see an array of hashes, but I just get a massive string of json.

$VAR1 = [
      {
        'priority' => 5,
        'ingestPath' => '/vg/24CHVOD_en',
...
...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>
...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>

...
...
      },
      {
        'priority' => 5,
        'ingestPath' =>

 ...
 ...},
      {
        'priority' => 5,
        'ingestPath' =>
  ....
  ...
      }
    ];

The hashes repeat (There are about 300 unique results) and I'm trying to figure out in perl how I can split this 1 string into my array of hashes simply.

Any way that I can easily convert this into a proper array of hashes so I can iterate through it?

Thanks in advance.

Body:
Any way that I can easily convert this into a proper array of hashes so I can iterate through it?

You've already done it.

so I took a curl output of a json formatted output and assigned it to a variable.

my $catcherJSON = decode_json $response->content;`

That's not correct.

You took the JSON formatted string from $response->content, decoded the JSON into a Perl data structure, and stored it in $catcherJSON.

When I view the $catcherJSON, I want to see an array of hashes, but I just get a massive string of json.

$catcherJSON is not a string of JSON. $catcherJSON is a Perl array of hashes. You've already decoded the JSON into a Perl data structure with decode_json. It's been formatted by Dumper() back into Perl code so you can read it.

Your code is fine, you have what you want. For example, $catcherJSON->[0]{ingestPath} will be '/vg/24CHVOD_en'.


问:
[object Object]undefined on input form (jquery+json+php)
can someone help me displaying that JSON array

{"contenusModeleCarte"{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte0":"pommes au four
  "},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte1":"salade de
  fruits"},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte2":"bananes"}]}

into form inputs.

When I try to do it via this code

```<code>$.each(dataModeleCarte.contenusModeleCarte, function(i,contenusModeleCarte){
  if(contenusModeleCarte.dessertCarte+i == null){
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val('');
  }else{
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val(contenusModeleCarte.dessertCarte);
  }
});
</code>```

I only get as a result :

[object Object]undefined

any help would be greatly appreciated.

Thx

答:
Your "dessertCarte" in the JSON has the numbers 0, 1, 2, ... after it, so it can't find a contenusModeleCarte.dessertCarte

You need to append the index i after "dessertCarte":

```<code> .val(contenusModeleCarte["dessertCarte" + i]);
</code>```

Body:
can someone help me displaying that JSON array

{"contenusModeleCarte"{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte0":"pommes au four
  "},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte1":"salade de
  fruits"},{"idmodele":"65","modeleName":"","typerepas":null,"commentairesModeleCarte":"premier
  commentaire pour le premier modele de
  carte","dessertCarte2":"bananes"}]}

into form inputs.

When I try to do it via this code

$.each(dataModeleCarte.contenusModeleCarte, function(i,contenusModeleCarte){
  if(contenusModeleCarte.dessertCarte+i == null){
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val('');
  }else{
     $("#edit-field-dessert-carte-"+ i +"-value-field-dessert-value").val(contenusModeleCarte.dessertCarte);
  }
});

I only get as a result :

[object Object]undefined

any help would be greatly appreciated.

Thx

Body:
Your "dessertCarte" in the JSON has the numbers 0, 1, 2, ... after it, so it can't find a contenusModeleCarte.dessertCarte

You need to append the index i after "dessertCarte":

 .val(contenusModeleCarte["dessertCarte" + i]);


问:
Azure Windows Portal: Unable to Save Image in order to create VHD
I am trying to publish my product on Azure marketplaces.

I am using windows 2012 R2 Datacenter that I use to create a VM from portal.azure.com. I followed steps of running a sysprep, generalizing it and then creating containers.

After that when we run save-azurermvmimage to capture image, I get the capture action is only supported on a virtual machine with blob based disks. please use the image resource apis to create an image from a managed virtual machine
So I am not able to get the image url in container. Is there anything I am doing wrong?
Please guide!

答:
Managed disk is different from unmanaged disk. We can use Powershell to create a managed image, but we can't find this new image in our storage account, managed disk manage by Azure, we can't manage it directly.

To create a managed image of a VM, we can follow those steps:

run sysprep to generalize the windows VM.(This process deletes the original virtual machine after it's captured.Prior to capturing an image of an Azure virtual machine, it is recommended the target virtual machine be backed up. )

```<code>$vmName = "myVM"
$rgName = "myResourceGroup"
$location = "EastUS"
$imageName = "myImage"
Stop-AzureRmVM -ResourceGroupName $rgName -Name $vmName -Force
Set-AzureRmVm -ResourceGroupName $rgName -Name $vmName -Generalized
$vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
$image = New-AzureRmImageConfig -Location $location -SourceVirtualMachineId $vm.ID
New-AzureRmImage -Image $image -ImageName $imageName -ResourceGroupName $rgName
</code>```

After it completed, we can find this image here:

More information about create a managed image, please refer to this link.

By the way, we should use Azure PowerShell 3.7.0 or later.

```<code>PS C:\Users> Get-Module -ListAvailable -Name Azure -Refresh

    Directory: C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.7.0      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnec...
</code>```

Body:
Managed disk is different from unmanaged disk. We can use Powershell to create a managed image, but we can't find this new image in our storage account, managed disk manage by Azure, we can't manage it directly.

To create a managed image of a VM, we can follow those steps:

run sysprep to generalize the windows VM.(This process deletes the original virtual machine after it's captured.Prior to capturing an image of an Azure virtual machine, it is recommended the target virtual machine be backed up. )

$vmName = "myVM"
$rgName = "myResourceGroup"
$location = "EastUS"
$imageName = "myImage"
Stop-AzureRmVM -ResourceGroupName $rgName -Name $vmName -Force
Set-AzureRmVm -ResourceGroupName $rgName -Name $vmName -Generalized
$vm = Get-AzureRmVM -Name $vmName -ResourceGroupName $rgName
$image = New-AzureRmImageConfig -Location $location -SourceVirtualMachineId $vm.ID
New-AzureRmImage -Image $image -ImageName $imageName -ResourceGroupName $rgName

After it completed, we can find this image here:

More information about create a managed image, please refer to this link.

By the way, we should use Azure PowerShell 3.7.0 or later.

PS C:\Users> Get-Module -ListAvailable -Name Azure -Refresh

    Directory: C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.7.0      Azure                               {Get-AzureAutomationCertificate, Get-AzureAutomationConnec...


问:
Why am I getting a TokenMismatchException with Laravel and JQuery Sortable?
Update
I've changed the question slightly based on answers I've been given

I'm trying to save an order of rows, after the user manipulates the table via JQuery's Sortable Library.

```<code><div class="nametag-layout">
        <table class="table table-striped pagin-table table-bordered">
            <thead>
                <tr>
                    <td>Duration</td>
                    <td>Intent</td>
                    <td>Module</td>
                    <td>Outputs</td>
                    <td>Inputs</td>
                    <td>Logistics</td>
                </tr>
            </thead>
            <tbody>
            @foreach($mods as $key => $value)
                <tr class="table-tr draggable" data-id="{!!$value->id!!}">
                    <td>{{ $value->mod_duration }}</td>
                    <td>{{ $value->mod_intent }}</td>
                    <td>{{ $value->mod_module }}</td>
                    <td>{{ $value->mod_output }}</td>
                    <td>{{ $value->mod_input }}</td>
                    <td>{{ $value->mod_logistics }}</td>
                    <td>
                        <a class="btn btn-small btn-info" style="margin:auto; display:block;" href="{{ URL::to('mods/' . $value->id . '/edit') }}">Edit</a>
                    </td>
                </tr>
            @endforeach
            </tbody>
        </table>
    </div>
</code>```

After the table is manipulated, a js function takes the new order of the rows and passes it via a call.

```<code>$( "tbody" ).sortable({
                    stop: function (event, ui) {
                        var ids = new Array();
                        $('tr', this).each(function () {
                            ids.push($(this).data('id'));
                        });
                        $.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
                    }
            });
</code>```

And a sort function in my controllers takes those values and parses them, then saves it to the DB so the new order is saved.

```<code>public function sort()
{
        $ids = request()->get('ids');
        if ($ids != null) {
            foreach ($ids as $i => $id) {
                $value = Mod::find($id);
                $value->sort = $i;
                $value->save();
            }
        }
}
</code>```

Every time I refresh the page, it doesn't save the order which I've moved the rows into. Checking chrome inspector and checking the XHR filter shows that every time I move a row, the sort function fires off, but every time it does fire off, a 'TokenMismatchException in VerifyCsrfToken' error occurs. I'm assuming either the js function isn't actually passing the values across to the controller, or I've messed up the call.

I've also added '/sort' to the $except parameter in 'VerifyCsrfToken.php', to temporarily fix the csrf issue I'm getting.

My route looks like this:

Route::get('/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

When I've done all this, the ajax call is sending the data to the controller, after checking using the XHR filter on chrome inspector, but whenever the rows are refreshed, it goes back to the original order of the rows instead of the manipulated order.

Basically, what am I doing wrong?

Things I've tried:

I've tried changing my js function to match the controller (post/get):

```<code>$.post(window.location.href.split('?')[0] + "/sort", {ids: ids});

public function sort()
{
        $ids = request()->post('ids');
...
</code>```

Changing both to the 'get' parameter just causes it to call another function I've written. Changing both to the 'post' parameter just returns the 'TokenMismatchException' error again.

I've tried another option, where I've changed the js function to 'get':

```<code>$.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
</code>```

and the function to get as well:

```<code>$ids = request()->get('ids');
</code>```

and removed the function that conflicted with the get parameter. Then I've written a show function which handles to redirect to '/sort'.

```<code>public function show()
{
    return redirect('/sort');
}
</code>```

Going back to the chrome inspector and checking the XHR filter shows that it is passing the values across, but the sort function returns a 'NotFoundHttpException in RouteCollection.php line 179' error.

For reference, my route looks like this:
  Route::get('strawdog/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

答:
Inside your VerifyCsrfToken.php middleware

Do this (add any route you want to crsf exception)

```<code>class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/sort'  // add the correct route here
    ];
}
</code>```

Body:
Update
I've changed the question slightly based on answers I've been given

I'm trying to save an order of rows, after the user manipulates the table via JQuery's Sortable Library.

                    Duration
                    Intent
                    Module
                    Outputs
                    Inputs
                    Logistics

            @foreach($mods as $key => $value)

id!!}">
                    {{ $value->mod_duration }}
                    {{ $value->mod_intent }}
                    {{ $value->mod_module }}
                    {{ $value->mod_output }}
                    {{ $value->mod_input }}
                    {{ $value->mod_logistics }}

                        id . '/edit') }}">Edit

            @endforeach

After the table is manipulated, a js function takes the new order of the rows and passes it via a call.

$( "tbody" ).sortable({
                    stop: function (event, ui) {
                        var ids = new Array();
                        $('tr', this).each(function () {
                            ids.push($(this).data('id'));
                        });
                        $.get(window.location.href.split('?')[0] + "/sort", {ids: ids});
                    }
            });

And a sort function in my controllers takes those values and parses them, then saves it to the DB so the new order is saved.

public function sort()
{
        $ids = request()->get('ids');
        if ($ids != null) {
            foreach ($ids as $i => $id) {
                $value = Mod::find($id);
                $value->sort = $i;
                $value->save();
            }
        }
}

Every time I refresh the page, it doesn't save the order which I've moved the rows into. Checking chrome inspector and checking the XHR filter shows that every time I move a row, the sort function fires off, but every time it does fire off, a 'TokenMismatchException in VerifyCsrfToken' error occurs. I'm assuming either the js function isn't actually passing the values across to the controller, or I've messed up the call.

I've also added '/sort' to the $except parameter in 'VerifyCsrfToken.php', to temporarily fix the csrf issue I'm getting.

My route looks like this:

Route::get('/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

When I've done all this, the ajax call is sending the data to the controller, after checking using the XHR filter on chrome inspector, but whenever the rows are refreshed, it goes back to the original order of the rows instead of the manipulated order.

Basically, what am I doing wrong?

Things I've tried:

I've tried changing my js function to match the controller (post/get):

$.post(window.location.href.split('?')[0] + "/sort", {ids: ids});

public function sort()
{
        $ids = request()->post('ids');
...

Changing both to the 'get' parameter just causes it to call another function I've written. Changing both to the 'post' parameter just returns the 'TokenMismatchException' error again.

I've tried another option, where I've changed the js function to 'get':

$.get(window.location.href.split('?')[0] + "/sort", {ids: ids});

and the function to get as well:

$ids = request()->get('ids');

and removed the function that conflicted with the get parameter. Then I've written a show function which handles to redirect to '/sort'.

public function show()
{
    return redirect('/sort');
}

Going back to the chrome inspector and checking the XHR filter shows that it is passing the values across, but the sort function returns a 'NotFoundHttpException in RouteCollection.php line 179' error.

For reference, my route looks like this:
  Route::get('strawdog/sort',array('as'=>'strawdog.sort','uses'=>'StrawdogController@sort'));

Body:
Inside your VerifyCsrfToken.php middleware

Do this (add any route you want to crsf exception)

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/sort'  // add the correct route here
    ];
}


问:
Google Instant Android Apps - Can I use my existing Hosted Payment capture provider to capture payment data?
We have an Android fully native app that captures the credit card and payment info using a reputable company's hosted tokenization solution.  (via Embedded Web View).  Credit card number related info is not stored or transmitted to our servers at any point.

We are evaluating whether we can jump onto Google's Instant Apps, and I found a piece in their UX-Best-Practices that says, you MUST go through either Google Play In-app Billing, OR Google Payment API

From their Docs: https://developer.android.com/topic/instant-apps/ux-best-practices.html#take_the_friction_out_of_payments

"You must use the Google Payment API for purchases within your instant app if you do not already have the user's payment information on file. Any new or replacement payment information for a given user must be collected using the Google Payment API.
If you implement the Google Payment API in your instant app, you can also offer purely offline payments, like cash on delivery, or store gift cards in your instant app."

AND

"As stated previously, you must handle payments within the instant app using the Google Payment API or Google Play In-app Billing."

They don't make any distinction about In-App purchases, or purchases for things that are delivered physically or electronically OUTSIDE of the app.   We are the latter:  We deliver digital goods outside of the app, to be claimed and redeemed later on by someone else.

So according to all this, Are we eligible to migrate to Instant Apps using our existing payment system?

答:
Yes, it is a policy requirement that all Instant App payments should go through either Google Play In-App Billing or the Google Payment API. The former is for purely digital goods (and attracts the standard 30% cut), the latter for physical goods or services.

Note that the Google Payment API is not the same as Android Pay. You can read more about the newer Payment API from the Google I/O 2017 session, this blog post and sign up for early access here.

As to if this will work with your current app / payments system, that's hard to say. The Google Payment API is a way to let users easily store and retrieve payment methods from their Google account, it does not actually process the payment. To process the payment you will still need to pass the tokenized credit card info that is received from the Payment API to a supported payment processor. At time of writing the supported processors are Braintree, Stripe and Vantiv with more coming soon.

If your current payment flow is not very flexible then it may not be possible to integrate this payment flow into your Instant App.


问:
How to get data to Dropdownlist from database in html view
I am creating an web page in which have a Dropdownlist. I have to retrieve data for the drop_down_list from the database. Is there any way to get data from the database to the html view my html code:

<select name="drop down"><option value="1">@test.list[i]</option></select>

I got the database value to the list variable but I don't know how to pass the data to the html view. Please help me in this issue.Thanks

答:
It is just a simple two step process:

Step1 :Action method code

```<code>public ActionResult Index()
{
  ViewBag.users = db.users.ToList();
}
</code>```

Step2: cshtml code

```<code>@Html.DropDownListFor(model => model.someId, new SelectList(ViewBag.users, "userId", "userName"), "Select users")
</code>```

Note: with this, you can bind n number of data from the database to dropdownlist

Hope it was useful

Thanks

Karthik

Body:
It is just a simple two step process:

Step1 :Action method code

public ActionResult Index()
{
  ViewBag.users = db.users.ToList();
}

Step2: cshtml code

@Html.DropDownListFor(model => model.someId, new SelectList(ViewBag.users, "userId", "userName"), "Select users")

Note: with this, you can bind n number of data from the database to dropdownlist

Hope it was useful

Thanks

Karthik


问:
Finding errors of Reactive Form subgroup
I cannot find a way to retrieve errors of subgroup of my reactive form.

private setupFormValidation() {
    this.progressForm = new FormGroup({
      'preImplementationGroup': new FormGroup({
        'otherProgramName': new FormControl(null, [Validators.required]),
        'programType': new FormControl(null, [Validators.required]),
        ...
      }),
      'testingReviewGroup': new FormGroup({
        ...
      })
    });```

What would be the best way to find all errors only for 'preImplementationGroup' Form Group?

答:
you can use FormBuilder to build your formgroup :</p>

```<code>import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms";
progressForm : FormGroup;
constructor(fb: FormBuilder) {}
private setupFormValidation() {
    this.progressForm = fb.group({
      'preImplementationGroup' :  fb.group({
        otherProgramName: [null, [Validators.required]],
        programType: [null, [Validators.required]]
      }),
      'testingReviewGroup' : fb.group({
        organisme: [null,[Validators.required]],
      })
});
}
</code>```

Body:
I cannot find a way to retrieve errors of subgroup of my reactive form.

private setupFormValidation() {
    this.progressForm = new FormGroup({
      'preImplementationGroup': new FormGroup({
        'otherProgramName': new FormControl(null, [Validators.required]),
        'programType': new FormControl(null, [Validators.required]),
        ...
      }),
      'testingReviewGroup': new FormGroup({
        ...
      })
    });

What would be the best way to find all errors only for 'preImplementationGroup' Form Group?

Body:
you can use FormBuilder to build your formgroup :

import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms";
progressForm : FormGroup;
constructor(fb: FormBuilder) {}
private setupFormValidation() {
    this.progressForm = fb.group({
      'preImplementationGroup' :  fb.group({
        otherProgramName: [null, [Validators.required]],
        programType: [null, [Validators.required]]
      }),
      'testingReviewGroup' : fb.group({
        organisme: [null,[Validators.required]],
      })
});
}


问:
downloading files with goroutines?
I'm new to Go and I'm learning how to work with goroutines.

I have a function that downloads images:

```<code>func imageDownloader(uri string, filename string) {
    fmt.Println("starting download for ", uri)

    outFile, err := os.Create(filename)
    defer outFile.Close()
    if err != nil {
        os.Exit(1)
    }

    client := &http.Client{}

    req, err := http.NewRequest("GET", uri, nil)

    resp, err := client.Do(req)
    defer resp.Body.Close()

    if err != nil {
        panic(err)
    }

    header := resp.ContentLength
    bar := pb.New(int(header))
    rd := bar.NewProxyReader(resp.Body)
    // and copy from reader
    io.Copy(outFile, rd)
}
</code>```

When I call by itself as part of another function, it downloads images completely and there is no truncated data.

However, when I try to modify it to make it a goroutine, images are often truncated or zero length files.

```<code>func imageDownloader(uri string, filename string, wg *sync.WaitGroup) {
    ...
    io.Copy(outFile, rd)
    wg.Done()
}

func main() {
var wg sync.WaitGroup
wg.Add(1)
go imageDownloader(url, file, &wg)
wg.Wait()
}
</code>```

Am I using WaitGroups incorrectly? What could cause this and how can I fix it?

Update:

Solved it. I had placed the wg.add() function outside of a loop. :(

答:
One change I would make in your example is leverage defer when you are Done. I think this defer ws.Done() should be the first statement in your function.

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So your example could be solved this way:

```<code>func imageDownloader(uri string, filename string) {
    ...
    io.Copy(outFile, rd)
}

func main() {
    functions := []func(){}
    list := make([]Object, 5)
    for _, object := range list {
        function := func(obj Object){
            imageDownloader(object.uri, object.filename)
        }(object)
        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Done")
}
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Title: downloading files with goroutines?

Body:
I'm new to Go and I'm learning how to work with goroutines.

I have a function that downloads images:

func imageDownloader(uri string, filename string) {
    fmt.Println("starting download for ", uri)

    outFile, err := os.Create(filename)
    defer outFile.Close()
    if err != nil {
        os.Exit(1)
    }

    client := &http.Client{}

    req, err := http.NewRequest("GET", uri, nil)

    resp, err := client.Do(req)
    defer resp.Body.Close()

    if err != nil {
        panic(err)
    }

    header := resp.ContentLength
    bar := pb.New(int(header))
    rd := bar.NewProxyReader(resp.Body)
    // and copy from reader
    io.Copy(outFile, rd)
}

When I call by itself as part of another function, it downloads images completely and there is no truncated data.

However, when I try to modify it to make it a goroutine, images are often truncated or zero length files.

func imageDownloader(uri string, filename string, wg *sync.WaitGroup) {
    ...
    io.Copy(outFile, rd)
    wg.Done()
}

func main() {
var wg sync.WaitGroup
wg.Add(1)
go imageDownloader(url, file, &wg)
wg.Wait()
}

Am I using WaitGroups incorrectly? What could cause this and how can I fix it?

Update:

Solved it. I had placed the wg.add() function outside of a loop. :(

Body:
One change I would make in your example is leverage defer when you are Done. I think this defer ws.Done() should be the first statement in your function.

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So your example could be solved this way:

func imageDownloader(uri string, filename string) {
    ...
    io.Copy(outFile, rd)
}

func main() {
    functions := []func(){}
    list := make([]Object, 5)
    for _, object := range list {
        function := func(obj Object){
            imageDownloader(object.uri, object.filename)
        }(object)
        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Done")
}

If you would like to use it, you can find it here https://github.com/shomali11/util


答:
```<code>select col1, ... from tab group by col1, ... having count(*)>1;
</code>```

Title: SQL to find why PK canidate has duplicates on unkeyed table

Body:
If my title hurts your head... I'm with you. I don't want to get into why this table exists except that it is part of a legacy system, also the system does "record level access"(RLA) and this I know will be an issue for many tables, anyways the RLA is mentioned because adding a column will change the table format and then many very old programs will no longer work...

Apparently adding a PK has been shown not to change the table format. So I've been told that a certain set of keys is guarantied to be unique, well what do you know... it isn't. And now I need to show where they aren't.

All I can think of is:

Get the cross product where the table matches on it's primary key.

Somehow get a count column onto the result set for the number of entries where the PK matches it self.

Filter that result set for values where count id greater than 2.

I'm going to see if I expand the PK sufficiently I'll actually find something unique.


问:
Jquery toggle selected items from multiple selectable lists (except the current selection) on selecting any of the items from either of the lists
I am attempting to use two selectable lists with the same selectable class, I want to toggle all the items irrespective of the parent list when a selection is made.

Currently when I select an item, only the selections from the same list get toggled/unselected, but the selected item from the other list remains selected.

Is there any way to have these as two separate lists but behave as the same one, for this specific function?

Any help would be appreciated. Thank You.

$( ".selectable" ).selectable();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<style>
    div {border:1px solid black;}
    .selectable .ui-selecting { background: #FECA40; }
    .selectable .ui-selected { background: #F39814; color: white; }
    .selectable { list-style-type: none; margin: 0; width: 60%; }
    .selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>

    <div id="div1">
        <h4>List 1</h4>
        <ul class="selectable">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
            <li>Item 5</li>
            <li>Item 6</li>
            <li>Item 7</li>
        </ul>
    </div>

    <div id="div2">
        <h4>List 2</h4>
        <ul class="selectable">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
            <li>Item 5</li>
            <li>Item 6</li>
            <li>Item 7</li>
        </ul>
    </div>

    </code>```

答:
I suppose what I was trying to achieve here is what is defined under a different widget, you would call menu.

Changing the script to:

```<code>$(".selectable").menu();
</code>```

gave the desired result.

Body:
I am attempting to use two selectable lists with the same selectable class, I want to toggle all the items irrespective of the parent list when a selection is made.

Currently when I select an item, only the selections from the same list get toggled/unselected, but the selected item from the other list remains selected.

Is there any way to have these as two separate lists but behave as the same one, for this specific function?

Any help would be appreciated. Thank You.

$( ".selectable" ).selectable();

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

List 1

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

List 2

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Body:
I suppose what I was trying to achieve here is what is defined under a different widget, you would call menu.

Changing the script to:

$(".selectable").menu();

gave the desired result.


Body:
I have two lists:

a_list =
[['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21].......]

b_list =
[['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79].......]

I need to merge a_list with b_list so it becomes:

combined_list =
[['2017-06-03 23:01:49', 0, 100,01], ['2017-06-03 23:02:49', 712.32, 50.01], ['2017-06-03 23:03:49', 501.21, 521.79].......]

How would I achieve this?

Body:
Try with this, merge two list, then use defaultdict to generate new dictioanry, find same key, append the value to super_dict, then convert the dictionary to list format:

import collections
a_list = [['2017-06-03 23:01:49', 0], ['2017-06-03 23:02:49', 712.32], ['2017-06-03 23:03:49', 501.21]]
b_list = [['2017-06-03 23:01:49', 100.01], ['2017-06-03 23:02:49', 50.01], ['2017-06-03 23:03:49', 521.79]]
super_dict = collections.defaultdict(list)

for e in a_list+b_list:
    super_dict[e[0]].append(e[1])

dictlist=list()
for key, value in super_dict.iteritems():
    dictlist.append([key]+value)
dictlist

Output:

[['2017-06-03 23:02:49', 712.32, 50.01],
 ['2017-06-03 23:03:49', 501.21, 521.79],
 ['2017-06-03 23:01:49', 0, 100.01]]


问:
Angular routing and controller not working
New to Angular and cannot for the life of me figure out why routing is not working for me. It worked for a while, and then promptly stopped for some reason.

Additionally, it doesn't seem like my controller is working either, since when I copy the form HTML into the index.html file and try to upload a file, it doesn't seem to be running the uploadFile() function.

Here's my code:

js/app.js

```<code>angular.module('packager', ['ngRoute', 'MainCtrl', 'appRoutes', 'ngFileUpload'])
</code>```

js/appRoutes.js

```<code> angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider
    .when('/', {
        templateUrl: './views/home.html',
        controller: 'MainController'
    })
    .when('/package', {
        templateUrl: './views/package.html',
        controller: 'MainController'
    });

}]);
</code>```

controllers/MainCtrl.js

```<code> angular.module('MainCtrl', []).controller('MainController', [$scope, $location, Upload, function($scope, $location, Upload) {
    $scope.upload = {};
    $scope.uploads = [];

    $scope.uploadFile = function() {
        Upload.upload({
        url: '/upload'
        method: 'post'
        data: $scope.upload
    }).then(function (response) {
        console.log($scope.upload)

        $scope.id = $scope.upload.id
        $scope.uploads.push(response.data);
        $scope.upload = {};

        $location.path('/package')
    }
}]);
</code>```

index.html

```<code><html>
<head>
    <base href="/">
    <title>Packager</title>

    <script src="libs/angular/angular.min.js"></script>
    <script src="libs/angular-route/angular-route.min.js"></script>
    <script src="libs/ng-file-upload/ng-file-upload.min.js"></script>

    <script src="js/app.js"></script>
    <script src="js/controllers/MainCtrl.js"></script>
    <script src="js/appRoutes.js"></script>
</head>

<body ng-app="packager" ng-controller="MainController">
    <div class="container">
        <div ng-view> </div>
    </div>
</body>
</html>
</code>```

views/home.html (one of two forms)

```<code><form ng-submit="uploadFile()">
    <input type="file" name="file" id="file" ngf-select required ng-model="upload.file"> <br>
    <input type="submit" value="Upload">
</form>
</code>```

答:
Fixed it. There were two syntax errors:

Forgot the commas in the upload object

```<code>Upload.upload({
    url: '/upload',
    method: 'post',
    data: $scope.upload
})
</code>```

And forgot to put the injections in strings:

"$scope", "$location", "Upload"

Body:
New to Angular and cannot for the life of me figure out why routing is not working for me. It worked for a while, and then promptly stopped for some reason.

Additionally, it doesn't seem like my controller is working either, since when I copy the form HTML into the index.html file and try to upload a file, it doesn't seem to be running the uploadFile() function.

Here's my code:

js/app.js

angular.module('packager', ['ngRoute', 'MainCtrl', 'appRoutes', 'ngFileUpload'])

js/appRoutes.js

 angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);

    $routeProvider
    .when('/', {
        templateUrl: './views/home.html',
        controller: 'MainController'
    })
    .when('/package', {
        templateUrl: './views/package.html',
        controller: 'MainController'
    });

}]);

controllers/MainCtrl.js

 angular.module('MainCtrl', []).controller('MainController', [$scope, $location, Upload, function($scope, $location, Upload) {
    $scope.upload = {};
    $scope.uploads = [];

    $scope.uploadFile = function() {
        Upload.upload({
        url: '/upload'
        method: 'post'
        data: $scope.upload
    }).then(function (response) {
        console.log($scope.upload)

        $scope.id = $scope.upload.id
        $scope.uploads.push(response.data);
        $scope.upload = {};

        $location.path('/package')
    }
}]);

index.html

    <base href="/">
    <title>Packager</title>

views/home.html (one of two forms)

<form ng-submit="uploadFile()">
    <input type="file" name="file" id="file" ngf-select required ng-model="upload.file">

    <input type="submit" value="Upload">
</form>

Body:
Fixed it. There were two syntax errors:

Forgot the commas in the upload object

Upload.upload({
    url: '/upload',
    method: 'post',
    data: $scope.upload
})

And forgot to put the injections in strings:

"$scope", "$location", "Upload"


问:
Test if a variable is a list or tuple
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection)

Is isinstance() as evil as suggested here? http://www.canonical.org/~kragen/isinstance/

Update: the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I'm exploring with a recursive algorithm and I need to know when I've hit the "leaf" nodes.

答:
Has to be more complex test if you really want to handle just about anything as function argument.

```<code>type(a) != type('') and hasattr(a, "__iter__")
</code>```

Although, usually it's enough to just spell out that a function expects iterable  and then check only type(a) != type('').

Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.

ContentLicense: CC BY-SA 4.0

Title: Test if a variable is a list or tuple

Body:
Has to be more complex test if you really want to handle just about anything as function argument.

type(a) != type('') and hasattr(a, "__iter__")

Although, usually it's enough to just spell out that a function expects iterable  and then check only type(a) != type('').

Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.


问:
Performing SQL Injection (Interactive exercise)
I am trying to solve an interactive exercise from my university. There is a field given for the username and one for the password. I have to login with my student ID (which of course I know but I dont want to reveal it here) without knowing the password. After trying some simple stuff I got the error message below. I guess this should help me, but I am not sure. Perhaps someone can give me a hint?

答:
It looks like you're on the right track with your ' OR 1=1, but then you have a syntax error because the string in the original query is closed again after you have already closed it. If you end your injection with a comment ' OR 1=1 -- that will tell the server to ignore the rest of the statement.

Edit:
I'm not sure why the comment approach didn't work, but even if you use the other mentioned technique of re-opening the string, I see now that still isn't enough - the precedence of the AND is higher than the OR, so you will get all rows instead of just the one with your username.
You could try instead

```<code>' OR name='myId
</code>```

to produce

```<code>WHERE name='myId' AND password='' OR name='myId'
</code>```

so it will match any row that has the correct username and password, or any row that just has the correct username.

Body:
It looks like you're on the right track with your ' OR 1=1, but then you have a syntax error because the string in the original query is closed again after you have already closed it. If you end your injection with a comment ' OR 1=1 -- that will tell the server to ignore the rest of the statement.

Edit:
I'm not sure why the comment approach didn't work, but even if you use the other mentioned technique of re-opening the string, I see now that still isn't enough - the precedence of the AND is higher than the OR, so you will get all rows instead of just the one with your username.
You could try instead

' OR name='myId

to produce

WHERE name='myId' AND password='' OR name='myId'

so it will match any row that has the correct username and password, or any row that just has the correct username.


问:
Android Embeddable Webserver
I am trying to make an embeddable webserver for android, to download and upload files, more functionality will be added later.

So far I have implemented nanoHTTPD to allow navigating the directories, and downloading files.

The problem is nanoHTTPD does not have any form of authentication, or SSL
I have tried looking into implementing I-jetty,tjws,simple but cannot find any examples to work off.

Basically i am looking for an embeddable webserver than can do authentication and SSL, as well as navigate directories.

Is there a library with examples and documentation i can use? If not then how hard would it be to write one using the apache http client library.

EDIT: While checking out the source code for nanoHTTPD, i noticed the use of SSLServerSocket, and decided to listen in on traffic over a port running nanoHTTPD, and the traffic seemed encrypted, just jibberish. Unless tcpflow is not the right tool to use

答:
For someone who is looking for an answer.

Lighthttpd is a web server written in c/c++ that can be compiled for arm. It provides great performance as well as security and flexibility.

One benefit is it can be coupled with php-cgi to get php working on the phone as well.

https://www.lighttpd.net

I discovered this all could be done because of the open source project DroidPHP.

https://github.com/DroidPHP/DroidPHP

Title: Android Embeddable Webserver


问:
Autofill method of range class failed - help needed for my code
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

```<code>Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
</code>```

答:
Ok I know what's the problem now, I think.

I limited my scroll area in the Sub for Worksheet_Activate and the value of NoOfClients exceeded the allowed amount!

So I deleted that and I think it's ok now! This is my final code (with the scroll area becoming dynamic now)

```<code>Private Sub Check_Cases_Click()
Dim NoOfClients As Long

ActiveSheet.ScrollArea = ""
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

'Fill down the formula for n times where n= No of Clients of the Caseworker'
'=============================================================================
Dim Sht As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set Sht = Worksheets("Grand Info Sheet")
NoOfClients = Range("C2").value
NoOfClientsAdjusted = NoOfClients + 4

Sht.Range("AV5").AutoFill Destination:=Sht.Range("AV5:AV" & NoOfClientsAdjusted)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
Range("A1").Select
End If

ActiveSheet.ScrollArea = "A1:AW" & NoOfClientsAdjusted + 5
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
</code>```

Body:
I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?

The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause

Private Sub Check_Cases_Click()
Dim NoOfClients As Long

Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
        Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues

GI_CustomSort
GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
End If

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Body:
Ok I know what's the problem now, I think.

I limited my scroll area in the Sub for Worksheet_Activate and the value of NoOfClients exceeded the allowed amount!

So I deleted that and I think it's ok now! This is my final code (with the scroll area becoming dynamic now)

Private Sub Check_Cases_Click()
Dim NoOfClients As Long

ActiveSheet.ScrollArea = ""
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select

Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value

CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
                    "System will now calculate all your active cases and display " & vbNewLine & _
                    "all the clients for your information." & vbNewLine & vbNewLine & _
                    "Confirm?", vbYesNo, "Case Checking")

If CheckCaseMsg = vbNo Then
Exit Sub
End If

If CheckCaseMsg = vbYes Then

'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If

Clear
Startup_Formula

'Fill down the formula for n times where n= No of Clients of the Caseworker'
'=============================================================================
Dim Sht As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set Sht = Worksheets("Grand Info Sheet")
NoOfClients = Range("C2").value
NoOfClientsAdjusted = NoOfClients + 4

Sht.Range("AV5").AutoFill Destination:=Sht.Range("AV5:AV" & NoOfClientsAdjusted)

Application.Calculation = xlCalculationAutomatic

Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

Application.ScreenUpdating = True

GI_CustomSort

MsgBox "Case Checking Ready", vbInformation, "Ready"
Range("A1").Select
End If

ActiveSheet.ScrollArea = "A1:AW" & NoOfClientsAdjusted + 5
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub


问:
How can I pass command-line arguments via file association in Vista 64?
How can one pass command line arguments via file association in Vista 64?

I recently built a PC running Vista Ultimate 64-bit.  I noticed several of the Perl scripts I transferred failed due to command-line arguments not being passed.  As a simple test, I wrote the following (foo.pl):

```<code>#!/usr/bin/perl -w
use strict;
my $num_args = $#ARGV + 1;
print "${num_args} arguments read\n";
print "$^X\n" # to see what was being used
</code>```

Running "foo.pl 1 2 3" undesirably yielded:

```<code>0 arguments read
C:\strawberry\perl\bin\perl.exe
</code>```

Running "perl foo.pl 1 2 3" expectedly yielded:

```<code>3 arguments read
C:\strawberry\perl\bin\perl.exe
</code>```

On my old Windows XP PC, both invocations returned 3 arguments.  I documented more of my sleuthing here (win32.perl.org wiki talk), but I've yet to find a solution that works.

I've also tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi to no avail.

Any help would be appreciated.  This is driving me batty.

答:
I just tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi on my Vista 64 Ultimate and it worked.

```<code>F:\prog\perl>foo.pl 1 2 3
3 arguments read
C:\Perl64\bin\perl.exe
</code>```

That means devio is right: it must be an "file association" issue;

On an explorer, right-click on your .pl file and ask "Open with": use the "Perl Command Line interpreter" and it will work (and select "always use this program to open this type of file").

To me, "Vista's file extension manager removed the ability to pass arguments to functions" seems wrong...

I do see:

```<code>Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Perl\shell\Open\command]
@="\"C:\\Perl64\\bin\\perl.exe\" \"%1\" %*"
</code>```

Meaning if your installation did not put that kind of value in your registry, it is because:

you did not select the association during the setup of ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi

or your account has not enough privilege to write anything in the registry.

Note:

it seems the regular extension manager on Vista does not pass argument (meaning \"C:\\Perl64\\bin\\perl.exe\" \"%1\" without the %* argument)

the registry addition is necessary as documented by the SO

Body:
How can one pass command line arguments via file association in Vista 64?

I recently built a PC running Vista Ultimate 64-bit.  I noticed several of the Perl scripts I transferred failed due to command-line arguments not being passed.  As a simple test, I wrote the following (foo.pl):

#!/usr/bin/perl -w
use strict;
my $num_args = $#ARGV + 1;
print "${num_args} arguments read\n";
print "$^X\n" # to see what was being used

Running "foo.pl 1 2 3" undesirably yielded:

0 arguments read
C:\strawberry\perl\bin\perl.exe

Running "perl foo.pl 1 2 3" expectedly yielded:

3 arguments read
C:\strawberry\perl\bin\perl.exe

On my old Windows XP PC, both invocations returned 3 arguments.  I documented more of my sleuthing here (win32.perl.org wiki talk), but I've yet to find a solution that works.

I've also tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi to no avail.

Any help would be appreciated.  This is driving me batty.

LastEditorDisplayName: Kurt Leucht

Body:
I just tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi on my Vista 64 Ultimate and it worked.

F:\prog\perl>foo.pl 1 2 3
3 arguments read
C:\Perl64\bin\perl.exe

That means devio is right: it must be an "file association" issue;

On an explorer, right-click on your .pl file and ask "Open with": use the "Perl Command Line interpreter" and it will work (and select "always use this program to open this type of file").

To me, "Vista's file extension manager removed the ability to pass arguments to functions" seems wrong...

I do see:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Perl\shell\Open\command]
@="\"C:\\Perl64\\bin\\perl.exe\" \"%1\" %*"

Meaning if your installation did not put that kind of value in your registry, it is because:

you did not select the association during the setup of ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi

or your account has not enough privilege to write anything in the registry.

Note:

it seems the regular extension manager on Vista does not pass argument (meaning \"C:\\Perl64\\bin\\perl.exe\" \"%1\" without the %* argument)

the registry addition is necessary as documented by the SO

OwnerDisplayName: VonC

LastEditorDisplayName: VonC