问:
Typescript variable syntax error on terminal
i try to learn TypeScript on Visual Studio Code. But i get an sim error that i don't understand beacuse of defining variable. I'm define as that:

```<code>let year:number = 2015
</code>```

I get a syntax error on terminal beacuse i'm put a colon and write the variable type after the variable name.

How can i correct this error?

答:
How can i correct this error?

Don't run .ts files directly.

Solution

Compile to js before running. e.g.

```<code>tsc srcfiles
</code>```

More

Quickstart : https://basarat.gitbook.io/typescript/content/docs/quick/nodejs.html

Body:
i try to learn TypeScript on Visual Studio Code. But i get an sim error that i don't understand beacuse of defining variable. I'm define as that:

let year:number = 2015

I get a syntax error on terminal beacuse i'm put a colon and write the variable type after the variable name.

How can i correct this error?

Body:
How can i correct this error?

Don't run .ts files directly.

Solution

Compile to js before running. e.g.

tsc srcfiles

More

Quickstart : https://basarat.gitbook.io/typescript/content/docs/quick/nodejs.html


来源: stackexchange

问:
UISearchController iOS 11 Customization
I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:

```<code>var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
} else {
    tableView.tableHeaderView = searchController.searchBar
}

extension UISearchBar {
    func setDefaultSearchBar() {
        self.tintColor = UIColor.blue
        self.searchBarStyle = .minimal
        self.backgroundImage = UIImage(color: UIColor.clear)
        let searchBarTextField = self.value(forKey: "searchField") as! UITextField
        searchBarTextField.textColor = UIColor.white
        searchBarTextField.tintColor = UIColor.blue
        searchBarTextField = .dark
    }
}
</code>```

However, the appearance of the search bar fails to update when running the same code on iOS 11.

iOS 10:

iOS 11:

Much of the attention to this question so far has focused on the text color of the search bar. I am looking at more than this - the background color, tint color, the search indicator, clear button color, etc.

答:
```<code>    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
</code>```

ContentLicense: CC BY-SA 4.0

Title: UISearchController iOS 11 Customization

Body:
I had been using the following code prior to iOS 11 to customize the appearance of the UISearchController search bar:

var searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.setDefaultSearchBar()
searchController.searchResultsUpdater = self

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
} else {
    tableView.tableHeaderView = searchController.searchBar
}

extension UISearchBar {
    func setDefaultSearchBar() {
        self.tintColor = UIColor.blue
        self.searchBarStyle = .minimal
        self.backgroundImage = UIImage(color: UIColor.clear)
        let searchBarTextField = self.value(forKey: "searchField") as! UITextField
        searchBarTextField.textColor = UIColor.white
        searchBarTextField.tintColor = UIColor.blue
        searchBarTextField = .dark
    }
}

However, the appearance of the search bar fails to update when running the same code on iOS 11.

iOS 10:

iOS 11:

Much of the attention to this question so far has focused on the text color of the search bar. I am looking at more than this - the background color, tint color, the search indicator, clear button color, etc.

ContentLicense: CC BY-SA 3.0


问:
Can't keep Wordpress from generating thumbnails
What I want is to prevent Wordpress from generating thumbnail images (additional sizes) when Media uploader in admin is used or when wp_generate_attachment_metadata() + wp_update_attachment_metadata() is used.

To do so I have set Thumbnail size, Medium size and Large size to 0 - 0 in Settings/Media in admin menu. However, Wordpress still keeps generating these additional size images.

What am I doing wrong?

答:
Try in theme's functions.php:

wordpress-folder/wp-content/themes/theme-name/functions.php

a line looking like :

```<code>add_image_size( 'homepage-thumb', 220, 180, true );
</code>```

and also:

```<code>set_post_thumbnail_size( 150, 150 );
</code>```

remove the lines, or uncomment them if you're not sure.

Hope that works together with what you already made.

Body:
Try in theme's functions.php:

wordpress-folder/wp-content/themes/theme-name/functions.php

a line looking like :

add_image_size( 'homepage-thumb', 220, 180, true );

and also:

set_post_thumbnail_size( 150, 150 );

remove the lines, or uncomment them if you're not sure.

Hope that works together with what you already made.


问:
Delete Empty tag from xmltype oracle
i want try to delete the empty tag from xmltype. I Have generate the below xml from oracle type. In the collection few elements does not have values so i generated with empty tag.

Can any one please help me out:

Actual output:

```<code><MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>
</code>```

Expected output:

```<code><MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
</LOCATIONS>
</MESSAGE>
</code>```

答:
Use DELETEXML and look for the XPath //*[not(text())][not(*)] to find elements that contain no text and no children:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE table_name ( xml ) AS
SELECT XMLTYPE( '<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>' ) FROM DUAL;
</code>```

Query 1:

```<code>SELECT DELETEXML(
         xml,
         '//*[not(text())][not(*)]'
       ).getStringVal()
FROM   table_name
</code>```

Results:

```<code>|                                                                                DELETEXML(XML,'//*[NOT(TEXT())][NOT(*)]').GETSTRINGVAL() |
|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| <MESSAGE><LOCATIONS><LOCATION_ID>9999</LOCATION_ID><LOC_TYPE>S</LOC_TYPE><NAME>Test Location</NAME><PHONE_NUM>08 </PHONE_NUM></LOCATIONS></MESSAGE> |
</code>```

Title: Delete Empty tag from xmltype oracle

Body:
i want try to delete the empty tag from xmltype. I Have generate the below xml from oracle type. In the collection few elements does not have values so i generated with empty tag.

Can any one please help me out:

Actual output:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>

Expected output:

<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
</LOCATIONS>
</MESSAGE>

Body:
Use DELETEXML and look for the XPath //*[not(text())][not(*)] to find elements that contain no text and no children:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE table_name ( xml ) AS
SELECT XMLTYPE( '<MESSAGE>
<LOCATIONS>
  <LOCATION_ID>9999</LOCATION_ID>
  <LOC_TYPE>S</LOC_TYPE>
  <NAME>Test Location</NAME>
  <PHONE_NUM>08 </PHONE_NUM>
   <LAST_MODIFIED_BY/>
   <LAST_MODIFIED_DATE/>
   <POS_CODE/>
</LOCATIONS>
</MESSAGE>' ) FROM DUAL;

Query 1:

SELECT DELETEXML(
         xml,
         '//*[not(text())][not(*)]'
       ).getStringVal()
FROM   table_name

Results:

|                                                                                DELETEXML(XML,'//*[NOT(TEXT())][NOT(*)]').GETSTRINGVAL() |
|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| <MESSAGE><LOCATIONS><LOCATION_ID>9999</LOCATION_ID><LOC_TYPE>S</LOC_TYPE><NAME>Test Location</NAME><PHONE_NUM>08 </PHONE_NUM></LOCATIONS></MESSAGE> |


问:
AdaptiveCard native method on android not found
i'm tring to launch the basic adaptive card example using maven central depencdency but i'm having an error because native method impl is not being found.

I have just add the dependency to my build.gradle:

```<code>compile 'io.adaptivecards:adaptivecards-android-arm:1.0.0'
</code>```

This is the error:

```<code>11-13 18:19:55.944 16684-16970 E/zygote: No implementation found for long com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(java.lang.String) (tried Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString and Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString__Ljava_lang_String_2)
11-13 18:19:55.945 16684-16684 D/AndroidRuntime: Shutting down VM
11-13 18:19:55.949 16684-16684 E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.tuenti.messenger, PID: 16684
                                                 java.lang.UnsatisfiedLinkError: No implementation found for long com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(java.lang.String) (tried Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString and Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString__Ljava_lang_String_2)
                                                     at com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(Native Method)
                                                     at com.microsoft.adaptivecards.objectmodel.AdaptiveCard.DeserializeFromString(AdaptiveCard.java:105)
</code>```

I have checked the generated APK and it contains the SO for adaptive cards but still does not work.

答:
Try adding a static ctor before accessing the API and see if that helps. </p>

```<code>static {
    System.loadLibrary("adaptivecards-native-lib");
}
</code>```

Body:
i'm tring to launch the basic adaptive card example using maven central depencdency but i'm having an error because native method impl is not being found.

I have just add the dependency to my build.gradle:

compile 'io.adaptivecards:adaptivecards-android-arm:1.0.0'

This is the error:

11-13 18:19:55.944 16684-16970 E/zygote: No implementation found for long com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(java.lang.String) (tried Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString and Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString__Ljava_lang_String_2)
11-13 18:19:55.945 16684-16684 D/AndroidRuntime: Shutting down VM
11-13 18:19:55.949 16684-16684 E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.tuenti.messenger, PID: 16684
                                                 java.lang.UnsatisfiedLinkError: No implementation found for long com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(java.lang.String) (tried Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString and Java_com_microsoft_adaptivecards_objectmodel_AdaptiveCardObjectModelJNI_AdaptiveCard_1DeserializeFromString__Ljava_lang_String_2)
                                                     at com.microsoft.adaptivecards.objectmodel.AdaptiveCardObjectModelJNI.AdaptiveCard_DeserializeFromString(Native Method)
                                                     at com.microsoft.adaptivecards.objectmodel.AdaptiveCard.DeserializeFromString(AdaptiveCard.java:105)

I have checked the generated APK and it contains the SO for adaptive cards but still does not work.

Body:
Try adding a static ctor before accessing the API and see if that helps.

static {
    System.loadLibrary("adaptivecards-native-lib");
}


问:
powershell delete some files older than 90 days, with exceptions
```<code>$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item
</code>```

So I have the easier part, but I am trying to figure out how to do something a little more complex.

I am setting up a backup deletion routine.  The requirement is to keep the last 90 days of backups, then the final day of each month prior to that for the current year and finally a backup from December 31st for the prior 2 years.

I couldn't find any examples other than just a single check; is it possible to do several checks to automate that.

答:
I suggest writing a custom filter to apply the logic e.g.

```<code>filter MyCustomFilter{

    $File = $_

    $FileDate = $File.LastWriteTime
    $Now = (Get-Date)
    $FileAgeDays = ($Now - $FileDate).TotalDays

    if (

        # Keep files for at least 90 days
        ( $FileAgeDays -lt 91
        ) -or

        # Keep files from last day of the month this year
        (  $FileDate.Year -eq $Now.Year -and
           $FileDate.Month -ne $FileDate.AddDays(1).Month
        ) -or

        # Keep files from 31 Dec for up to 2 years
        (   $FileAgeDays -lt ( 2 * 365 ) -and
            $FileDate.Month -eq 12 -and
            $FileDate.Day -eq 31
        )

    ) {

        # File should be kept, so nothing is returned by the filter

    } else {

        # File should be deleted, so pass the file down the pipeline
        write-output $File

    }

}
</code>```

Now your overall code would look something like this:

```<code>get-childItem -path <path> |
    where-object { -not $_.PSIsContainer } |
    MyCustomFilter |
    Remove-Item
</code>```

It goes without saying, that proper testing is required before letting this loose on production systems.

EDIT: A Simpler test for last day of month

I thought of a neater 'last day of the month' test, which is simply to compare the month property of the date under test, with the month property of the following day e.g.

```<code>$FileDate.Month -ne $FileDate.AddDays(1).Month
</code>```

will return $true if $FileDate is last day of the month.

Body:
$timeLimit1 = Get-Date.AddDays(-90)
Get-ChildItem <path> | ? {$_.LastWriteTime -le $timeLimit1 } | Remove-Item

So I have the easier part, but I am trying to figure out how to do something a little more complex.

I am setting up a backup deletion routine.  The requirement is to keep the last 90 days of backups, then the final day of each month prior to that for the current year and finally a backup from December 31st for the prior 2 years.

I couldn't find any examples other than just a single check; is it possible to do several checks to automate that.

Body:
I suggest writing a custom filter to apply the logic e.g.

filter MyCustomFilter{

    $File = $_

    $FileDate = $File.LastWriteTime
    $Now = (Get-Date)
    $FileAgeDays = ($Now - $FileDate).TotalDays

    if (

        # Keep files for at least 90 days
        ( $FileAgeDays -lt 91
        ) -or

        # Keep files from last day of the month this year
        (  $FileDate.Year -eq $Now.Year -and
           $FileDate.Month -ne $FileDate.AddDays(1).Month
        ) -or

        # Keep files from 31 Dec for up to 2 years
        (   $FileAgeDays -lt ( 2 * 365 ) -and
            $FileDate.Month -eq 12 -and
            $FileDate.Day -eq 31
        )

    ) {

        # File should be kept, so nothing is returned by the filter

    } else {

        # File should be deleted, so pass the file down the pipeline
        write-output $File

    }

}

Now your overall code would look something like this:

get-childItem -path <path> |
    where-object { -not $_.PSIsContainer } |
    MyCustomFilter |
    Remove-Item

It goes without saying, that proper testing is required before letting this loose on production systems.

EDIT: A Simpler test for last day of month

I thought of a neater 'last day of the month' test, which is simply to compare the month property of the date under test, with the month property of the following day e.g.

$FileDate.Month -ne $FileDate.AddDays(1).Month

will return $true if $FileDate is last day of the month.


问:
Storing Data in the correct way in Python
In Keywords.txt I have these words and their 'values':

```<code>alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10
</code>```

These are some of the keywords and their 'values' that I need to store in a data structure, a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

```<code>line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()
</code>```

And I tried to convert it to a list form by doing this:

```<code>   list=[line]
</code>```

However, when I print the list, I get this:

```<code>['amazed,10']
['amazing,10']
['bad,1']
['best,10']
['better,7']
['excellent,10']
</code>```

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking to get lists in this format:

```<code>['amazed',10]
['amazing',10]
['bad',1]
</code>```

Thanks in advance!

答:
put line amazed,10 into sample.csv

```<code>    import csv

    with open('sample.csv') as csvfile:
        inputs = csv.reader(csvfile, delimiter=',')
        for row in inputs:
            row = [int(x) if x.isdigit() else x for x in row]  # convert numerical string to int which would remove quotes
            print(row)
</code>```

output:

```<code>['amazed', 10]
</code>```

Body:
In Keywords.txt I have these words and their 'values':

alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10

These are some of the keywords and their 'values' that I need to store in a data structure, a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()

And I tried to convert it to a list form by doing this:

   list=[line]

However, when I print the list, I get this:

['amazed,10']
['amazing,10']
['bad,1']
['best,10']
['better,7']
['excellent,10']

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking to get lists in this format:

['amazed',10]
['amazing',10]
['bad',1]

Thanks in advance!

Body:
put line amazed,10 into sample.csv

    import csv

    with open('sample.csv') as csvfile:
        inputs = csv.reader(csvfile, delimiter=',')
        for row in inputs:
            row = [int(x) if x.isdigit() else x for x in row]  # convert numerical string to int which would remove quotes
            print(row)

output:

['amazed', 10]


问:
Compare a variable to every element of an array
I am trying to compare a variable to the values that are stored in an array. The values in the array are extracted out from a csv file. If the values of the array are equal to the variable it will print out true.

```<code>import csv

array=[]

values = csv.reader(open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r'),
                    delimiter=',',
                    quotechar='|')
for row in values:
    array.append(row[5])

number= 4200

for a in array:
    if number == a:
        print ('True')
print ('False')
</code>```

The code only compares one value in the array and returns a false. How do I compare all the values in the array to the variable?

答:
Because it is exiting from the loop after it hits the first true value. Use the following code: </p>

```<code>   for i in array:
        if number == i:
            print ('True')
        else:
            print ('False')
</code>```

Body:
I am trying to compare a variable to the values that are stored in an array. The values in the array are extracted out from a csv file. If the values of the array are equal to the variable it will print out true.

import csv

array=[]

values = csv.reader(open('SampleEEG data Insight-1-30.11.15.17.36.16.csv', 'r'),
                    delimiter=',',
                    quotechar='|')
for row in values:
    array.append(row[5])

number= 4200

for a in array:
    if number == a:
        print ('True')
print ('False')

The code only compares one value in the array and returns a false. How do I compare all the values in the array to the variable?

Body:
Because it is exiting from the loop after it hits the first true value. Use the following code:

   for i in array:
        if number == i:
            print ('True')
        else:
            print ('False')


问:
How to use HTTP server for getting input from the client and manipulate it
I'v been using python before but never web.

I want to write a python program for generating a server that get the client input and do some function with it.

for example: a word.

And than return it's ASCII value.

I guess it's a very basic question, but I am totaly new to this stuff.

答:
For local development, you can play around with running a SimpleHTTPServer to receive HTTP requests:
https://docs.python.org/2/library/simplehttpserver.html

If you want to make a full-on web service or API that can take in input and respond to it, that sounds like a great use case for one of the Python web frameworks. I'm partial to Django, but Flask might be a bit easier to get set up with.


问:
extracting Java classes from AWT executable
I have an application that is running JVM inside it, it looks like it is using Abstract Windowing ToolKit (AWT), I found that after doing some researches as the main application window is a MSAWT_Comp_Class, doing some analyzing on the application EXE I found what looked like links to import the Java classes (I am not sure):

So I guess the Java classes are there but unreachable, all I could find in the app is an RC_DATA content that has the above links, also found that the app is a Java app converted to EXE using Jexegen as Jexegen and some SDK links can be found using a hex viewer.

My question is if is there a way to extract the Java classes or read them from that application? maybe by knowing the structure of Abstract Windowing ToolKit (AWT) or Swing or Jexegen or how Java files are being included in the c# app after compiling.

I hope I could I ask my question clearly, I tried my best with my little knowledge.

答:
My question is if is there a way to extract the Java classes or read them from that application?

As you already figured out, .exe file contains resources of type RC_DATA.
There are two entries of such type. The smaller one (named "1001") contains just string with a class name (it may be main class name) and bigger one (named "1000", about 600 Kb) contains actual classes.
You can extract that resource with help of any resource extracting tool such as a "Resource Hacker".

Each *.class file starts with 4 bytes 0xCA 0xFE 0xBA 0xBE so you can iterate through content of extracted "1000" and save each class into separate *.class file. Each 0xCA 0xFE 0xBA 0xBE will mark new file start. And, obviously end of previous.

Then classes can be decompiled.

maybe by knowing the structure of Abstract Windowing ToolKit (AWT) or Swing

AWT and Swing is a just standard libraries to build UI. So it doesn't matter here.


问:
digit_sum error, iterating through a string and then changing to an integer, python
On Codecademy.com I am on section 8, "Practice Makes Perfect", exercise 4 they ask you to:

Write a function called digit_sum that takes a positive integer n
  as input and returns the sum of all that number's digits. For example:
  digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that
  the number you are given will always be positive.)

```<code>def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(n[i])
    return total
</code>```

Since you have to only add one of the digits, I wrote a program that changed the number into a string and then iterate over each digit. When I iterate, I add each number to a local varible, total, by accessing the digit and then changing the number back into an integer. After writing my program, I was thrown the error "string indices must be integers, not str". This is the error you get when you try to add a number to a string. I was confused by this so I researched if other people were having the same problem. I also asked my programming teacher and we still could not figure it out. Can someone explain what I am doing wrong?

It does not tell me what line is throwing the error either. I forgot to mention but on the website they give a solution, but it is not at all in the terms of what I am doing, I am just severely confused of why this error is occurring.

答:
Your code iterates over the characters of your string, not the indices.  Change to:</p>

```<code>def digit_sum2(n):
     total = 0
     n = str(n)
     for i in range(0, len(n)):
         total += int(n[i])
     return total
</code>```

Body:
On Codecademy.com I am on section 8, "Practice Makes Perfect", exercise 4 they ask you to:

Write a function called digit_sum that takes a positive integer n
  as input and returns the sum of all that number's digits. For example:
  digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that
  the number you are given will always be positive.)

def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total += int(n[i])
    return total

Since you have to only add one of the digits, I wrote a program that changed the number into a string and then iterate over each digit. When I iterate, I add each number to a local varible, total, by accessing the digit and then changing the number back into an integer. After writing my program, I was thrown the error "string indices must be integers, not str". This is the error you get when you try to add a number to a string. I was confused by this so I researched if other people were having the same problem. I also asked my programming teacher and we still could not figure it out. Can someone explain what I am doing wrong?

It does not tell me what line is throwing the error either. I forgot to mention but on the website they give a solution, but it is not at all in the terms of what I am doing, I am just severely confused of why this error is occurring.

Body:
Your code iterates over the characters of your string, not the indices.  Change to:

def digit_sum2(n):
     total = 0
     n = str(n)
     for i in range(0, len(n)):
         total += int(n[i])
     return total


问:
Execute sql query from tab click event
I have a project where I am connecting my database to the windows application in vb.net. I am required to make tabs that sort the data in a specific way. For example, it is a student database with names, etc. So When I press the "Student by Last name" tab, it sorts the data by last name in ascending order. So, I made a query which brought a button, but I don't know how to execute the button automatically when the tab page is clicked. The user can't have the control of sorting. The tab does it itself. Any help will be great! I have been looking everywhere for help.</p>

```<code>Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles tbLastName.Click
        TabPage1.Hide() "this is made to get rid of previous page, but may be unnecessary"
        tbLastName.Show() "this is supposed to show the data"
        Sort_By_LastNameToolStripButton.Enabled() "My attempt to execute code from the query button that I made hidden"

    End Sub
</code>```

答:
Keep a copy of the queried data, and then order it depending on which tab is selected. Use the TabControl.SelectedIndexChanged event

```<code>Private queryData As IEnumerable(Of Student)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    queryData = QueryStudentsFromDatabase()
End Sub

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
    Select Case TabControl1.SelectedIndex
        Case 0 ' Last Name
            Dim displayData = queryData.OrderBy(Function(s) s.LastName)
        Case 1 ' Student ID
            Dim displayData = queryData.OrderBy(Function(s) s.ID)
    End Select
    ListView1.DataSource = displayData ' or whatever
End Sub
</code>```

This is a very simple example. In the interest of brevity, it is performing work on the UI thread. You can handle offloading the work if you wish.

Title: Execute sql query from tab click event

Body:
I have a project where I am connecting my database to the windows application in vb.net. I am required to make tabs that sort the data in a specific way. For example, it is a student database with names, etc. So When I press the "Student by Last name" tab, it sorts the data by last name in ascending order. So, I made a query which brought a button, but I don't know how to execute the button automatically when the tab page is clicked. The user can't have the control of sorting. The tab does it itself. Any help will be great! I have been looking everywhere for help.

Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles tbLastName.Click
        TabPage1.Hide() "this is made to get rid of previous page, but may be unnecessary"
        tbLastName.Show() "this is supposed to show the data"
        Sort_By_LastNameToolStripButton.Enabled() "My attempt to execute code from the query button that I made hidden"

    End Sub

Body:
Keep a copy of the queried data, and then order it depending on which tab is selected. Use the TabControl.SelectedIndexChanged event

Private queryData As IEnumerable(Of Student)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    queryData = QueryStudentsFromDatabase()
End Sub

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
    Select Case TabControl1.SelectedIndex
        Case 0 ' Last Name
            Dim displayData = queryData.OrderBy(Function(s) s.LastName)
        Case 1 ' Student ID
            Dim displayData = queryData.OrderBy(Function(s) s.ID)
    End Select
    ListView1.DataSource = displayData ' or whatever
End Sub

This is a very simple example. In the interest of brevity, it is performing work on the UI thread. You can handle offloading the work if you wish.


问:
To call inherited final method produce "cannot find symbol" error
I have this code:

```<code>import javafx.scene.control.TextArea;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.Node;

public class InitialTextFixedArea extends TextArea{
    public InitialTextFixedArea(String testoIniziale){
        super(testoIniziale);
        EventHandler<KeyEvent> eventHandler = new EventHandler<KeyEvent>(){
            @Override
            public void handle(KeyEvent e){
                if((e.getEventType() == KeyEvent.KEY_PRESSED & this.getCaretPosition() < 5)
                    |(this.getCaretPosition() == 5 & e.getCode() == KeyCode.BACK_SPACE)){
                    this.setEditable(false);
                }else{
                    this.setEditable(true);
                }
            }
        };
        this.addEventFilter(KeyEvent.KEY_PRESSED, eventHandler);
        this.addEventFilter(KeyEvent.KEY_RELEASED, eventHandler);
    }
}
</code>```

and when I try to compile, I obtain more than one error of type "cannot find symbol", where the symbols are the getCaretPosition() and setEditable() methods.
Do not I inherit these methods from TextArea that inherit them from TextInputControl?

Thank you for the answers!

答: this in this context points to the EventHandler, which doesn't have those methods. Change it to InitialTextFixedArea.this.getCaretPosition() or just getCaretPosition().

Body:
I have this code:

import javafx.scene.control.TextArea;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.Node;

public class InitialTextFixedArea extends TextArea{
    public InitialTextFixedArea(String testoIniziale){
        super(testoIniziale);
        EventHandler<KeyEvent> eventHandler = new EventHandler<KeyEvent>(){
            @Override
            public void handle(KeyEvent e){
                if((e.getEventType() == KeyEvent.KEY_PRESSED & this.getCaretPosition() < 5)
                    |(this.getCaretPosition() == 5 & e.getCode() == KeyCode.BACK_SPACE)){
                    this.setEditable(false);
                }else{
                    this.setEditable(true);
                }
            }
        };
        this.addEventFilter(KeyEvent.KEY_PRESSED, eventHandler);
        this.addEventFilter(KeyEvent.KEY_RELEASED, eventHandler);
    }
}

and when I try to compile, I obtain more than one error of type "cannot find symbol", where the symbols are the getCaretPosition() and setEditable() methods.
Do not I inherit these methods from TextArea that inherit them from TextInputControl?

Thank you for the answers!


问:
Can I instrument outgoing method/constructor calls with ByteBuddy?
I have a project where I was using Javassist to log outgoing method/constructor calls with code like this:

```<code>CtMethod cm = ... ;
cm.instrument(
new ExprEditor() {
    public void edit(MethodCall m)
                  throws CannotCompileException
    {
        if (m.getClassName().equals("Point")
                      && m.getMethodName().equals("move"))
            m.replace("{ $1 = 0; $_ = $proceed($$); }");
    }
});
</code>```

which assigns '0' to the first argument of the called method and then proceeds with the original call, that is, if cm represents the method someMethod we modify the outgoing calls to Point::move from someMethod:

```<code>public int someMethod(int arg1){
    Point p;
    ...
    Point newPoint =
    //Here we start tampering with the code
        p.move(0, arg2, arg3, arg4); //Say it was originally p.move(arg1, arg2, arg3, arg4);
    //From here we leave it as it was
    ...
}
</code>```

I am now trying to migrate to ByteBuddy as I wanted the classes to be compatible with (online) JaCoCo. I've managed to instrument methods and constructors "from the inside" (instrumenting the called methods themselves), but I haven't found any way to do it "from the outside" (instrumenting the calls to such methods from elsewhere). Is there any way to do it with ByteBuddy ?

This question is related to another which asked for a way to catch constructor exceptions as it is the way I achieved it using Javassist.

答:
You can change an argument of a method by using Advice which allows you to change an argument prior to the original method's execution:

```<code>@Advice.OnMethodEnter
static void enter(@Advice.Argument(value = 0, readOnly = false) int arg) {
  arg = 0;
}
</code>```

Doing so, the above code will be prepended to the move method that you need to locate using an ElementMatcher like named("move").

Body:
I have a project where I was using Javassist to log outgoing method/constructor calls with code like this:

CtMethod cm = ... ;
cm.instrument(
new ExprEditor() {
    public void edit(MethodCall m)
                  throws CannotCompileException
    {
        if (m.getClassName().equals("Point")
                      && m.getMethodName().equals("move"))
            m.replace("{ $1 = 0; $_ = $proceed($$); }");
    }
});

which assigns '0' to the first argument of the called method and then proceeds with the original call, that is, if cm represents the method someMethod we modify the outgoing calls to Point::move from someMethod:

public int someMethod(int arg1){
    Point p;
    ...
    Point newPoint =
    //Here we start tampering with the code
        p.move(0, arg2, arg3, arg4); //Say it was originally p.move(arg1, arg2, arg3, arg4);
    //From here we leave it as it was
    ...
}

I am now trying to migrate to ByteBuddy as I wanted the classes to be compatible with (online) JaCoCo. I've managed to instrument methods and constructors "from the inside" (instrumenting the called methods themselves), but I haven't found any way to do it "from the outside" (instrumenting the calls to such methods from elsewhere). Is there any way to do it with ByteBuddy ?

This question is related to another which asked for a way to catch constructor exceptions as it is the way I achieved it using Javassist.

Body:
You can change an argument of a method by using Advice which allows you to change an argument prior to the original method's execution:

@Advice.OnMethodEnter
static void enter(@Advice.Argument(value = 0, readOnly = false) int arg) {
  arg = 0;
}

Doing so, the above code will be prepended to the move method that you need to locate using an ElementMatcher like named("move").


问:
docker-compose replays past output on container reboot
It appears that docker-compose replays captured output on container re-launch.  This is against expectation, and is misleading about what my container is actually doing.  Can this be disabled?

For instance,

I have a simple service that logs and exits w/ code 0.

In docker-compose.yml, i have restart: always set.

When running docker-compose up, each time the logging container comes back up after existing, I see all previous output relogged, plus any new additions from the current run.

Here's an easy to run example.

clone, cd <project>/fluentd, docker-compose build, & docker-compose up

I'm using docker-compose version 1.16.1, build 6d1ac21 on OSX.

Tips would be great!

答:
Is this a life cycle problem? There is a difference between a stop and a "rm". If you do a docker-compose stop, the containers are suspended. Use "docker-compose up" to restart them from last time.
But "docker-compose rm" will destroy the containers. docker-compose up again to recreate them from scratch.</p>


问:
Add new route in Restful route and use this in form Laravel
I added a new route for a restful controller:

Route::get('admin/store_productos', 'AdminController@store_productos');
Route::resource('admin', 'AdminController');
```

<p>And I use it in a form:</p>

<pre class="lang-php prettyprint-override"><code>{!!Form::open([
    'route' => 'admin.store_productos',
    'method'=> 'POST',
    'files' => true])!!}
   <div class="row">
    {!!Form::text('name', null, ['class' => 'input-field col s12', 'placeholder' => 'Inserte Nombre del articulo'])!!}
  </div>

  <div class="row">
    {!!Form::text('precio', null, ['class' => 'input-field col  s12', 'placeholder'=>'Inserte precio del articulo'])!!}
  </div>

  <div class="row">
    {!!Form::text('descripcion', null, ['class' => 'input-field col  s12', 'placeholder'=>'Inserte descripcion del articulo'])!!}
  </div>

  <div class="row">
    {!! Form::file('path') !!}
  </div>
  {!! Form::submit('Registrar', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
</code>```

But I'm getting this error:

Route [admin/store_productos] not defined

I don't know what's happening.

答:
That's probably because your additional route is not named:

Route::get('admin/store_productos', 'AdminController@store_productos')
    ->name('admin.store_productos');
```

Body:
I added a new route for a restful controller:

Route::get('admin/store_productos', 'AdminController@store_productos');
Route::resource('admin', 'AdminController');

And I use it in a form:

{!!Form::open([
    'route' => 'admin.store_productos',
    'method'=> 'POST',
    'files' => true])!!}

    {!!Form::text('name', null, ['class' => 'input-field col s12', 'placeholder' => 'Inserte Nombre del articulo'])!!}

    {!!Form::text('precio', null, ['class' => 'input-field col  s12', 'placeholder'=>'Inserte precio del articulo'])!!}

    {!!Form::text('descripcion', null, ['class' => 'input-field col  s12', 'placeholder'=>'Inserte descripcion del articulo'])!!}

    {!! Form::file('path') !!}

  {!! Form::submit('Registrar', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}

But I'm getting this error:

Route [admin/store_productos] not defined

I don't know what's happening.


问:
Why is Symfony Session data encrypted on my production server?
I want to share a single authentificaition method for to Symfony websites sharing the same top-domain.
I use a cookie valid on all subdomains and sfPDOSessionStorage for keeping session data.

factories.yml is set up like this on both projects:

```<code>all:
  storage:
    class: sfPDOSessionStorage
    param:
      database: doctrine
      db_table: sessions
      session_name: myauth
      db_id_col: id
      db_data_col: sess_data
      db_time_col: time
      session_cookie_domain: ".mydomain.net"
      session_cookie_lifetime: 86400
      session_cookie_path: /
</code>```

On my development machine and on my co-workers's machine this mechanism is working fine but on the server it does not (I'm asked for credentials when I switch sub-domains). The only difference I see between the two environments is the format in which the data is stored, the data seems to be encrypted on the prod server but appears in clear text on my machine. There's no sensitive data here so I can post an example :

Dev environment sess_data:

```<code>symfony/user/sfUser/lastRequest|i:1295349567;symfony/user/sfUser/authenticated|b:0;symfony/user/sfUser/credentials|a:0:{}symfony/user/sfUser/attributes|a:1:{s:30:"symfony/user/sfUser/attributes";a:1:{s:7:"referer";s:0:"";}}symfony/user/sfUser/culture|s:2:"fr";
</code>```

Production server sess_data:

```<code>BB7HBTsQg75NNGvb9Z8sexldqbS79YzDgrztQzSFhsUpEk2EeCOtKw8FQbm31vLIRyr3ZP_klwZFXywnkdem27naIWjIVBP_WwpwNRg4IMj1J0fIfxJN_UOw2RbCWh91L5ryCD_7_ynN2UtxfuJwUWnxoGuUvqD8YQxNdczQipmktPVFk1mVfKE1-BsrdHHLIXH_gi44-Bos3f-EshE5skuQpachnY1FkgvvvOuXEj7zxPflgA3xtGoqJxkDijT-uKnQCH4TrimhvkIRGCt0oVuOdsAJzuWW6ijgPCD3X767mSIzm_lQmJoSGxDB7fAgFihB7Ljoq0tsysC62BqTYFB6dTnuZoj3KON8lXlyNJZVyLgTWZ3EYoObtc8jCKYNDonSjEqzTvwg4NJRVoB5ePx61iTqbDd9qFlkryzj9J8.
</code>```

I haven't got a clue which encryption type is used to store information in the database, nor am I sure that this is the root of my problems but as this is the only difference I can spot, I don't see any other explanation. (PHP and MySQL versions are identical, with Ubuntu 10.10 on my side and Debian Squeeze server-side).

答:
I think there's some module installed on your production server responsible for encrypting the session's data.

For example, suhosin patch adds such a feature to PHP: http://www.hardened-php.net/suhosin/configuration.html

It's activated by suhosin.session.encrypt configuration option in php.ini.

ContentLicense: CC BY-SA 2.5

Body:
I want to share a single authentificaition method for to Symfony websites sharing the same top-domain.
I use a cookie valid on all subdomains and sfPDOSessionStorage for keeping session data.

factories.yml is set up like this on both projects:

all:
  storage:
    class: sfPDOSessionStorage
    param:
      database: doctrine
      db_table: sessions
      session_name: myauth
      db_id_col: id
      db_data_col: sess_data
      db_time_col: time
      session_cookie_domain: ".mydomain.net"
      session_cookie_lifetime: 86400
      session_cookie_path: /

On my development machine and on my co-workers's machine this mechanism is working fine but on the server it does not (I'm asked for credentials when I switch sub-domains). The only difference I see between the two environments is the format in which the data is stored, the data seems to be encrypted on the prod server but appears in clear text on my machine. There's no sensitive data here so I can post an example :

Dev environment sess_data:

symfony/user/sfUser/lastRequest|i:1295349567;symfony/user/sfUser/authenticated|b:0;symfony/user/sfUser/credentials|a:0:{}symfony/user/sfUser/attributes|a:1:{s:30:"symfony/user/sfUser/attributes";a:1:{s:7:"referer";s:0:"";}}symfony/user/sfUser/culture|s:2:"fr";

Production server sess_data:

BB7HBTsQg75NNGvb9Z8sexldqbS79YzDgrztQzSFhsUpEk2EeCOtKw8FQbm31vLIRyr3ZP_klwZFXywnkdem27naIWjIVBP_WwpwNRg4IMj1J0fIfxJN_UOw2RbCWh91L5ryCD_7_ynN2UtxfuJwUWnxoGuUvqD8YQxNdczQipmktPVFk1mVfKE1-BsrdHHLIXH_gi44-Bos3f-EshE5skuQpachnY1FkgvvvOuXEj7zxPflgA3xtGoqJxkDijT-uKnQCH4TrimhvkIRGCt0oVuOdsAJzuWW6ijgPCD3X767mSIzm_lQmJoSGxDB7fAgFihB7Ljoq0tsysC62BqTYFB6dTnuZoj3KON8lXlyNJZVyLgTWZ3EYoObtc8jCKYNDonSjEqzTvwg4NJRVoB5ePx61iTqbDd9qFlkryzj9J8.

I haven't got a clue which encryption type is used to store information in the database, nor am I sure that this is the root of my problems but as this is the only difference I can spot, I don't see any other explanation. (PHP and MySQL versions are identical, with Ubuntu 10.10 on my side and Debian Squeeze server-side).


问:
Android Studio gradle build stuck at app:processDebugResources
I'm on Windows. I created a new project on Android Studio for Marshmallow at least.
The only thing I've done so far is generating the main activity which is a tabbed activity with view pager. Also, you should know that this project is a private git repo that I cloned.

I'm working on this project with another developer and the project is perfectly working on his side.

The problem is:

When I try to launch the app (wether it is a virtual device or my real phone), the gradle build gets stuck at the app:processDebugResources step. I waited more than an hour and nothing happened. Moreover, when I want to cancel the gradle build, it doesn't respond and I have to kill Android Studio process. Then I restart Android Studio and I have to kill a gradle process that prevents the initial gradle build (at Android Studio startup) from working.

The crazy thing is that I was able to launch the app before. I even installed it on my phone!

What I've tried so far:

Do what stackoverflow was giving as solutions like tick the offline mode in the settings

Create a new project --> It doesn't change anything

Reinstall Android Studio --> It doesn't change anything

Deactivating Avast antivirus

Invalidate cache/restart + Clean + rebuild (the rebuild gets stuck like when I try to launch the app)

And maybe other solutions that I forgot...

It's getting very annoying as it's making me lose days of development.

If you have any more solutions, or if you think I should try again some of the previous solutions, help would be greatly appreciated !

答:
I did several things:

Install NDK

Change JDK from embedded one to Jdk 8

Redownload SDK i was using (6,7,8)

And now the problem is solved ! I have no idea which of these things made the tricks but I'm happy ! It may be useful to someone else one day.


问:
creating an auto increment field within a mongo document
In my Spring Boot application I am using Spring-Data MongoDB, and I have a simple POJO that represents users:

```<code>@EqualsAndHashCode
public class User implements Storable {

  @Id
  public ObjectId id;

  @Getter @Setter public String firstName;
  @Getter @Setter public String lastName;
  @Getter @Setter public long userNum;
  @DBRef(lazy = true)
  @Getter @Setter public List<Section> sections = new ArrayList<Section>();

...
rest of class omitted
...

}
</code>```

my UserController looks something like this:

```<code>@Controller
public class UserController {

  @Autowired
  UserRepository repository;

  @ModelAttribute("allSections")
  public List<Section> getSections() {
    return sectionRepository.findAll();
  }

  @RequestMapping(value = "/users/new", method = RequestMethod.POST)
  public String newUser(@ModelAttribute("user") User user) {
    User newUser = new User();
    newUser.userNum = user.userNum;
    newUser.firstName = user.firstName;
    newUser.lastName = user.lastName;
    newUser.sections = user.sections;
    newUser = repository.save(newUser);

    for (Section section : newUser.sections) {
      section.addToUsers(newUser);
      sectionRepository.save(section);
    }

    return "redirect:/users";
  }
... rest of controller omitted
}
</code>```

please notice that the field that I want to be auto-generated is not the ID field.

I would like for the userNum attribute to be auto incrementing such that the first user object created and stored in the database starts at a certain value... say 9000 and each user created after that is incremented by 1.

What are my options to do this? I have seen examples using JPA's @GeneratedValue, others that rely on custom Mongo queries to create a sequence collection, but I have not been able to get either to work...

答:
Ok I have figured this out here is how I implemented this:

class for userNum, which is a simple POJO

```<code>public class UserNum {

  @Id
  private ObjectId id;

  @Getter
  @Setter
  public long seq;

  public UserNum(long seq) {
    this.seq = seq;
  }

}
</code>```

the UserNumRepository has one method defined that returns the last UserNum that was saved to the collection

```<code>@Repository
public interface UserNumRepository extends MongoRepository<UserNum, String> {
  UserNum findTopByOrderByIdDesc();
}
</code>```

the UserNumService which simply finds the last number in the sequence and creates the next number, then saves it and returns that number. UserNumService is an interface with one method signature. this creates a collection of all userNums that have been created and used.

```<code>@Service
public class UserNumServiceImpl implements UserNumService {

  @Autowired
  private UserNumRepository userNumRepository;

  @Override
  public long getNext() {
    UserNum last = userNumRepository.findTopByOrderByIdDesc();
    long lastNum = last.seq;
    UserNum next = new UserNum(lastNum + 1);
    userNumRepository.save(next);
    return next.seq;
  }
}
</code>```

Inside Application.java you could seed the collection with the starting number or from the mongo shell.

```<code>@Autowired UserNumRepository userNumRepository;

public void run(String... args) throws Exception {

    userNumRepository.deleteAll();
    // start the sequence at 9000
    userNumRepository.save(new UserNum(9000));
}
</code>```

and finally now you can simply use the service when needing to issue a new userNum, perhaps inside the constructor.

Body:
In my Spring Boot application I am using Spring-Data MongoDB, and I have a simple POJO that represents users:

@EqualsAndHashCode
public class User implements Storable {

  @Id
  public ObjectId id;

  @Getter @Setter public String firstName;
  @Getter @Setter public String lastName;
  @Getter @Setter public long userNum;
  @DBRef(lazy = true)
  @Getter @Setter public List
 sections = new ArrayList
();

...
rest of class omitted
...

}

my UserController looks something like this:

@Controller
public class UserController {

  @Autowired
  UserRepository repository;

  @ModelAttribute("allSections")
  public List
 getSections() {
    return sectionRepository.findAll();
  }

  @RequestMapping(value = "/users/new", method = RequestMethod.POST)
  public String newUser(@ModelAttribute("user") User user) {
    User newUser = new User();
    newUser.userNum = user.userNum;
    newUser.firstName = user.firstName;
    newUser.lastName = user.lastName;
    newUser.sections = user.sections;
    newUser = repository.save(newUser);

    for (Section section : newUser.sections) {
      section.addToUsers(newUser);
      sectionRepository.save(section);
    }

    return "redirect:/users";
  }
... rest of controller omitted
}

please notice that the field that I want to be auto-generated is not the ID field.

I would like for the userNum attribute to be auto incrementing such that the first user object created and stored in the database starts at a certain value... say 9000 and each user created after that is incremented by 1.

What are my options to do this? I have seen examples using JPA's @GeneratedValue, others that rely on custom Mongo queries to create a sequence collection, but I have not been able to get either to work...

Body:
Ok I have figured this out here is how I implemented this:

class for userNum, which is a simple POJO

public class UserNum {

  @Id
  private ObjectId id;

  @Getter
  @Setter
  public long seq;

  public UserNum(long seq) {
    this.seq = seq;
  }

}

the UserNumRepository has one method defined that returns the last UserNum that was saved to the collection

@Repository
public interface UserNumRepository extends MongoRepository<UserNum, String> {
  UserNum findTopByOrderByIdDesc();
}

the UserNumService which simply finds the last number in the sequence and creates the next number, then saves it and returns that number. UserNumService is an interface with one method signature. this creates a collection of all userNums that have been created and used.

@Service
public class UserNumServiceImpl implements UserNumService {

  @Autowired
  private UserNumRepository userNumRepository;

  @Override
  public long getNext() {
    UserNum last = userNumRepository.findTopByOrderByIdDesc();
    long lastNum = last.seq;
    UserNum next = new UserNum(lastNum + 1);
    userNumRepository.save(next);
    return next.seq;
  }
}

Inside Application.java you could seed the collection with the starting number or from the mongo shell.

@Autowired UserNumRepository userNumRepository;

public void run(String... args) throws Exception {

    userNumRepository.deleteAll();
    // start the sequence at 9000
    userNumRepository.save(new UserNum(9000));
}

and finally now you can simply use the service when needing to issue a new userNum, perhaps inside the constructor.


答:
You're calling this.getCaretPosition() from within an EventHandler. In that case this refers the the event handler and not to the TextArea.

Try calling it without this.

Title: To call inherited final method produce "cannot find symbol" error


问:
How to Get The Oldest And The Newest Record of Different Columns By Person - SQL Server?
I need to get the oldest previous balance and the newest actual balance of each person in a table of transactions.

For example I got this:

```<code>+-----------------+---------------+-----------------+---------------+
| dateTransaction | idPerson      | previousBalance | actualBalance |
+-----------------+---------------+-----------------+---------------+
| 01-11-2017      |      1        |       0         |    1000       |
| 02-11-2017      |      2        |       500       |    2000       |
| 03-11-2017      |      1        |       1000      |    1500       |
| 04-11-2017      |      2        |       2000      |    2500       |
+-----------------+---------------+-----------------+---------------+
</code>```

So I need to get something like this:

```<code>+---------------+-----------------+---------------+
| idPerson      | previousBalance | actualBalance |
+---------------+-----------------+---------------+
|      1        |       0         |    1500       |
|      2        |       500       |    2500       |
+---------------+-----------------+---------------+
</code>```

This is the script to create the table:

```<code>SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Transaction]
(
    [numberTransaction] [int] NOT NULL,
    [dateTransaction] [datetime] NOT NULL,
    [idPerson] [decimal](20, 0) NOT NULL,
    [transactionAmount] [decimal](18, 3) NOT NULL,
    [previousBalance] [decimal](18, 3) NOT NULL,
    [actualBalance] [decimal](18, 3) NOT NULL,

    CONSTRAINT [PK_Transaction]
        PRIMARY KEY CLUSTERED ([numberTransaction] ASC)
) ON [PRIMARY]
GO
</code>```

Thanks in advance...

答:
Use row_number() over() as follows:

```<code>SELECT *
FROM (
    SELECT t.*
    , row_number() over(partition by idPerson order by dateTransaction ASC) as is_oldest
    , row_number() over(partition by idPerson order by dateTransaction DESC) as is_newest
    FROM Transaction t
     ) d
WHERE ( is_oldest = 1 OR is_newest = 1 )
ORDER BY idPerson, dateTransaction ASC
</code>```

In the over clause the partition by means numbers assigned by row_number() will be PER idPerson. Then the order by sets 1 at the oldest date (when sorted asending) or 1 at the newest (when sorted descending).

Body:
I need to get the oldest previous balance and the newest actual balance of each person in a table of transactions.

For example I got this:

+-----------------+---------------+-----------------+---------------+
| dateTransaction | idPerson      | previousBalance | actualBalance |
+-----------------+---------------+-----------------+---------------+
| 01-11-2017      |      1        |       0         |    1000       |
| 02-11-2017      |      2        |       500       |    2000       |
| 03-11-2017      |      1        |       1000      |    1500       |
| 04-11-2017      |      2        |       2000      |    2500       |
+-----------------+---------------+-----------------+---------------+

So I need to get something like this:

+---------------+-----------------+---------------+
| idPerson      | previousBalance | actualBalance |
+---------------+-----------------+---------------+
|      1        |       0         |    1500       |
|      2        |       500       |    2500       |
+---------------+-----------------+---------------+

This is the script to create the table:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Transaction]
(
    [numberTransaction] [int] NOT NULL,
    [dateTransaction] [datetime] NOT NULL,
    [idPerson] [decimal](20, 0) NOT NULL,
    [transactionAmount] [decimal](18, 3) NOT NULL,
    [previousBalance] [decimal](18, 3) NOT NULL,
    [actualBalance] [decimal](18, 3) NOT NULL,

    CONSTRAINT [PK_Transaction]
        PRIMARY KEY CLUSTERED ([numberTransaction] ASC)
) ON [PRIMARY]
GO

Thanks in advance...

Body:
Use row_number() over() as follows:

SELECT *
FROM (
    SELECT t.*
    , row_number() over(partition by idPerson order by dateTransaction ASC) as is_oldest
    , row_number() over(partition by idPerson order by dateTransaction DESC) as is_newest
    FROM Transaction t
     ) d
WHERE ( is_oldest = 1 OR is_newest = 1 )
ORDER BY idPerson, dateTransaction ASC

In the over clause the partition by means numbers assigned by row_number() will be PER idPerson. Then the order by sets 1 at the oldest date (when sorted asending) or 1 at the newest (when sorted descending).


问:
How to print out message in textfield using query and cursor
I may have formulated my question wrong but the point is I am creating a signup form, and I faced with a problem. So, imagine you are trying to register as a new user, and you typed email, username, and password. When you press "Sign up" button cursor checks whether or not your email or username in database. If it is not in database then we add it our database, but the problem is if it already exists in database then IT SHOULD PRINT MESSAGE : "username/email already exist". So, I am not able to print that message. I have added some code with "TOAST" but when I run it the app crashes. I commented the code that I added.
using Toast is accepted as well as textfield

```<code>public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
EditText email, username, password, passwordconf;
Boolean checkEmail, checkUsername, checkPassword, checkPasswordconf,zbz,zbc;
SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    dbHelper = new DBHelper(this);
}
public void clickButton2(View view) throws Exception {
    email = (EditText) findViewById(R.id.email);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    String userName = username.getText().toString();
    String userEmail = email.getText().toString();
    if (checkEmail && checkUsername && checkPassword && checkPasswordconf) {
     if (!ValidateUser(userName, userEmail)) {
     database = dbHelper.getWritableDatabase();
     ContentValues contentValues = new ContentValues();
     contentValues.put(DBHelper.KEY_LOGIN,username.getText().toString());
     contentValues.put(DBHelper.KEY_EMAIL,email.getText().toString());
     contentValues.put(DBHelper.KEY_PASSWORD,password.getText().toString());
     database.insert(DBHelper.TABLE_NAME, null, contentValues);
Toast.makeText(this, "you have registered
successfully!",Toast.LENGTH_SHORT).show();
     Intent intent2 = new Intent(Main2Activity.this, Main3Activity.class);
     startActivity(intent2);
        }/*else{
      database = dbHelper.getWritableDatabase();
      Cursor cursor = database.query(DBHelper.TABLE_NAME, null, null, null,
null, null, null);
            if (cursor.getString(cursor.getColumnIndex(DBHelper.KEY_EMAIL)).equals(userEmail)){
                Toast.makeText(this, "email already exist in Database", Toast.LENGTH_SHORT).show();
            }else if (cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LOGIN)).equals(userName)){
                Toast.makeText(this, "username already exist in Database", Toast.LENGTH_SHORT).show();
            }
            cursor.close();
        }*/
    }
}
public boolean ValidateUser(String userName, String userEmail) {
    database = dbHelper.getWritableDatabase();
    Cursor cursor = database.query(DBHelper.TABLE_NAME, null,
    DBHelper.KEY_LOGIN + "=? OR " + DBHelper.KEY_EMAIL + "=?", new String[
{userName, userEmail}, null, null, null);
    int i = cursor.getCount();
    cursor.close();
        if(i>0){
            return true;
        }else{
            return false;
        }
}
}
</code>```

DBHelper.java

```<code>public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Login_register";
public static final String TABLE_NAME = "users";
public static final String KEY_LOGIN = "login";
public static final String KEY_PASSWORD = "passsword";
public static final String KEY_EMAIL = "email";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
            KEY_PASSWORD + " TEXT," + KEY_EMAIL + " TEXT"+")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
}
</code>```

答:
I think, you should first try running adb logcat / pidcat to find out what exactly is the crash / what caused it.

PS: Your check for the presence of values in the db is wrong. You should iterate through the cursor to find the same.

PPS: You might prefer using unboxed boolean for the values initialized.

if (null && null..)

would ideally throw NPE

Body:
I may have formulated my question wrong but the point is I am creating a signup form, and I faced with a problem. So, imagine you are trying to register as a new user, and you typed email, username, and password. When you press "Sign up" button cursor checks whether or not your email or username in database. If it is not in database then we add it our database, but the problem is if it already exists in database then IT SHOULD PRINT MESSAGE : "username/email already exist". So, I am not able to print that message. I have added some code with "TOAST" but when I run it the app crashes. I commented the code that I added.
using Toast is accepted as well as textfield

public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
EditText email, username, password, passwordconf;
Boolean checkEmail, checkUsername, checkPassword, checkPasswordconf,zbz,zbc;
SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    dbHelper = new DBHelper(this);
}
public void clickButton2(View view) throws Exception {
    email = (EditText) findViewById(R.id.email);
    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    String userName = username.getText().toString();
    String userEmail = email.getText().toString();
    if (checkEmail && checkUsername && checkPassword && checkPasswordconf) {
     if (!ValidateUser(userName, userEmail)) {
     database = dbHelper.getWritableDatabase();
     ContentValues contentValues = new ContentValues();
     contentValues.put(DBHelper.KEY_LOGIN,username.getText().toString());
     contentValues.put(DBHelper.KEY_EMAIL,email.getText().toString());
     contentValues.put(DBHelper.KEY_PASSWORD,password.getText().toString());
     database.insert(DBHelper.TABLE_NAME, null, contentValues);
Toast.makeText(this, "you have registered
successfully!",Toast.LENGTH_SHORT).show();
     Intent intent2 = new Intent(Main2Activity.this, Main3Activity.class);
     startActivity(intent2);
        }/*else{
      database = dbHelper.getWritableDatabase();
      Cursor cursor = database.query(DBHelper.TABLE_NAME, null, null, null,
null, null, null);
            if (cursor.getString(cursor.getColumnIndex(DBHelper.KEY_EMAIL)).equals(userEmail)){
                Toast.makeText(this, "email already exist in Database", Toast.LENGTH_SHORT).show();
            }else if (cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LOGIN)).equals(userName)){
                Toast.makeText(this, "username already exist in Database", Toast.LENGTH_SHORT).show();
            }
            cursor.close();
        }*/
    }
}
public boolean ValidateUser(String userName, String userEmail) {
    database = dbHelper.getWritableDatabase();
    Cursor cursor = database.query(DBHelper.TABLE_NAME, null,
    DBHelper.KEY_LOGIN + "=? OR " + DBHelper.KEY_EMAIL + "=?", new String[
{userName, userEmail}, null, null, null);
    int i = cursor.getCount();
    cursor.close();
        if(i>0){
            return true;
        }else{
            return false;
        }
}
}

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Login_register";
public static final String TABLE_NAME = "users";
public static final String KEY_LOGIN = "login";
public static final String KEY_PASSWORD = "passsword";
public static final String KEY_EMAIL = "email";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + KEY_LOGIN + " TEXT," +
            KEY_PASSWORD + " TEXT," + KEY_EMAIL + " TEXT"+")");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
}


问:
Can not move widgets in Tkinter
I am trying to learn tkinter, but I got a problem and I can`t move forward from this point. I wanted to make just a simple GUI with one button, unfortunately, I am not able to move that button ( being always displayed in the most left upper corner).

This is the code that I used :

```<code>class App(Frame):
def __init__(self, master=None):
    Frame.__init__(self, master)
    self.grid()
    self.master.title('GUI')
    quitbttn = Button(self, text='quit')
    quitbttn.grid(row=3, column=5)

root = Tk()
app = App(root)
app.mainloop()
</code>```

Although, I found this snippet of code on the iternet, and it is working perfectly, the only difference being that pack() is used instead of grid() :

```<code>class Window(Frame):
def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master
    self.init_window()
def init_window(self):
    self.master.title("GUI")
    self.pack(fill=BOTH, expand=1)
    quit_button = Button(self, text='quit')
    quit_button.pack(side=BOTTOM)

root = Tk()
app = Window(root)
root.mainloop()
</code>```

I would like to be able to use grid as well.
Any advice is being apreciated. Thank you!

答:
The reason you cannot move the button is because you only have one element.

```<code>quitbttn.grid(row=3, column=5)
</code>```

This part of the script basically says that the button should be placed a third row down and in the fifth space along.  Since you have no other elements in the window it does not move the button at all.  This is because all the 2 rows and 4 columns are all equal to 0 so the first place it packs is in the top left corner.

Using the .pack() function allows you move the button without the need of any other button in the window.

If you added another button you would then be able to move around the first button in three different places.

Note that you cannot use the .pack() and .grid() functions in the same window.

Title: Can not move widgets in Tkinter

Body:
I am trying to learn tkinter, but I got a problem and I can`t move forward from this point. I wanted to make just a simple GUI with one button, unfortunately, I am not able to move that button ( being always displayed in the most left upper corner).

This is the code that I used :

class App(Frame):
def __init__(self, master=None):
    Frame.__init__(self, master)
    self.grid()
    self.master.title('GUI')
    quitbttn = Button(self, text='quit')
    quitbttn.grid(row=3, column=5)

root = Tk()
app = App(root)
app.mainloop()

Although, I found this snippet of code on the iternet, and it is working perfectly, the only difference being that pack() is used instead of grid() :

class Window(Frame):
def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master
    self.init_window()
def init_window(self):
    self.master.title("GUI")
    self.pack(fill=BOTH, expand=1)
    quit_button = Button(self, text='quit')
    quit_button.pack(side=BOTTOM)

root = Tk()
app = Window(root)
root.mainloop()

I would like to be able to use grid as well.
Any advice is being apreciated. Thank you!

Body:
The reason you cannot move the button is because you only have one element.

quitbttn.grid(row=3, column=5)

This part of the script basically says that the button should be placed a third row down and in the fifth space along.  Since you have no other elements in the window it does not move the button at all.  This is because all the 2 rows and 4 columns are all equal to 0 so the first place it packs is in the top left corner.

Using the .pack() function allows you move the button without the need of any other button in the window.

If you added another button you would then be able to move around the first button in three different places.

Note that you cannot use the .pack() and .grid() functions in the same window.


问:
Auto resize std::vector when I use insert
What is elegant way to insert an element to particular position of std::vector ?
If std::vector has size less than a position.

For example:

```<code>#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> vec(8);
    vec.insert(vec.begin() + 200, 5); // fail, I need auto-resize
}
</code>```

答:
Use std::vector::resize, with appropriate argument. Say you have your:

```<code>std::vector<int> vec(8);
</code>```

Simply use:

```<code>vec.resize(201);
vec.insert(vec.begin() + 200, 5);
</code>```

You could also wrap it around your own template function, which could check for possibly needed allocation:

```<code>template<class T>
void safe_insert(std::vector<T>& vec, const size_t pos, const T arg)
{
    if(vec.size() <= pos) vec.resize(pos);
    vec.insert(vec.begin() + pos, arg);
}
</code>```

Calling it like so:

```<code>std::vector<int> vec(8);
safe_insert(vec, 200, 5);
std::cout << vec[200];
</code>```

The code outputs: 5.

Body:
What is elegant way to insert an element to particular position of std::vector ?
If std::vector has size less than a position.

For example:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> vec(8);
    vec.insert(vec.begin() + 200, 5); // fail, I need auto-resize
}

Body:
Use std::vector::resize, with appropriate argument. Say you have your:

std::vector<int> vec(8);

Simply use:

vec.resize(201);
vec.insert(vec.begin() + 200, 5);

You could also wrap it around your own template function, which could check for possibly needed allocation:

template<class T>
void safe_insert(std::vector<T>& vec, const size_t pos, const T arg)
{
    if(vec.size() <= pos) vec.resize(pos);
    vec.insert(vec.begin() + pos, arg);
}

Calling it like so:

std::vector<int> vec(8);
safe_insert(vec, 200, 5);
std::cout << vec[200];

The code outputs: 5.


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答: Sorry, don't know the exact name of the event off the top of my head, but is something like SelectedItemChanged that you are looking for.

OwnerDisplayName: Steve

OwnerDisplayName: Rob Prouse


问:
WebRequest MVC HttpPost DateTime Format
I have an MVC Action.....

```<code>[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)
</code>```

...and I'm calling the action from a compact framework application like so.....

```<code> WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }
</code>```

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax

答: Did you misspell? You are posting 'myDate', but your action method expects 'myDateTime'.</p>

Title: WebRequest MVC HttpPost DateTime Format

Body:
I have an MVC Action.....

[HttpPost]
public ActionResult DoStuff(string myString, DateTime myDateTime)

...and I'm calling the action from a compact framework application like so.....

 WebRequest request = WebRequest.Create(url);

        // Set the Method property of the request to POST.
        request.Method = "POST";
        request.Proxy = null;

        // Create POST data and convert it to a byte array.
        string postData = "myString=Bonjour&myDateTime=" + DateTime.Now.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        // Get the response.
        using (WebResponse response = request.GetResponse())
        {
            // Display the status.
            // Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            using (Stream responseStream = response.GetResponseStream())
            {
                // Read the response...
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }

Problem is the "myDateTime" parameter is always null?   What format should the postData string be in for this to work (i've tried quite a few!)?

Many thanks,

ETFairfax


问:
file_get_contents failed to open stream: HTTP request failed! HTTP/1.1 500 Internal > Server Error in
I see many questions matching to my issue. But none of them is providing any workable solution. so instead of making complex functionality i need simple solution. Please I dont' want cURL. I've already done a lot with this code.

I'm working on a scraping project and need to load the contents of product revisions from ebay.

I am using PHP function

```<code>file_get_contents();
</code>```

Here is the URL i'm troubling with.

```<code>https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183
</code>```

this file_get_contents(); is working perfectly fine on different URLs but don't know why not on this.

This is the code i'm using.

```<code><?php
$html = file_get_contents('https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183');
echo $html;
?>
</code>```

but i'm getting this error..

Warning:
  file_get_contents(https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&&item=272908801183):
  failed to open stream: HTTP request failed! HTTP/1.1 500 Internal
  Server Error in
  /Users/samz/Documents/projects/scraping/test.php
  on line 3

答:
file_get_contents (read the tip on blue rectangle) can be easily blocked on server side through php.ini  avoid using it. When you want to get data from an other site use curl instead. http://php.net/manual/en/book.curl.php, there are plenty of options that you can use with curl, by playing a bit the following code can work with your url.

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
$data = curl_exec($ch);
curl_close($ch);
</code>```

and by echoing the $data varible you can see the whole page.

```<code>echo $data;
</code>```

you can try parsing the data from the page by utilizing php DOM Methods and convert them to the data type you want (object class, array etc).

Body:
I see many questions matching to my issue. But none of them is providing any workable solution. so instead of making complex functionality i need simple solution. Please I dont' want cURL. I've already done a lot with this code.

I'm working on a scraping project and need to load the contents of product revisions from ebay.

I am using PHP function

file_get_contents();

Here is the URL i'm troubling with.

https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183

this file_get_contents(); is working perfectly fine on different URLs but don't know why not on this.

This is the code i'm using.

<?php
$html = file_get_contents('https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183');
echo $html;
?>

but i'm getting this error..

Warning:
  file_get_contents(https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&&item=272908801183):
  failed to open stream: HTTP request failed! HTTP/1.1 500 Internal
  Server Error in
  /Users/samz/Documents/projects/scraping/test.php
  on line 3

Body:
file_get_contents (read the tip on blue rectangle) can be easily blocked on server side through php.ini  avoid using it. When you want to get data from an other site use curl instead. http://php.net/manual/en/book.curl.php, there are plenty of options that you can use with curl, by playing a bit the following code can work with your url.

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL,"https://cgi.ebay.com/ws/eBayISAPI.dll?ViewItemRevisionDetails&item=272908801183");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
$data = curl_exec($ch);
curl_close($ch);

and by echoing the $data varible you can see the whole page.

echo $data;

you can try parsing the data from the page by utilizing php DOM Methods and convert them to the data type you want (object class, array etc).


问:
User input as string cannot be used to call variable in a class
Not sure I am even asking the question correctly, but I will explain. I have created a class, and I have created instances in that class, the problem is I want to be able to use an instance which is chosen by the user via input. Let's say I would like to create a chess game. I want to be able to move a piece forward (possibly backward), left, and right. Suppose I have already created a method inside the class to move the piece and each piece has a name, x-coord, and y-coord. This is the issue I get

```<code>class Piece(object):
    def __init__(self, x , y):
         self.x = x
         self.y = y

    def move(self, amount, direction):
         if direction == 'right':
            self.x = self.x + amount
         if direction == 'left':
            self.x = self.x - amount
         if direction == 'up':
            self.y = self.y + amount
         if direction == 'down':
            self.y = self.y - amount

rook = Piece(0,0)

piece = input('What piece would you like to move?')

#Assume that the user types rook after this prompt

piece.move(4,'right')
</code>```

Now I get an error because the input which is assigned to the variable piece is a string, and when I need rook.move, I am actually getting 'rook'.move
I understand variables can be changed using int(var), float(var), str(var), but how would one go about changing a variable to a class variable.

答:
A way would be to have a dictionary that maps the piece names to your classes.

So

```<code>pieces = {
    'Queen': Piece(0,0),
    'Tower': Piece(0,0),
    'Rook' Piece(0,0)
}

inp = input('Which piece would you like to move?')

if inp in pieces:
    pieces[inp]().move(4, right)
else:
    print('No such piece: %s - Valid pieces: %s' % (inp, pieces.keys()))
</code>```

Body:
Not sure I am even asking the question correctly, but I will explain. I have created a class, and I have created instances in that class, the problem is I want to be able to use an instance which is chosen by the user via input. Let's say I would like to create a chess game. I want to be able to move a piece forward (possibly backward), left, and right. Suppose I have already created a method inside the class to move the piece and each piece has a name, x-coord, and y-coord. This is the issue I get

class Piece(object):
    def __init__(self, x , y):
         self.x = x
         self.y = y

    def move(self, amount, direction):
         if direction == 'right':
            self.x = self.x + amount
         if direction == 'left':
            self.x = self.x - amount
         if direction == 'up':
            self.y = self.y + amount
         if direction == 'down':
            self.y = self.y - amount

rook = Piece(0,0)

piece = input('What piece would you like to move?')

#Assume that the user types rook after this prompt

piece.move(4,'right')

Now I get an error because the input which is assigned to the variable piece is a string, and when I need rook.move, I am actually getting 'rook'.move
I understand variables can be changed using int(var), float(var), str(var), but how would one go about changing a variable to a class variable.

Body:
A way would be to have a dictionary that maps the piece names to your classes.

So

pieces = {
    'Queen': Piece(0,0),
    'Tower': Piece(0,0),
    'Rook' Piece(0,0)
}

inp = input('Which piece would you like to move?')

if inp in pieces:
    pieces[inp]().move(4, right)
else:
    print('No such piece: %s - Valid pieces: %s' % (inp, pieces.keys()))


问:
Azure Search: Order by dynamic data
I have an Azure Search index composed of documents that can "occur" in multiple regions any number of times. For example Document1 has 5 occurrences in Region1, 20 occurrences in Region2. Document2 has 54 occurrences in Region1, and 10 occurrences in Region3. Document3 has 10 occurrences in Region3. We want to use Azure Search for searching and suggestions, but base the order on number of occurrences on a region. For example the search for Document from a user in Region1 should return in the order Document2, Document1, Document3 because Document2 has 54 occurrences in that region, while Document1 has 5 occurrences and Document3 has none.

```<code>[
  { 'name': 'Document1', 'regions': ['Region1|5', 'Region2|20'] },
  { 'name': 'Document2', 'regions': ['Region1|54', 'Region3|10'] },
  { 'name': 'Document3', 'regions': ['Region3|10'] }
]
</code>```

I'm having a hard time figuring out how to structure the index or if it is even possible with Azure Search. Please note that the number of regions is potentially in the hundreds of thousands. I am ok with changing regions for center points and use geospatial functions instead, but I still don't see how to lay the data or query it.

What is the best way to structure the index and how would one make the query possible?

答:
tl;dr - There might be a solution for you based on some assumptions I have. Please read on, and if possible try to provide some validations around my assumptions for me to give a better answer (if such an answer exists).

Unfortunately, Azure search doesn't have an out-of-the box approach for your scenario. There might be a work around however - instead of the regions collection being something like ['Region1|5', 'Region2|20'], you could try to structure the document such that it appears to be ['Region1', 'Region1',...., 'Region2', 'Region2', ...] (that is, make the collection contain n elements of Region1 and m elements of Region2 where in your case n = 5 and m = 10.

Then you should simply be able to search using the Region that the user originates from and I believe the results should be ordered based on which document's collection column (regions) contains more occurrences of the particular queried region.

This approach helps you in 2 ways:

You could try adding each region as a column in the search index and use some queries to get the kind of result you want. However, since you mention there might be hundreds of thousands of such regions, it might not work well with our service limits. If however that's not the case, I highly recommend adding each region as a column, so that you can query/order by the column value.

With the replication of the string approach, you can have arbitrarily large collections as I believe Azure search does not have any limitations with regard to the number of elements in a collection. Also the nice thing here is, if your document will have a sparse number of regions (i.e., you may have 100s of 1000s of regions, but any given document will only have few regions enumerated), you should be able to achieve what you want. If that's not the case however, this approach might not be super nice/efficient and might even be painful for you to manage.

Also, just FYI I'd recommend taking a look at the scoring profiles feature
and especially the tag function to see if that might in any way be useful to you.

Title: Azure Search: Order by dynamic data

Body:
I have an Azure Search index composed of documents that can "occur" in multiple regions any number of times. For example Document1 has 5 occurrences in Region1, 20 occurrences in Region2. Document2 has 54 occurrences in Region1, and 10 occurrences in Region3. Document3 has 10 occurrences in Region3. We want to use Azure Search for searching and suggestions, but base the order on number of occurrences on a region. For example the search for Document from a user in Region1 should return in the order Document2, Document1, Document3 because Document2 has 54 occurrences in that region, while Document1 has 5 occurrences and Document3 has none.

[
  { 'name': 'Document1', 'regions': ['Region1|5', 'Region2|20'] },
  { 'name': 'Document2', 'regions': ['Region1|54', 'Region3|10'] },
  { 'name': 'Document3', 'regions': ['Region3|10'] }
]

I'm having a hard time figuring out how to structure the index or if it is even possible with Azure Search. Please note that the number of regions is potentially in the hundreds of thousands. I am ok with changing regions for center points and use geospatial functions instead, but I still don't see how to lay the data or query it.

What is the best way to structure the index and how would one make the query possible?


问:
How could I make this XSLT not(contains()) work?
I put here this part of the XSLT with the if:

```<code><xsl:template match="receta">
<xsl:if test="./ingredientes/ingrediente[not(contains(., 'Leche'))] and
              ./ingredientes/ingrediente[not(contains(., 'Queso'))] ">
    <article>
        <header>
            <h2>
                <xsl:apply-templates select="nombre"/>
</code>```

And the corresponding part of the XML:

```<code><receta n="R2">
    <nombre>
        Croquetas de bacalao
    </nombre>
    <tipo>
        Primer plato
    </tipo>
    <ingredientes>
        <ingrediente cantidad= "1" unidad="en lomos">
            Bacalao
        </ingrediente>
        <ingrediente cantidad= "850" unidad= "ml.">
            Leche entera
        </ingrediente>
</code>```

Without the not() it works but obviously it's not what I need. Which is the correct way of using not() in this case?

答:
Perhaps you want to test if none of the ingredients contain Lecho or Quese. That would be

```<code>test="not(./ingredientes/ingrediente[contains(., 'Leche'))] and
      not(./ingredientes/ingrediente[contains(., 'Queso'))]"
</code>```

Your code is testing that there is at least one ingredient which doesn't contain Leche and at least one that doesn't contain Queso, which I don't think is going to satisfy people allergic to dairy products.

Body:
I put here this part of the XSLT with the if:

<xsl:template match="receta">
<xsl:if test="./ingredientes/ingrediente[not(contains(., 'Leche'))] and
              ./ingredientes/ingrediente[not(contains(., 'Queso'))] ">

                <xsl:apply-templates select="nombre"/>

And the corresponding part of the XML:

<receta n="R2">
    <nombre>
        Croquetas de bacalao
    </nombre>
    <tipo>
        Primer plato
    </tipo>
    <ingredientes>
        <ingrediente cantidad= "1" unidad="en lomos">
            Bacalao
        </ingrediente>
        <ingrediente cantidad= "850" unidad= "ml.">
            Leche entera
        </ingrediente>

Without the not() it works but obviously it's not what I need. Which is the correct way of using not() in this case?

Body:
Perhaps you want to test if none of the ingredients contain Lecho or Quese. That would be

test="not(./ingredientes/ingrediente[contains(., 'Leche'))] and
      not(./ingredientes/ingrediente[contains(., 'Queso'))]"

Your code is testing that there is at least one ingredient which doesn't contain Leche and at least one that doesn't contain Queso, which I don't think is going to satisfy people allergic to dairy products.