问:
Python Assistance Searching a List
```<code>"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
    if index==0:
        artist.append(line)
        index=index+1
    elif index==1:
        song.append(line)
        index=index+1
    elif index==2:
        album.append(line)
        index=index+1
    elif index==3:
        genre.append(line)
        index=index+1
    elif index==4:
        index=0
while 1:
    selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
    if selection == 1:
        print "You selected Search"
        searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
        if searchselection == 1:
           print '[%s]' % ''.join(map(str, song))
        elif searchselection == 2:
            print '[%s]' % ''.join(map(str, artist))
        elif searchselection == 3:
            artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
            artist.index(artistsearch)
            print value
        elif searchselection == 4:
            print '[%s]' % ''.join(map(str, genre))
        elif searchselection == 5:
            print "display"
        elif searchselection == 6:
            print "display"
        elif searchselection == 7:
            print "display"
        break
    elif selection == 2:
        print "You selected recommend."
        recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
        if recommendselection == 1:
            songrec = str(raw_input("Please enter the song title\n"))

        elif recommendselection == 2:
            artistrec = str(raw_input("Please enter the Artist's name\n"))
        break
    elif selection == 3:
        print "You selected edit."
        editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
        if editselection == 1:
            songadd = str(raw_input("Please enter the EVERYTHING\n"))
        elif editselection == 2:
            playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
        elif editselection == 3:
            playlistadd = str(raw_input("Please enter the name of the playlist\n"))
        break
    elif selection == 4:
        print "You selected Save."
        f.close()
        break
</code>```

So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.

Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.

Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:

```<code>Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes

Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes

Gathering Field
Lost In America
Lost In America
Rock

Ellie Goulding
Burn
Halcyon
Pop;Road tunes

Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
</code>```

答:
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:</p>

```<code>class Song():
    """Class to store the attributes for each song"""
    def __init__ (self):
        self.artist = ""
        self.song = ""
        self.album = ""
        self.genre = ""

# List to store all the Song objects
songs_list = []

f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
    # Instantiate an empty Song object
    s = Song()
    if index == 0:
        s.artist = line
        index=index+1
    elif index == 1:
        s.song = line
        index = index + 1
    elif index == 2:
        s.album = line
        index = index + 1
    elif index == 3:
        s.genre = line
        index = index+1
    elif index == 4:
        index = 0
    songs_list.append(s)
</code>```

Title: Python Assistance Searching a List

Body:
"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
    if index==0:
        artist.append(line)
        index=index+1
    elif index==1:
        song.append(line)
        index=index+1
    elif index==2:
        album.append(line)
        index=index+1
    elif index==3:
        genre.append(line)
        index=index+1
    elif index==4:
        index=0
while 1:
    selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
    if selection == 1:
        print "You selected Search"
        searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
        if searchselection == 1:
           print '[%s]' % ''.join(map(str, song))
        elif searchselection == 2:
            print '[%s]' % ''.join(map(str, artist))
        elif searchselection == 3:
            artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
            artist.index(artistsearch)
            print value
        elif searchselection == 4:
            print '[%s]' % ''.join(map(str, genre))
        elif searchselection == 5:
            print "display"
        elif searchselection == 6:
            print "display"
        elif searchselection == 7:
            print "display"
        break
    elif selection == 2:
        print "You selected recommend."
        recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
        if recommendselection == 1:
            songrec = str(raw_input("Please enter the song title\n"))

        elif recommendselection == 2:
            artistrec = str(raw_input("Please enter the Artist's name\n"))
        break
    elif selection == 3:
        print "You selected edit."
        editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
        if editselection == 1:
            songadd = str(raw_input("Please enter the EVERYTHING\n"))
        elif editselection == 2:
            playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
        elif editselection == 3:
            playlistadd = str(raw_input("Please enter the name of the playlist\n"))
        break
    elif selection == 4:
        print "You selected Save."
        f.close()
        break

So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.

Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.

Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:

Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes

Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes

Gathering Field
Lost In America
Lost In America
Rock

Ellie Goulding
Burn
Halcyon
Pop;Road tunes

Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes

Body:
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:

class Song():
    """Class to store the attributes for each song"""
    def __init__ (self):
        self.artist = ""
        self.song = ""
        self.album = ""
        self.genre = ""

# List to store all the Song objects
songs_list = []

f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
    # Instantiate an empty Song object
    s = Song()
    if index == 0:
        s.artist = line
        index=index+1
    elif index == 1:
        s.song = line
        index = index + 1
    elif index == 2:
        s.album = line
        index = index + 1
    elif index == 3:
        s.genre = line
        index = index+1
    elif index == 4:
        index = 0
    songs_list.append(s)


来源: stackexchange

问:
Pulling key value from array in Python
I am trying to pull specific key values from an array that is returned after using the requests library to perform a GET request. Here is a sample of what is returned from the GET request:

```<code>{
  'response': {
     'members': [
        {
         'id': 5562221,
         'pacing': False,
         'file_name': None,
         'id': 5562227,
         'pacing': False,
         'file_name': None,
         }]
</code>```

This is what my code looks like. I am trying to pull all of the 'id' key values:

```<code>response = requests.get(url, headers=header)

member_advert_list = json.loads(response.text)

final_member_list = member_advert_list["response"]["members"]["id]

print final_member_list
</code>```

After running my code, I receive a "string indices must be integers, not str" error. Am I going about this the wrong way? Do I need to also run a loop to pull these "Id" key values? I saw a similar question on here about this error message in python but my situation is a bit different being that I am trying to pull data returned in JSON format from a GET request. Thanks in advance for the help.

答:
This code would give a list of all of the IDs.</p>

```<code>import json
string = '{"response":{"members":[{"id": 123}, {"id": 456}]}}' # simplified data structure
data = json.loads(string)
ids = map(lambda x: x['id'], data['response']['members'])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pulling key value from array in Python

Body:
I am trying to pull specific key values from an array that is returned after using the requests library to perform a GET request. Here is a sample of what is returned from the GET request:

{
  'response': {
     'members': [
        {
         'id': 5562221,
         'pacing': False,
         'file_name': None,
         'id': 5562227,
         'pacing': False,
         'file_name': None,
         }]

This is what my code looks like. I am trying to pull all of the 'id' key values:

response = requests.get(url, headers=header)

member_advert_list = json.loads(response.text)

final_member_list = member_advert_list["response"]["members"]["id]

print final_member_list

After running my code, I receive a "string indices must be integers, not str" error. Am I going about this the wrong way? Do I need to also run a loop to pull these "Id" key values? I saw a similar question on here about this error message in python but my situation is a bit different being that I am trying to pull data returned in JSON format from a GET request. Thanks in advance for the help.

Body:
This code would give a list of all of the IDs.

import json
string = '{"response":{"members":[{"id": 123}, {"id": 456}]}}' # simplified data structure
data = json.loads(string)
ids = map(lambda x: x['id'], data['response']['members'])


问:
Opening a screenshot image in another activity
I created an application to take a screen shot of the current screen and then open the image in a new activity. For some reason my application crashes when i want to open the new activity to view the picture. Here's my code:

```<code>public static Bitmap getScreenShot(View view) {
    View screenView = view.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);
    return bitmap;
}
</code>```

This is the onSave method that gets the image and is meant to set and display the image in another activity:

```<code> public void onSave(View view){
   Bitmap bm = getScreenShot(view);

    ImageView view= (ImageView) findViewById(R.id.newView);
    view.setImageBitmap(bm);

   Intent saveIntent = new Intent(this, SavePicture.class);
   startActivity(saveIntent);

}
</code>```

This is the saveIntent activity XML code:

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/saveView"
    android:contentDescription=""
    tools:ignore="ContentDescription" />
</RelativeLayout>
</code>```

And the MANIFEST

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.krypttech.gallery">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SavePicture">

    </activity>
</application>

</manifest>
</code>```

答:
So I fixed this by passing the Bitmap through the Intent. Had to compress the Bitmap to byte though.

```<code>public  void onSave(View view){
    Bitmap bm = getScreenShot(view);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    Intent previewIntent = new Intent(this, SavePicture.class);
    previewIntent.putExtra("Bitmap", byteArray);

    startActivity(previewIntent);
}
</code>```

Then this is the receiving activity

```<code>public class SavePicture extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.save_activity);

    byte[] byteArray = getIntent().getByteArrayExtra("Bitmap");
    Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView saveView = (ImageView) findViewById(R.id.saveView);
    saveView.setImageBitmap(bm);
}

}
</code>```

Body:
I created an application to take a screen shot of the current screen and then open the image in a new activity. For some reason my application crashes when i want to open the new activity to view the picture. Here's my code:

public static Bitmap getScreenShot(View view) {
    View screenView = view.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);
    return bitmap;
}

This is the onSave method that gets the image and is meant to set and display the image in another activity:

 public void onSave(View view){
   Bitmap bm = getScreenShot(view);

    ImageView view= (ImageView) findViewById(R.id.newView);
    view.setImageBitmap(bm);

   Intent saveIntent = new Intent(this, SavePicture.class);
   startActivity(saveIntent);

}

This is the saveIntent activity XML code:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/saveView"
    android:contentDescription=""
    tools:ignore="ContentDescription" />
</RelativeLayout>

And the MANIFEST

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.krypttech.gallery">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SavePicture">

    </activity>
</application>

</manifest>

Body:
So I fixed this by passing the Bitmap through the Intent. Had to compress the Bitmap to byte though.

public  void onSave(View view){
    Bitmap bm = getScreenShot(view);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    Intent previewIntent = new Intent(this, SavePicture.class);
    previewIntent.putExtra("Bitmap", byteArray);

    startActivity(previewIntent);
}

Then this is the receiving activity

public class SavePicture extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.save_activity);

    byte[] byteArray = getIntent().getByteArrayExtra("Bitmap");
    Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView saveView = (ImageView) findViewById(R.id.saveView);
    saveView.setImageBitmap(bm);
}

}


问:
Runtime 440 Excel Error Deleting Selected Row in VBA
EDIT: So I tried manually performing the actions in this code, and excel also crashed. Does this mean that I've got the same crash error as the other poster?

As a preface, fair warning I am not a professional programmer, I just play with this to try to make my (and my co-workers') lives a little easier.

This code was working a month ago when I made it, maybe it's been broken by an update, not sure, but I'm not sure why it now throws up the error. Another macro I have that's very similar still works.

Now the macro throws Error 440, and afterwards, MS Excel will crash.

```<code>Sub RemoveRow()
    Dim Eng As Worksheet
    Dim rmg As Range
    Dim Sup As Worksheet

    Application.ScreenUpdating = False

       '~~> Set this to the relevant worksheet
    Set Eng = ThisWorkbook.Sheets("Engr+Tech")
    Set Sup = ThisWorkbook.Sheets("Suprv+Sppt")

    Eng.Activate

With Eng

    Range("D8").End(xlDown).Select

    '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

    '~~> Select last row
    Set rmg = .Rows(ActiveCell.Row)
    rmg.Offset(-1).Select

    '~~> Select techs
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

    '~~> Select last row
    Set rmg = .Rows(ActiveCell.Row)
    rmg.Offset(-1).Select

    '~~> Select ftechs
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

End With

Sup.Activate

With Sup

    Range("D8").End(xlDown).Select

    '~~> Select CLS
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
     '~~> Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    .Rows(ActiveCell.Row).Delete

End With

Eng.Activate

Range("A1").Select

Application.ScreenUpdating = True

End Sub
</code>```

答:
Big thanks to everyone that helped me on this one. It turned out to be a security patch from March 17th, and the new patch (released today) corrected the issue.

Here's the update I got:
https://support.microsoft.com/en-us/help/3178690/ms17-014-description-of-the-security-update-for-excel-2010-march-14-20

Solution was to update to the new patch:
https://support.microsoft.com/en-us/help/3191855

Body:
EDIT: So I tried manually performing the actions in this code, and excel also crashed. Does this mean that I've got the same crash error as the other poster?

As a preface, fair warning I am not a professional programmer, I just play with this to try to make my (and my co-workers') lives a little easier.

This code was working a month ago when I made it, maybe it's been broken by an update, not sure, but I'm not sure why it now throws up the error. Another macro I have that's very similar still works.

Now the macro throws Error 440, and afterwards, MS Excel will crash.

Sub RemoveRow()
    Dim Eng As Worksheet
    Dim rmg As Range
    Dim Sup As Worksheet

    Application.ScreenUpdating = False

       '~~> Set this to the relevant worksheet
    Set Eng = ThisWorkbook.Sheets("Engr+Tech")
    Set Sup = ThisWorkbook.Sheets("Suprv+Sppt")

    Eng.Activate

With Eng

    Range("D8").End(xlDown).Select

    '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

    '~~> Select last row
    Set rmg = .Rows(ActiveCell.Row)
    rmg.Offset(-1).Select

    '~~> Select techs
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

    '~~> Select last row
    Set rmg = .Rows(ActiveCell.Row)
    rmg.Offset(-1).Select

    '~~> Select ftechs
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
    Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    rmg.Delete

End With

Sup.Activate

With Sup

    Range("D8").End(xlDown).Select

    '~~> Select CLS
    Cells(Selection.Row, 4).End(xlDown).Select
    Cells(Selection.Row, 4).End(xlDown).Select

     '~~> Set your range
     '~~> Set rmg = .Rows(ActiveCell.Row)

    '~~> Delete the range
    .Rows(ActiveCell.Row).Delete

End With

Eng.Activate

Range("A1").Select

Application.ScreenUpdating = True

End Sub


问:
How the function changes the unsortedlist variable?
```<code>def merge_sort(alist):
##    print("The list entering the function is ",alist)

    if (len(alist)>1):

        mid=len(alist)//2
        left_list=alist[0:mid]
        right_list=alist[mid:]

        merge_sort(left_list)
        merge_sort(right_list)

##        print("alist is ",alist)

        i=0
        j=0
        k=0

        while i < len(left_list) and j < len(right_list):
            if left_list[i]<right_list[j]:
                alist[k]=left_list[i]
                i+=1
            else:
                alist[k]=right_list[j]
                j+=1
            k+=1

        while i < len(left_list):
            alist[k]=left_list[i]
            i+=1
            k+=1

        while j< len(right_list):
            alist[k]=right_list[j]
            j+=1
            k+=1

        #return(alist)

unsortedlist=[56,2,3,91,45,34,56,2,4,7,8,1,3]
merge_sort(unsortedlist)

print(unsortedlist)
</code>```

The output is
[1, 2, 2, 3, 3, 4, 7, 8, 34, 45, 56, 56, 91]

Why the unsortedlist list changed even though nothing was returned ?

答: The list is being mutated within the function as a 'side-effect' of the functions actions. When you pass 'alist' into your function mergesort, you pass in a reference (i.e. the location in memory) of alist. Within mergesort you change the value at that memory location (e.g. alist[0] = 1 changes the value in memory located at alist[0] to 1). Now when the mergesort function terminates even though it doesn't return anything, you have still altered the values found in  alist. Hence when you later reference that memory location again, you find that it's value has changed even outside of the mergesort function. </p>

Body:
def merge_sort(alist):
##    print("The list entering the function is ",alist)

    if (len(alist)>1):

        mid=len(alist)//2
        left_list=alist[0:mid]
        right_list=alist[mid:]

        merge_sort(left_list)
        merge_sort(right_list)

##        print("alist is ",alist)

        i=0
        j=0
        k=0

        while i < len(left_list) and j < len(right_list):
            if left_list[i]<right_list[j]:
                alist[k]=left_list[i]
                i+=1
            else:
                alist[k]=right_list[j]
                j+=1
            k+=1

        while i < len(left_list):
            alist[k]=left_list[i]
            i+=1
            k+=1

        while j< len(right_list):
            alist[k]=right_list[j]
            j+=1
            k+=1

        #return(alist)

unsortedlist=[56,2,3,91,45,34,56,2,4,7,8,1,3]
merge_sort(unsortedlist)

print(unsortedlist)

The output is
[1, 2, 2, 3, 3, 4, 7, 8, 34, 45, 56, 56, 91]

Why the unsortedlist list changed even though nothing was returned ?


问:
iOS - Run async operations in serial manner on non-main thread
```<code>- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.
</code>```

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.

答:
the basic idea that you had tried semaphores sounds good.

I like to use the extendable approach, where you can easily extent the amount of operations being performed, where you pass all the parameters (or other operation related information) from an array.

Simple and easy extendable function!

```<code>- (void)performBatchProcess
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *attributes = @[@"A", @"B", @"C"];
        NSLog(@"Started all Operations at: %f",CFAbsoluteTimeGetCurrent());
        [self performSelectorWithAttributes:attributes success:^{
            NSLog(@"Finished all Operations");
            NSLog(@"Finished at: %f",CFAbsoluteTimeGetCurrent());
        }];
    });
}
</code>```

This function is basically used to queue all the operations sequentially

```<code>- (void)performSelectorWithAttributes:(NSArray<NSString *> *)attributes success:(void (^)())success
{
    for (NSString *attribute in attributes)
    {
        [self performOperationWithAttributeAndWait:attribute];
    }
    success();
}
</code>```

Your basic function is included here with its success block being used to stop blocking the queue

```<code>- (void)performOperationWithAttributeAndWait:(NSString *)attribute
{
    //create a semaphore
    __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    void (^privateFinish)(NSString *attribute) = ^(NSString *attribute) {
        NSLog(@"Finished Process: %@",attribute);
        // Stop blocking our thread and go on :-)
        dispatch_semaphore_signal(semaphore);
    };

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Started Process: %f",CFAbsoluteTimeGetCurrent());
        [NSThread sleepForTimeInterval:2]; // Simulate a process that takes time
        privateFinish(attribute);
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
</code>```

Sample log, which demonstrates that an operation takes at least 2 seconds now (with the timer simulating the process calculations)

```<code>2017-03-29 00:05:02.570 asdasd[24376:1836160] Started all Operations at: 512431502.570876
2017-03-29 00:05:02.571 asdasd[24376:1836146] Started Process: 512431502.571429
2017-03-29 00:05:04.598 asdasd[24376:1836146] Finished Process: A
2017-03-29 00:05:04.599 asdasd[24376:1836146] Started Process: 512431504.599392
2017-03-29 00:05:06.673 asdasd[24376:1836146] Finished Process: B
2017-03-29 00:05:06.673 asdasd[24376:1836146] Started Process: 512431506.673433
2017-03-29 00:05:08.673 asdasd[24376:1836146] Finished Process: C
2017-03-29 00:05:08.674 asdasd[24376:1836160] Finished all Operations
2017-03-29 00:05:08.674 asdasd[24376:1836160] Finished at: 512431508.674475
</code>```

Body:
- (void) fetchOperation:(NSString *c){
    async_method(c):^{
      NSLog(@"%@ completed.",c);
    }
  }
// call fetchOperation:@"A"
// call fetchOperation:@"B"
// call fetchOperation:@"C"

//Expecting output: A completed, B completed, C Completed.

Please note I want fetch to happen on non-main thread. Their could be 1 to n fetchOperation calls. And each fetchOperation call can happen as a result of some other user action like user tapped.
I tried semaphores, nsoperationQueue but no luck so far.

Body:
the basic idea that you had tried semaphores sounds good.

I like to use the extendable approach, where you can easily extent the amount of operations being performed, where you pass all the parameters (or other operation related information) from an array.

Simple and easy extendable function!

- (void)performBatchProcess
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *attributes = @[@"A", @"B", @"C"];
        NSLog(@"Started all Operations at: %f",CFAbsoluteTimeGetCurrent());
        [self performSelectorWithAttributes:attributes success:^{
            NSLog(@"Finished all Operations");
            NSLog(@"Finished at: %f",CFAbsoluteTimeGetCurrent());
        }];
    });
}

This function is basically used to queue all the operations sequentially

- (void)performSelectorWithAttributes:(NSArray<NSString *> *)attributes success:(void (^)())success
{
    for (NSString *attribute in attributes)
    {
        [self performOperationWithAttributeAndWait:attribute];
    }
    success();
}

Your basic function is included here with its success block being used to stop blocking the queue

- (void)performOperationWithAttributeAndWait:(NSString *)attribute
{
    //create a semaphore
    __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    void (^privateFinish)(NSString *attribute) = ^(NSString *attribute) {
        NSLog(@"Finished Process: %@",attribute);
        // Stop blocking our thread and go on :-)
        dispatch_semaphore_signal(semaphore);
    };

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Started Process: %f",CFAbsoluteTimeGetCurrent());
        [NSThread sleepForTimeInterval:2]; // Simulate a process that takes time
        privateFinish(attribute);
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

Sample log, which demonstrates that an operation takes at least 2 seconds now (with the timer simulating the process calculations)

2017-03-29 00:05:02.570 asdasd[24376:1836160] Started all Operations at: 512431502.570876
2017-03-29 00:05:02.571 asdasd[24376:1836146] Started Process: 512431502.571429
2017-03-29 00:05:04.598 asdasd[24376:1836146] Finished Process: A
2017-03-29 00:05:04.599 asdasd[24376:1836146] Started Process: 512431504.599392
2017-03-29 00:05:06.673 asdasd[24376:1836146] Finished Process: B
2017-03-29 00:05:06.673 asdasd[24376:1836146] Started Process: 512431506.673433
2017-03-29 00:05:08.673 asdasd[24376:1836146] Finished Process: C
2017-03-29 00:05:08.674 asdasd[24376:1836160] Finished all Operations
2017-03-29 00:05:08.674 asdasd[24376:1836160] Finished at: 512431508.674475


问:
How to select data top x data after y rows from SQL Server
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

```<code>SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)
</code>```

答:
Tutorial 25: Efficiently Paging Through Large Amounts of Data</p>

```<code>with cte as (
 SELECT ...,
  ROW_NUMBER () OVER (ORDER BY ...) as rn
 FROM ...)
SELECT ... FROM cte
WHERE rn BETWEEN 500 and 600;
</code>```

Body:
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)

Body:
Tutorial 25: Efficiently Paging Through Large Amounts of Data

with cte as (
 SELECT ...,
  ROW_NUMBER () OVER (ORDER BY ...) as rn
 FROM ...)
SELECT ... FROM cte
WHERE rn BETWEEN 500 and 600;

ContentLicense: CC BY-SA 2.5


问:
AngularJS ng-repeat update does not apply when object keys stay the same?
I'm trying to make a minimal but fancy AngularJS tutorial example, and I am running into an issue where after updating the entire tree for a model (inside the scope of an ng-change update), a template that is driven by a top-level ng-repeat is not re-rendered at all.

However, if I add the code $scope.data = {} at a strategic place, it starts working; but then the display flashes instead of being nice and smooth.  And it's not a great example of how AngularJS automatic data binding works.

What am I missing; and what would be the right fix?

Exact code - select a country from the dropdown -
This jsFiddle does not work: http://jsfiddle.net/f9zxt36g/
This jsFiddle works but flickers: http://jsfiddle.net/y090my10/

```<code>var app = angular.module('factbook', []);
app.controller('loadfact', function($scope, $http) {
  $scope.country = 'europe/uk';
  $scope.safe = function safe(name) { // Makes a safe CSS class name
    return name.replace(/[_\W]+/g, '_').toLowerCase();
  };
  $scope.trunc = function trunc(text) { // Truncates text to 500 chars
    return (text.length < 500) ? text : text.substr(0, 500) + "...";
  };
  $scope.update = function() { // Handles country selection
    // $scope.data = {}; // uncomment to force rednering; an angular bug?
    $http.get('https://rawgit.com/opendatajson/factbook.json/master/' +
        $scope.country + '.json').then(function(response) {
      $scope.data = response.data;
    });
  };
  $scope.countries = [
    {id: 'europe/uk', name: 'UK'},
    {id: 'africa/eg', name: 'Egypt'},
    {id: 'east-n-southeast-asia/ch', name: 'China'}
  ];
  $scope.update();
});
</code>```

The template is driven by ng-repeat:

```<code><div ng-app="factbook" ng-controller="loadfact">
  <select ng-model="country" ng-change="update()"
      ng-options="item.id as item.name for item in countries">
  </select>
  <div ng-repeat="(heading, section) in data"
       ng-init="depth = 1"
       ng-include="'recurse.template'"></div>
  <!-- A template for nested sections with heading and body parts -->
  <script type="text/ng-template" id="recurse.template">
    <div ng-if="section.text"
         class="level{{depth}} section fact ng-class:safe(heading);">
      <div class="level{{depth}} heading factname">{{heading}}</div>
      <div class="level{{depth}} body factvalue">{{trunc(section.text)}}</div>
    </div>
    <div ng-if="!section.text"
         class="level{{depth}} section ng-class:safe(heading);">
      <div class="level{{depth}} heading">{{heading}}</div>
      <div ng-repeat="(heading, body) in section"
           ng-init="depth = depth+1; section = body;"
           ng-include="'recurse.template'"
           class="level{{depth-1}} body"></div>
    </div>
  </script>
</div>
</code>```

What am I missing?

答:
Thanks to Apperion and anoop for their analysis.  I have narrowed down the problem, and the upshot is that there seems to be a buggy interaction between ng-repeat and ng-init which prevents updates from being applied when a repeated variable is copied in ng-init.  Here is a minimized example that shows the problem without using any recursion or includes or shadowing.  https://jsfiddle.net/7sqk02m6/

```<code><div ng-app="app" ng-controller="c">
  <select ng-model="choice" ng-change="update()">
    <option value="">Choose X or Y</option>
    <option value="X">X</option>
    <option value="Y">Y</option>
  </select>
  <div ng-repeat="(key, val) in data" ng-init="copy = val">
    <span>{{key}}:</span> <span>val is {{val}}</span>  <span>copy is {{copy}}</span>
  </div>
</div>
</code>```

The controller code just switches the data between "X" and "Y" and empty versions:

```<code>var app = angular.module('app', []);
app.controller('c', function($scope) {
  $scope.choice = '';
  $scope.update = function() {
    $scope.data = {
      X: { first: 'X1', second: 'X2' },
      Y: { first: 'Y1', second: 'Y2' },
      "": {}
    }[$scope.choice];
  };
  $scope.update();
});
</code>```

Notice that {{copy}} and {{val}} should behave the same inside the loop, because copy is just a copy of val.  They are just strings like 'X1'.  And indeed, the first time you select 'X', it works great - the copies are made, they follow the looping variable and change values through the loop.  The val and the copy are the same.

```<code>first: val is X1 copy is X1
second: val is X2 copy is X2
</code>```

But when you update to the 'Y' version of the data, the {{val}} variables update to the Y version but the {{copy}} values do not update: they stay as X versions.

```<code>first: val is Y1 copy is X1
second: val is Y2 copy is X2
</code>```

Similarly, if you clear everything and start with 'Y', then update to 'X', the copies get stuck as the Y versions.

The upshot is: ng-init seems to fail to set up watchers correctly somehow when looped variables are copied in this situation.  I could not follow Angular internals well enough to understand where the bug is. But avoiding ng-init solves the problem.  A version of the original example that works well with no flicker is here: http://jsfiddle.net/cjtuyw5q/

Body:
I'm trying to make a minimal but fancy AngularJS tutorial example, and I am running into an issue where after updating the entire tree for a model (inside the scope of an ng-change update), a template that is driven by a top-level ng-repeat is not re-rendered at all.

However, if I add the code $scope.data = {} at a strategic place, it starts working; but then the display flashes instead of being nice and smooth.  And it's not a great example of how AngularJS automatic data binding works.

What am I missing; and what would be the right fix?

Exact code - select a country from the dropdown -
This jsFiddle does not work: http://jsfiddle.net/f9zxt36g/
This jsFiddle works but flickers: http://jsfiddle.net/y090my10/

var app = angular.module('factbook', []);
app.controller('loadfact', function($scope, $http) {
  $scope.country = 'europe/uk';
  $scope.safe = function safe(name) { // Makes a safe CSS class name
    return name.replace(/[_\W]+/g, '_').toLowerCase();
  };
  $scope.trunc = function trunc(text) { // Truncates text to 500 chars
    return (text.length < 500) ? text : text.substr(0, 500) + "...";
  };
  $scope.update = function() { // Handles country selection
    // $scope.data = {}; // uncomment to force rednering; an angular bug?
    $http.get('https://rawgit.com/opendatajson/factbook.json/master/' +
        $scope.country + '.json').then(function(response) {
      $scope.data = response.data;
    });
  };
  $scope.countries = [
    {id: 'europe/uk', name: 'UK'},
    {id: 'africa/eg', name: 'Egypt'},
    {id: 'east-n-southeast-asia/ch', name: 'China'}
  ];
  $scope.update();
});

The template is driven by ng-repeat:

  <select ng-model="country" ng-change="update()"
      ng-options="item.id as item.name for item in countries">
  </select>

What am I missing?

Body:
Thanks to Apperion and anoop for their analysis.  I have narrowed down the problem, and the upshot is that there seems to be a buggy interaction between ng-repeat and ng-init which prevents updates from being applied when a repeated variable is copied in ng-init.  Here is a minimized example that shows the problem without using any recursion or includes or shadowing.  https://jsfiddle.net/7sqk02m6/

<div ng-app="app" ng-controller="c">
  <select ng-model="choice" ng-change="update()">
    <option value="">Choose X or Y</option>
    <option value="X">X</option>
    <option value="Y">Y</option>
  </select>
  <div ng-repeat="(key, val) in data" ng-init="copy = val">
    <span>{{key}}:</span> <span>val is {{val}}</span>  <span>copy is {{copy}}</span>
  </div>
</div>

The controller code just switches the data between "X" and "Y" and empty versions:

var app = angular.module('app', []);
app.controller('c', function($scope) {
  $scope.choice = '';
  $scope.update = function() {
    $scope.data = {
      X: { first: 'X1', second: 'X2' },
      Y: { first: 'Y1', second: 'Y2' },
      "": {}
    }[$scope.choice];
  };
  $scope.update();
});

Notice that {{copy}} and {{val}} should behave the same inside the loop, because copy is just a copy of val.  They are just strings like 'X1'.  And indeed, the first time you select 'X', it works great - the copies are made, they follow the looping variable and change values through the loop.  The val and the copy are the same.

first: val is X1 copy is X1
second: val is X2 copy is X2

But when you update to the 'Y' version of the data, the {{val}} variables update to the Y version but the {{copy}} values do not update: they stay as X versions.

first: val is Y1 copy is X1
second: val is Y2 copy is X2

Similarly, if you clear everything and start with 'Y', then update to 'X', the copies get stuck as the Y versions.

The upshot is: ng-init seems to fail to set up watchers correctly somehow when looped variables are copied in this situation.  I could not follow Angular internals well enough to understand where the bug is. But avoiding ng-init solves the problem.  A version of the original example that works well with no flicker is here: http://jsfiddle.net/cjtuyw5q/


问:
Creating an array of integers from argv in C
its going to be quite obvious I am brand new to this but I am taking the CS50 course and I'm having a hard time with one of my assignments. I thought this would be simple but there is something flawed in my syntax causing runtime errors.
I am trying to create an array using each character from a command line argument as elements for the array but nothing I try seems to work. Here's the chunk that's tripping me up:

```<code>#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    //make sure only 2 command line arguments entered
    if( argc != 2)
        {
        printf("Please input a keyword composing of letters only\n");
        return 1;
        }
     else
     {
         // declare variable "m" to designate the number of elements in the array "keyword"
        int m = strlen(argv[1]);
        //array declaration for "keyword" with "m" elements
        int keyword[m];
        //convert characters to integers
        keyword[m] = atoi(argv[1]);
        //iterate through characters in argv[1] in order to printf the elements in the array
        for (int j = 0; j < strlen(argv[1]); j++)
        printf("%i",keyword[j]);
     }
}
</code>```

So, I know this is really really wrong but can someone point me in the right direction?

答:
I'm not sure i correctly understood what you want to do, but if you only want to extract from a number given in parameter of your program each figure composing it you can do it like that</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char** argv)
{
    //make sure only 2 command line arguments entered
    if( argc != 2)
        {
        printf("Please input a keyword composing of letters only\n");
        return 1;
        }
     else
     {
         // declare variable "m" to designate the number of elements in the array "keyword"
        int m = strlen(argv[1]);
        //array declaration for "keyword" with "m" elements
        int keyword[m];
        //convert characters to integers
        //iterate through characters in argv[1] in order to printf the elements in the array
        for (int j = 0; j < strlen(argv[1]); j++){
          keyword[j] = argv[1][j] - '0';
          printf("%d\n",keyword[j]);
        }
     }
}
</code>```

Body:
its going to be quite obvious I am brand new to this but I am taking the CS50 course and I'm having a hard time with one of my assignments. I thought this would be simple but there is something flawed in my syntax causing runtime errors.
I am trying to create an array using each character from a command line argument as elements for the array but nothing I try seems to work. Here's the chunk that's tripping me up:

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    //make sure only 2 command line arguments entered
    if( argc != 2)
        {
        printf("Please input a keyword composing of letters only\n");
        return 1;
        }
     else
     {
         // declare variable "m" to designate the number of elements in the array "keyword"
        int m = strlen(argv[1]);
        //array declaration for "keyword" with "m" elements
        int keyword[m];
        //convert characters to integers
        keyword[m] = atoi(argv[1]);
        //iterate through characters in argv[1] in order to printf the elements in the array
        for (int j = 0; j < strlen(argv[1]); j++)
        printf("%i",keyword[j]);
     }
}

So, I know this is really really wrong but can someone point me in the right direction?

Body:
I'm not sure i correctly understood what you want to do, but if you only want to extract from a number given in parameter of your program each figure composing it you can do it like that

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char** argv)
{
    //make sure only 2 command line arguments entered
    if( argc != 2)
        {
        printf("Please input a keyword composing of letters only\n");
        return 1;
        }
     else
     {
         // declare variable "m" to designate the number of elements in the array "keyword"
        int m = strlen(argv[1]);
        //array declaration for "keyword" with "m" elements
        int keyword[m];
        //convert characters to integers
        //iterate through characters in argv[1] in order to printf the elements in the array
        for (int j = 0; j < strlen(argv[1]); j++){
          keyword[j] = argv[1][j] - '0';
          printf("%d\n",keyword[j]);
        }
     }
}


问:
get current SVG stroke value using javascript
I want to get the current 'stroke' value for a particular svg element. This isn't a problem if the value has been set via javascript previously but when it is set by a class I don't seem to be able to get a return value using the following scripts...

```<code>el.getAttribute('stroke') //returns 'null'

el.setAttribute('stroke','red') // the stroke is visibly changed to 'red'

el.getAttribute('stroke') //returns 'red'
</code>```

So how do I go about getting the current value when it is set via a style?

答:
stroke is a CSS property so if you want to see what an element's stroke is no matter how it's been set then this should do it...</p>

```<code>var stroke = window.getComputedStyle(el).getPropertyValue("stroke");
</code>```

Body:
I want to get the current 'stroke' value for a particular svg element. This isn't a problem if the value has been set via javascript previously but when it is set by a class I don't seem to be able to get a return value using the following scripts...

el.getAttribute('stroke') //returns 'null'

el.setAttribute('stroke','red') // the stroke is visibly changed to 'red'

el.getAttribute('stroke') //returns 'red'

So how do I go about getting the current value when it is set via a style?

Body:
stroke is a CSS property so if you want to see what an element's stroke is no matter how it's been set then this should do it...

var stroke = window.getComputedStyle(el).getPropertyValue("stroke");


问:
Errno 13 Permission denied when trying to run wkhtmltopdf

There are similar questions but my set of configuration is not the
  same.I  downloaded the wkhtmltopdf from wkhtmltopdf.org, placed on the
  project folder, i cant figure out why im still getting access denied.

Trying to point django to run the wkhtmltopdf in order to generate a pdf file.

Running NGINX with UNICORN

Using SUPERVISOR

Ubuntu 16

in my unicorn_supervisor log i got:

```<code>Internal Server Error: /invoice/1/pdf
    Traceback (most recent call last):emphasized text
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
        response = get_response(request)
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_respons                                                                                e
        response = self.process_exception_by_middleware(e, request)
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_respons                                                                                e
        response = response.render()
      File "/home/instantuser/app/lib/python3.5/site-packages/django/template/response.py", line 109, in render
        self.content = self.rendered_content
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/views.py", line 78, in rendered_content
        cmd_options=cmd_options
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 186, in render_pdf_from_temp                                                                                late
        cmd_options=cmd_options)
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 124, in convert_to_pdf
        return wkhtmltopdf(pages=filename, **cmd_options)
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 110, in wkhtmltopdf
        return check_output(ck_args, **ck_kwargs)
      File "/usr/lib/python3.5/subprocess.py", line 626, in check_output
        **kwargs).stdout
      File "/usr/lib/python3.5/subprocess.py", line 693, in run
        with Popen(*popenargs, **kwargs) as process:
      File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
        restore_signals, start_new_session)
      File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
        raise child_exception_type(errno_num, err_msg)
    PermissionError: [Errno 13] Permission denied
</code>```

The wkhtmltopdf file:

```<code>-rwxr-xr-x 1 instantuser instantuser 39804584 Nov 22 10:11 wkhtmltopdf
</code>```

Unicorn process:

```<code>instant+  2949  0.1  0.5  70344 23216 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2954  0.3  1.2 171712 51992 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2955  0.3  1.2 171704 51936 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2957  0.3  1.2 171568 51960 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
ubuntu    2970  0.0  0.0  12944   964 pts/0    S+   18:53   0:00 grep --color=auto unicorn
</code>```

NGINX Process

```<code>root      3006  0.0  0.0 125112  1460 ?        Ss   18:55   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data  3007  0.0  0.0 125436  3108 ?        S    18:55   0:00 nginx: worker process
www-data  3008  0.0  0.1 125712  5060 ?        S    18:55   0:00 nginx: worker process
ubuntu    3104  0.0  0.0  12944   940 pts/0    S+   19:09   0:00 grep --color=auto nginx
</code>```

Why am I getting access denied since the wkhtmltopdf file owner is the same running unicorn?

I'm able to run the command in the terminal but python cant run it. why?

答:
Just use
    sudo su
or
    sudo command
That will run it as superuser and bypass all permissions. I the case that you Don't have access to superuser, I am not sure. This sometimes happens to me when I am trying to run something that is not supposed to be ran. Though I use ubuntu 14.04, so I don't understand this as well as others might.</p>

Body:
There are similar questions but my set of configuration is not the
  same.I  downloaded the wkhtmltopdf from wkhtmltopdf.org, placed on the
  project folder, i cant figure out why im still getting access denied.

Trying to point django to run the wkhtmltopdf in order to generate a pdf file.

Running NGINX with UNICORN

Using SUPERVISOR

Ubuntu 16

in my unicorn_supervisor log i got:

Internal Server Error: /invoice/1/pdf
    Traceback (most recent call last):emphasized text
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
        response = get_response(request)
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_respons                                                                                e
        response = self.process_exception_by_middleware(e, request)
      File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_respons                                                                                e
        response = response.render()
      File "/home/instantuser/app/lib/python3.5/site-packages/django/template/response.py", line 109, in render
        self.content = self.rendered_content
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/views.py", line 78, in rendered_content
        cmd_options=cmd_options
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 186, in render_pdf_from_temp                                                                                late
        cmd_options=cmd_options)
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 124, in convert_to_pdf
        return wkhtmltopdf(pages=filename, **cmd_options)
      File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 110, in wkhtmltopdf
        return check_output(ck_args, **ck_kwargs)
      File "/usr/lib/python3.5/subprocess.py", line 626, in check_output
        **kwargs).stdout
      File "/usr/lib/python3.5/subprocess.py", line 693, in run
        with Popen(*popenargs, **kwargs) as process:
      File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
        restore_signals, start_new_session)
      File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
        raise child_exception_type(errno_num, err_msg)
    PermissionError: [Errno 13] Permission denied

The wkhtmltopdf file:

-rwxr-xr-x 1 instantuser instantuser 39804584 Nov 22 10:11 wkhtmltopdf

Unicorn process:

instant+  2949  0.1  0.5  70344 23216 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2954  0.3  1.2 171712 51992 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2955  0.3  1.2 171704 51936 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
instant+  2957  0.3  1.2 171568 51960 ?        S    18:51   0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=-
ubuntu    2970  0.0  0.0  12944   964 pts/0    S+   18:53   0:00 grep --color=auto unicorn

NGINX Process

root      3006  0.0  0.0 125112  1460 ?        Ss   18:55   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data  3007  0.0  0.0 125436  3108 ?        S    18:55   0:00 nginx: worker process
www-data  3008  0.0  0.1 125712  5060 ?        S    18:55   0:00 nginx: worker process
ubuntu    3104  0.0  0.0  12944   940 pts/0    S+   19:09   0:00 grep --color=auto nginx

Why am I getting access denied since the wkhtmltopdf file owner is the same running unicorn?

I'm able to run the command in the terminal but python cant run it. why?


问:
Is it possible to pot a line chart of date vs time in ChartJS?
I am trying to plot a line chart of date vs time using the following code:

```<code>var canvas = document.getElementById("lineChart");
data = JSON.parse('JSON string');

var myLineChart = new Chart(canvas, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                type: 'time',
                time: {parser: 'HH:mm'}
                }],
            xAxes: [{
                type: 'time',
                time: {parser: 'YYYY-MM-DD'}
                }],
        },
    }
});
</code>```

Is this possible? Should I convert the HH:mm to milliseconds instead?

UPDATE

Chrome console error:

```<code>Uncaught TypeError: Cannot read property 'undefined' of undefined
    at i.getLabelMoment (Chart.min.js:14)
    at i.getPixelForValue (Chart.min.js:14)
    at i.update (Chart.min.js:11)
    at i.reset (Chart.min.js:12)
    at Chart.min.js:12
    at Object.s.each (Chart.min.js:12)
    at t.Controller.resetElements (Chart.min.js:12)
    at t.Controller.initialize (Chart.min.js:12)
    at new t.Controller (Chart.min.js:12)
    at new t (Chart.min.js:12)
</code>```

答:
Unfortunately it is not possible to use a time scale on both the x and y axis.  Per the api docs...

The time scale is used to display times and dates. It can only be placed on the X axis.

If you really need to do this (I'm having trouble thinking of a use for this), then you could try using a time scale for your X axis and a category scale for your Y axis.

Just generate string values from your date data for the y value in your dataset object ({x: new Date(), y: 'May 2017'}).

Body:
I am trying to plot a line chart of date vs time using the following code:

var canvas = document.getElementById("lineChart");
data = JSON.parse('JSON string');

var myLineChart = new Chart(canvas, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                type: 'time',
                time: {parser: 'HH:mm'}
                }],
            xAxes: [{
                type: 'time',
                time: {parser: 'YYYY-MM-DD'}
                }],
        },
    }
});

Is this possible? Should I convert the HH:mm to milliseconds instead?

UPDATE

Chrome console error:

Uncaught TypeError: Cannot read property 'undefined' of undefined
    at i.getLabelMoment (Chart.min.js:14)
    at i.getPixelForValue (Chart.min.js:14)
    at i.update (Chart.min.js:11)
    at i.reset (Chart.min.js:12)
    at Chart.min.js:12
    at Object.s.each (Chart.min.js:12)
    at t.Controller.resetElements (Chart.min.js:12)
    at t.Controller.initialize (Chart.min.js:12)
    at new t.Controller (Chart.min.js:12)
    at new t (Chart.min.js:12)


问:
JS - Why must I predefine the key for a hash counter?
I've been fiddling with a hash counter in js, and I'm having trouble understanding why predefining the key to be null makes the accumulator work.

var totCounts = {};
Object.keys(repoCollection).forEach((x) => {
    Object.keys(repoCollection[x]).forEach((y) => {
        // If I remove this totCounts becomes a collection of Nans
        // why do I need this
        if(!totCounts[y]){
            console.log('undef');
            totCounts[y] = null;
        }
        totCounts[y] += repoCollection[x][y]
    });
});
```

<p>repoCollection looks like this, in this case many times abbreviated:</p>

```{
  "HSchmale16/AccelLib": {
    "C++": 4915,
    "Arduino": 1580,
    "Makefile": 786
  },
  "HSchmale16/better-nfsn-dotfiles": {
    "Shell": 459,
    "VimL": 241
  },
  "HSchmale16/CustomComputerChair": {
    "C": 62477,
    "C++": 52760,
    "Assembly": 11862,
    "Eagle": 10410,
    "Prolog": 1297,
    "Arduino": 500,
    "Shell": 120
  },
  "HSchmale16/CalculusProject": {
    "C++": 7661,
    "TeX": 5870,
    "Makefile": 828
  },
  "HSchmale16/econsim": {},
  "HSchmale16/BoostVpthread": {
    "C++": 2527,
    "Perl": 2124,
    "Makefile": 770
  },
  "HSchmale16/ConsoleMP": {
    "C": 12525,
    "Shell": 2109,
    "C++": 1854,
    "Makefile": 1359
  },
  "HSchmale16/ElectronChargeSim": {
    "C++": 14588,
    "C": 3188,
    "Makefile": 736
  },
  "HSchmale16/GenericMakefile": {
    "Makefile": 12223,
    "C++": 164,
    "C": 147
  }
}
```

答:
Because a number plus undefined is NaN, but a number plus null is the number. JS coerces null into 0, but undefined into NaN.

See What exactly is Type Coercion in Javascript? for more information.

console.log( undefined + 1 );
console.log( null + 1 );```

It'd make more sense to initialize your value to 0 instead of null, but JS treats them the same (in this scenario).

Body:
I've been fiddling with a hash counter in js, and I'm having trouble understanding why predefining the key to be null makes the accumulator work.

var totCounts = {};
Object.keys(repoCollection).forEach((x) => {
    Object.keys(repoCollection[x]).forEach((y) => {
        // If I remove this totCounts becomes a collection of Nans
        // why do I need this
        if(!totCounts[y]){
            console.log('undef');
            totCounts[y] = null;
        }
        totCounts[y] += repoCollection[x][y]
    });
});

repoCollection looks like this, in this case many times abbreviated:

{
  "HSchmale16/AccelLib": {
    "C++": 4915,
    "Arduino": 1580,
    "Makefile": 786
  },
  "HSchmale16/better-nfsn-dotfiles": {
    "Shell": 459,
    "VimL": 241
  },
  "HSchmale16/CustomComputerChair": {
    "C": 62477,
    "C++": 52760,
    "Assembly": 11862,
    "Eagle": 10410,
    "Prolog": 1297,
    "Arduino": 500,
    "Shell": 120
  },
  "HSchmale16/CalculusProject": {
    "C++": 7661,
    "TeX": 5870,
    "Makefile": 828
  },
  "HSchmale16/econsim": {},
  "HSchmale16/BoostVpthread": {
    "C++": 2527,
    "Perl": 2124,
    "Makefile": 770
  },
  "HSchmale16/ConsoleMP": {
    "C": 12525,
    "Shell": 2109,
    "C++": 1854,
    "Makefile": 1359
  },
  "HSchmale16/ElectronChargeSim": {
    "C++": 14588,
    "C": 3188,
    "Makefile": 736
  },
  "HSchmale16/GenericMakefile": {
    "Makefile": 12223,
    "C++": 164,
    "C": 147
  }
}

Body:
Because a number plus undefined is NaN, but a number plus null is the number. JS coerces null into 0, but undefined into NaN.

See What exactly is Type Coercion in Javascript? for more information.

console.log( undefined + 1 );
console.log( null + 1 );

It'd make more sense to initialize your value to 0 instead of null, but JS treats them the same (in this scenario).


问:
Python Turtle draw centered square
I need to draw a square given a center point using the turtle module.

```<code>def drawCentSq(t,center,side):
    xPt=center[0]
    yPt=center[1]
    xPt-=int(side/side)
    yPt+=int(side/side)
    t.up()
    t.goto(xPt,yPt)
    t.down()
    for i in range(4):
        t.forward(side)
        t.right(90)
</code>```

def main():

```<code>import turtle
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawCentSq(mad,(0,0),50))
main()
</code>```

I'm having a hard time making my turtle go to the right starting point.

答:
I need to draw a square given a center point using the turtle module.

As @seth notes, you can do this by fixing the center calculation in your code:

```<code>from turtle import Turtle, Screen

def drawCentSq(turtle, center, side):

    """ A square is a series of perpendicular sides """

    xPt, yPt = center

    xPt -= side / 2
    yPt += side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.down()

    for _ in range(4):
        turtle.forward(side)
        turtle.right(90)

yertle = Turtle()

drawCentSq(yertle, (0, 0), 50)

screen = Screen()
screen.exitonclick()
</code>```

But let's step back and consider how else we can draw a square at a given point of a given size.  Here's a completely different solution:

```<code>def drawCentSq(turtle, center, side):

    """ A square is a circle drawn at a rough approximation """

    xPt, yPt = center

    xPt -= side / 2
    yPt -= side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.right(45)
    turtle.down()

    turtle.circle(2**0.5 * side / 2, steps=4)

    turtle.left(45)  # return cursor to original orientation
</code>```

And here's yet another:

```<code>STAMP_UNIT = 20

def drawCentSq(turtle, center, side):

    """ A square can be stamped directly from a square cursor """

    mock = turtle.clone()  # clone turtle to avoid cleaning up changes
    mock.hideturtle()
    mock.shape("square")
    mock.fillcolor("white")
    mock.shapesize(side / STAMP_UNIT)

    mock.up()
    mock.goto(center)

    return mock.stamp()
</code>```

Note that this solution returns a stamp ID that you can pass to yertle's clearstamp() method to remove the square from the screen if/when you wish.

Title: Python Turtle draw centered square

Body:
I need to draw a square given a center point using the turtle module.

def drawCentSq(t,center,side):
    xPt=center[0]
    yPt=center[1]
    xPt-=int(side/side)
    yPt+=int(side/side)
    t.up()
    t.goto(xPt,yPt)
    t.down()
    for i in range(4):
        t.forward(side)
        t.right(90)

def main():

import turtle
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawCentSq(mad,(0,0),50))
main()

I'm having a hard time making my turtle go to the right starting point.

Body:
I need to draw a square given a center point using the turtle module.

As @seth notes, you can do this by fixing the center calculation in your code:

from turtle import Turtle, Screen

def drawCentSq(turtle, center, side):

    """ A square is a series of perpendicular sides """

    xPt, yPt = center

    xPt -= side / 2
    yPt += side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.down()

    for _ in range(4):
        turtle.forward(side)
        turtle.right(90)

yertle = Turtle()

drawCentSq(yertle, (0, 0), 50)

screen = Screen()
screen.exitonclick()

But let's step back and consider how else we can draw a square at a given point of a given size.  Here's a completely different solution:

def drawCentSq(turtle, center, side):

    """ A square is a circle drawn at a rough approximation """

    xPt, yPt = center

    xPt -= side / 2
    yPt -= side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.right(45)
    turtle.down()

    turtle.circle(2**0.5 * side / 2, steps=4)

    turtle.left(45)  # return cursor to original orientation

And here's yet another:

STAMP_UNIT = 20

def drawCentSq(turtle, center, side):

    """ A square can be stamped directly from a square cursor """

    mock = turtle.clone()  # clone turtle to avoid cleaning up changes
    mock.hideturtle()
    mock.shape("square")
    mock.fillcolor("white")
    mock.shapesize(side / STAMP_UNIT)

    mock.up()
    mock.goto(center)

    return mock.stamp()

Note that this solution returns a stamp ID that you can pass to yertle's clearstamp() method to remove the square from the screen if/when you wish.


问:
How to speed up floating-point to integer number conversion?
We're doing a great deal of floating-point to integer number conversions in our project. Basically, something like this

```<code>for(int i = 0; i < HUGE_NUMBER; i++)
     int_array[i] = float_array[i];
</code>```

The default C function which performs the conversion turns out to be quite time consuming.

Is there any work around (maybe a hand tuned function) which can speed up the process a little bit? We don't care much about a precision.

答:
The key is to avoid the _ftol() function, which is needlessly slow. Your best bet for long lists of data like this is to use the SSE2 instruction cvtps2dq to convert two packed floats to two packed int64s. Do this twice (getting four int64s across two SSE registers) and you can shuffle them together to get four int32s (losing the top 32 bits of each conversion result). You don't need assembly to do this; MSVC exposes compiler intrinsics to the relevant instructions -- _mm_cvtpd_epi32() if my memory serves me correctly.

If you do this it is very important that your float and int arrays be 16-byte aligned so that the SSE2 load/store intrinsics can work at maximum efficiency. Also, I recommend you software pipeline a little and process sixteen floats at once in each loop, eg (assuming that the "functions" here are actually calls to compiler intrinsics):

```<code>for(int i = 0; i < HUGE_NUMBER; i+=16)
{
//int_array[i] = float_array[i];
   __m128 a = sse_load4(float_array+i+0);
   __m128 b = sse_load4(float_array+i+4);
   __m128 c = sse_load4(float_array+i+8);
   __m128 d = sse_load4(float_array+i+12);
   a = sse_convert4(a);
   b = sse_convert4(b);
   c = sse_convert4(c);
   d = sse_convert4(d);
   sse_write4(int_array+i+0, a);
   sse_write4(int_array+i+4, b);
   sse_write4(int_array+i+8, c);
   sse_write4(int_array+i+12, d);
}
</code>```

The reason for this is that the SSE instructions have a long latency, so if you follow a load into xmm0 immediately with a dependent operation on xmm0 then you will have a stall. Having multiple registers "in flight" at once hides the latency a little. (Theoretically a magic all-knowing compiler could alias its way around this problem but in practice it doesn't.)

Failing this SSE juju you can supply the /QIfist option to MSVC which will cause it to issue the single opcode fist instead of a call to _ftol; this means it will simply use whichever rounding mode happens to be set in the CPU without making sure it is ANSI C's specific truncate op. The Microsoft docs say /QIfist is deprecated because their floating point code is fast now, but a disassembler will show you that this is unjustifiedly optimistic. Even /fp:fast simply results to a call to _ftol_sse2, which though faster than the egregious _ftol is still a function call followed by a latent SSE op, and thus unnecessarily slow.

I'm assuming you're on x86 arch, by the way -- if you're on PPC there are equivalent VMX operations, or you can use the magic-number-multiply trick mentioned above followed by a vsel (to mask out the non-mantissa bits) and an aligned store.

OwnerDisplayName: Serge

Body:
We're doing a great deal of floating-point to integer number conversions in our project. Basically, something like this

for(int i = 0; i < HUGE_NUMBER; i++)
     int_array[i] = float_array[i];

The default C function which performs the conversion turns out to be quite time consuming.

Is there any work around (maybe a hand tuned function) which can speed up the process a little bit? We don't care much about a precision.

LastEditorDisplayName: Jonathan Leffler

Body:
The key is to avoid the _ftol() function, which is needlessly slow. Your best bet for long lists of data like this is to use the SSE2 instruction cvtps2dq to convert two packed floats to two packed int64s. Do this twice (getting four int64s across two SSE registers) and you can shuffle them together to get four int32s (losing the top 32 bits of each conversion result). You don't need assembly to do this; MSVC exposes compiler intrinsics to the relevant instructions -- _mm_cvtpd_epi32() if my memory serves me correctly.

If you do this it is very important that your float and int arrays be 16-byte aligned so that the SSE2 load/store intrinsics can work at maximum efficiency. Also, I recommend you software pipeline a little and process sixteen floats at once in each loop, eg (assuming that the "functions" here are actually calls to compiler intrinsics):

for(int i = 0; i < HUGE_NUMBER; i+=16)
{
//int_array[i] = float_array[i];
   __m128 a = sse_load4(float_array+i+0);
   __m128 b = sse_load4(float_array+i+4);
   __m128 c = sse_load4(float_array+i+8);
   __m128 d = sse_load4(float_array+i+12);
   a = sse_convert4(a);
   b = sse_convert4(b);
   c = sse_convert4(c);
   d = sse_convert4(d);
   sse_write4(int_array+i+0, a);
   sse_write4(int_array+i+4, b);
   sse_write4(int_array+i+8, c);
   sse_write4(int_array+i+12, d);
}

The reason for this is that the SSE instructions have a long latency, so if you follow a load into xmm0 immediately with a dependent operation on xmm0 then you will have a stall. Having multiple registers "in flight" at once hides the latency a little. (Theoretically a magic all-knowing compiler could alias its way around this problem but in practice it doesn't.)

Failing this SSE juju you can supply the /QIfist option to MSVC which will cause it to issue the single opcode fist instead of a call to _ftol; this means it will simply use whichever rounding mode happens to be set in the CPU without making sure it is ANSI C's specific truncate op. The Microsoft docs say /QIfist is deprecated because their floating point code is fast now, but a disassembler will show you that this is unjustifiedly optimistic. Even /fp:fast simply results to a call to _ftol_sse2, which though faster than the egregious _ftol is still a function call followed by a latent SSE op, and thus unnecessarily slow.

I'm assuming you're on x86 arch, by the way -- if you're on PPC there are equivalent VMX operations, or you can use the magic-number-multiply trick mentioned above followed by a vsel (to mask out the non-mantissa bits) and an aligned store.

OwnerDisplayName: Crashworks

LastEditorDisplayName: Crashworks


问:
What's the prime advantage to having an MSI installation package?
I thought this would be somewhere on the Web, but I couldn't Google it:

Given the complexity involved in creating an MSI package (compared to NSIS, InnoSetup, etc.), what would be a compelling reason to go through all the mess (using MSVS's crappy setup project wizard, learn a whole new langauge/ecosystem just to make the installer (WiX), or pay heavy license fees (InstallShield)) for the sake of making an MSI installer?

Would be nice to have real world opinions or experience (even to prove that MSI is really worthless) other than the obvious MSDN page, for instance :)

答:
I don't think there is one prime advantage for all situations.  Here are some things I like about it, vs other kinds of installers:

Install logic and code is contained in a database, which is in an accessible format.
I like this a lot when I'm debugging.  Rather than rebuilding your installer, you can directly edit the database with a tool like Orca (free database editing download from MS), then run the install again to test your changes.  Update your custom code, temporarily condition something out, change the order of operations, whatever you need to do.

Patching.  The Installer service and its corresponding tools know how to create patches containing deltas of updated files, rather than complete files.  It allows maintenance sizes to remain reasonable.

Administrative Images.  The installer can create an administrative image.  If you've generated patches, you can apply the patches to the administrative image, and new installations can then be run from the administrative image rather than the original installer.  Like slipstreaming patches in OS images.  If you're pushing your app out to a large number of machines, it's pretty cool to not need to push a bunch of patches out post-install.

Other interesting features include transforms, run from source, detect and repair, component sharing, and so on.


问:
Properly handling errors with Node/Express
Which is the proper way to return errors with your server in general (node/express) and reject a promise?

A) Like this: res.json({status: 1, message: 'Test missing phone.', error: 'phone'})

And then pull the error 'code' out of error and the message out of messsage on your front end, resulting in a fulfilled promise that has an error and message in it.

B) Like this;

```<code>res.status(500)
res.json({message: 'Test missing phone.'})
</code>```

And then just pull message out and call .reject with the message. Or res.error or something.

Do either of these cause a 'rejected' promise or 'error' callback that would make frontend stuff easier?

Should I be causing promise/callback rejection when I get an error, or just send a fulfilled promise with an error in the object like A?

Which of these is the 'correct' way to return an error from your server to your front end?

Currently I use method A, but it seems pretty dumb because I have to handle the error twice, backend (to actually send the custom error) and frontend (to check if the fulfilled promise has an error object, and then display a popup). Method B would eliminate the 'checking if the fulfilled promise has an error object' part, since a rejected promise is an error by nature.

EDIT: I'm using React Native as frontend.

EDIT2: If you res.status(500).json({test: 'Test missing phone.'}) on your backend you can console.log(error.response.data) on the frontend to make "B" a viable option.

答:
TL;DR Use your "B" method

Depends on what you're using on the front-end. If it's Angular and you're using the $http object for example, the promise will get rejected if there's an error status (for example, a 400 status code) according to the docs.

So to allow the front end to "know" when there's an error automatically (instead of having to do some extra checking to see if the body contains an error message), you should probably go with the res.status() approach on the back-end. HTTP status codes are the model that you should be using for your front-end to know what's going on in the server, and most front-end HTTP libraries are built with this model in mind.

You can send additional info in the body of your response too if you want. You can have custom app code on the front-end that handles more granular error cases. For example, a status of 401 would tell the client that they're unauthorized to do some action on the server, and a body with a code member might further define exactly what the issue was, along with some human-readable description (which you already have as message in your example).

Body:
Which is the proper way to return errors with your server in general (node/express) and reject a promise?

A) Like this: res.json({status: 1, message: 'Test missing phone.', error: 'phone'})

And then pull the error 'code' out of error and the message out of messsage on your front end, resulting in a fulfilled promise that has an error and message in it.

B) Like this;

res.status(500)
res.json({message: 'Test missing phone.'})

And then just pull message out and call .reject with the message. Or res.error or something.

Do either of these cause a 'rejected' promise or 'error' callback that would make frontend stuff easier?

Should I be causing promise/callback rejection when I get an error, or just send a fulfilled promise with an error in the object like A?

Which of these is the 'correct' way to return an error from your server to your front end?

Currently I use method A, but it seems pretty dumb because I have to handle the error twice, backend (to actually send the custom error) and frontend (to check if the fulfilled promise has an error object, and then display a popup). Method B would eliminate the 'checking if the fulfilled promise has an error object' part, since a rejected promise is an error by nature.

EDIT: I'm using React Native as frontend.

EDIT2: If you res.status(500).json({test: 'Test missing phone.'}) on your backend you can console.log(error.response.data) on the frontend to make "B" a viable option.


问:
android camera2 setTorchMode too slow
I am using Camera2 to turn on the Flash Light on my Android phone with the following :

```<code>camManager.setTorchMode(cameraId, true);
</code>```

But the thing is it's really slow (like half a second to open), compared to the iOS flashlight. I can't find any instantaneous flashlight, is it a hardware issue..?

Thanks in advance!

答:
It's a hardware issue.

If the underlying hardware directly supports a enable-torch call at the HAL (hardware abstraction layer) interface, turning the flash on and off is very fast.

But if it doesn't, the Android OS has to actually open a camera device and turn on the flash via the full camera API. And unfortunately, powering on and off the camera is not a quick (or power-efficient) operation.

The needed HAL interfaces for this were added in Android 6.0 along with the setTorchMode API, but since the backwards compatibility code exists in the OS, not all manufacturers have added the necessary HAL implementation for fast flash control.

Title: android camera2 setTorchMode too slow

Body:
I am using Camera2 to turn on the Flash Light on my Android phone with the following :

camManager.setTorchMode(cameraId, true);

But the thing is it's really slow (like half a second to open), compared to the iOS flashlight. I can't find any instantaneous flashlight, is it a hardware issue..?

Thanks in advance!


问:
Android App button press not functioning correctly
Being brand new to Java I'm not sure why this when called with android:onClick="changeInfo" isn't changing the text view back to the original value.

```<code>public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){
    setContentView(R.layout.activity_java_test);
    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText()==getResources().getString(R.string.lorem_ipsum)){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}
</code>```

Could anyone help, thank you.

答: Try removing setContentView(R.layout.activity_java_test); from the changeInfo(View view) method.

Body:
Being brand new to Java I'm not sure why this when called with android:onClick="changeInfo" isn't changing the text view back to the original value.

public class JavaTest extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_java_test);
}
public void changeInfo(View view){
    setContentView(R.layout.activity_java_test);
    TextView t = (TextView)findViewById(R.id.textSpace1);
    if (t.getText()==getResources().getString(R.string.lorem_ipsum)){
        t.setText("[Email Here]");
    }
    else{
        t.setText(getResources().getString(R.string.lorem_ipsum));
    }
}

Could anyone help, thank you.


问:
Error using Box SDK on Azure Functions
I am getting a "Could not load file or assembly 'Box.V2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ddda8fe64dde1ac3' or one of its dependencies. The system cannot find the file specified" error in Azure Functions. Any ideas on what the problem might be?

I am using the package.json file to have Azure Functions pull in the references and hook them all up as described in the docs.

When you upload a project.json file, the runtime gets the packages and automatically adds references to the package assemblies. You don't need to add #r "AssemblyName" directives. Just add the required using statements to your run.csx file to use the types defined in the NuGet packages.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp

My package.json file:

```<code>{
  "frameworks": {
    "net46":{
      "dependencies": {
        "BouncyCastle": "1.8.1",
        "BouncyCastle-PCL": "1.0.0.6",
        "Box.V2": "2.14.0",
        "Box.V2.JWTAuth": "1.2.0",
        "Microsoft.Bcl": "1.1.10",
        "Microsoft.Bcl.Async": "1.0.168",
        "Microsoft.Bcl.Build": "1.0.14",
        "Microsoft.Net.Http": "2.2.29",
        "Newtonsoft.Json": "6.0.2",
        "Nito.AsyncEx": "2.1.3",
        "System.IdentityModel.Tokens.Jwt": "4.0.2.206221351"
      }
    }
  }
}
</code>```

run.csx using statements:

```<code>using global::Box.V2;
using global::Box.V2.Config;
using global::Box.V2.Exceptions;
using global::Box.V2.JWTAuth;
using global::Box.V2.Models;
</code>```

Full Exception:

```<code>Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.GetTelogisFormInstancePdf ---> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException : Could not load file or assembly 'Box.V2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ddda8fe64dde1ac3' or one of its dependencies. The system cannot find the file specified.

   at Submission#0.Run(HttpRequestMessage req,TraceWriter log) at  : 84

   End of inner exception

   at System.RuntimeMethodHandle.InvokeMethod(Object target,Object[] arguments,Signature sig,Boolean constructor)

   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,Object[] parameters,Object[] arguments)

   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object[] parameters,CultureInfo culture)

   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context)

   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.InvokeAsync[TReflected](Object[] arguments)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,Object[] invokeParameters,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,IReadOnlyDictionary`2 parameters,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??…
</code>```

答: This error is misleading and I had to end up overriding BoxJWTAuth in order to make it work.  The details of this error can be found here:  https://github.com/box/box-windows-sdk-v2/issues/297</p>

Title: Error using Box SDK on Azure Functions

Body:
I am getting a "Could not load file or assembly 'Box.V2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ddda8fe64dde1ac3' or one of its dependencies. The system cannot find the file specified" error in Azure Functions. Any ideas on what the problem might be?

I am using the package.json file to have Azure Functions pull in the references and hook them all up as described in the docs.

When you upload a project.json file, the runtime gets the packages and automatically adds references to the package assemblies. You don't need to add #r "AssemblyName" directives. Just add the required using statements to your run.csx file to use the types defined in the NuGet packages.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp

My package.json file:

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "BouncyCastle": "1.8.1",
        "BouncyCastle-PCL": "1.0.0.6",
        "Box.V2": "2.14.0",
        "Box.V2.JWTAuth": "1.2.0",
        "Microsoft.Bcl": "1.1.10",
        "Microsoft.Bcl.Async": "1.0.168",
        "Microsoft.Bcl.Build": "1.0.14",
        "Microsoft.Net.Http": "2.2.29",
        "Newtonsoft.Json": "6.0.2",
        "Nito.AsyncEx": "2.1.3",
        "System.IdentityModel.Tokens.Jwt": "4.0.2.206221351"
      }
    }
  }
}

run.csx using statements:

using global::Box.V2;
using global::Box.V2.Config;
using global::Box.V2.Exceptions;
using global::Box.V2.JWTAuth;
using global::Box.V2.Models;

Full Exception:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.GetTelogisFormInstancePdf ---> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundException : Could not load file or assembly 'Box.V2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ddda8fe64dde1ac3' or one of its dependencies. The system cannot find the file specified.

   at Submission#0.Run(HttpRequestMessage req,TraceWriter log) at  : 84

   End of inner exception

   at System.RuntimeMethodHandle.InvokeMethod(Object target,Object[] arguments,Signature sig,Boolean constructor)

   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj,Object[] parameters,Object[] arguments)

   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object[] parameters,CultureInfo culture)

   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context)

   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.InvokeAsync[TReflected](Object[] arguments)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,Object[] invokeParameters,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,IReadOnlyDictionary`2 parameters,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)

   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??…


问:
SQL Order By within Order By
So I have two tables, Questions and Answers, joined by a many to many relation table, QuestionsAnswers.  Questions have a Sort column that allows me to control how they are displayed to the user, and QuestionsAnswers also has a sort column that allows me to control the order of the answers for each Question.  My problem is that I am trying to write a SQL query that will select all the Questions and their Answers ordered first by Question.Sort and then by QuestionsAnswers.Sort.  Both sort columns are nullable and integers in these columns should take precedence over nulls.

I can get the Order By Questions.Sort to work fine but once I add in the second sort column, it goes awry.  For instance, if a Question has a Sort = 0 meaning it should be the first Question displayed but does not have any preference for its Answers, it will get ordered below a QuestionsAnswers row that has Questions.Sort = null and QuestionsAnswers.Sort = 0.

Any tips or thoughts if this is even workable would be great.

edit:

```<code>SELECT
    Q.Id AS QuestionId,
    Q.Name AS Question,
    A.Id AS AnswerId,
    A.Text AS Answer
FROM
    dbo.Questions AS Q
INNER JOIN
    dbo.QuestionsAnswers AS QA
        ON Q.Id = QA.QuestionId
INNER JOIN
    dbo.Answers AS A
        ON QA.AnswerId = A.Id
ORDER BY
    ISNUMERIC(Q.Sort) DESC,
    Q.Sort,
    Q.Id,
    A.Text;
</code>```

答:
From what I can see something like this should do the trick. Unless I am misssing something.</p>

```<code>select questions.*, answers.*
from questionsanswers qa
inner join questions
    on questions.idquestions = qa.questionid
inner join answers
    on answers.idanswers = qa.answerid
order by isnull(questions.sort), questions.sort, isnull(qa.sort), qa.sort
</code>```

Title: SQL Order By within Order By

Body:
So I have two tables, Questions and Answers, joined by a many to many relation table, QuestionsAnswers.  Questions have a Sort column that allows me to control how they are displayed to the user, and QuestionsAnswers also has a sort column that allows me to control the order of the answers for each Question.  My problem is that I am trying to write a SQL query that will select all the Questions and their Answers ordered first by Question.Sort and then by QuestionsAnswers.Sort.  Both sort columns are nullable and integers in these columns should take precedence over nulls.

I can get the Order By Questions.Sort to work fine but once I add in the second sort column, it goes awry.  For instance, if a Question has a Sort = 0 meaning it should be the first Question displayed but does not have any preference for its Answers, it will get ordered below a QuestionsAnswers row that has Questions.Sort = null and QuestionsAnswers.Sort = 0.

Any tips or thoughts if this is even workable would be great.

edit:

SELECT
    Q.Id AS QuestionId,
    Q.Name AS Question,
    A.Id AS AnswerId,
    A.Text AS Answer
FROM
    dbo.Questions AS Q
INNER JOIN
    dbo.QuestionsAnswers AS QA
        ON Q.Id = QA.QuestionId
INNER JOIN
    dbo.Answers AS A
        ON QA.AnswerId = A.Id
ORDER BY
    ISNUMERIC(Q.Sort) DESC,
    Q.Sort,
    Q.Id,
    A.Text;

Body:
From what I can see something like this should do the trick. Unless I am misssing something.

select questions.*, answers.*
from questionsanswers qa
inner join questions
    on questions.idquestions = qa.questionid
inner join answers
    on answers.idanswers = qa.answerid
order by isnull(questions.sort), questions.sort, isnull(qa.sort), qa.sort


问:
Using Aurelia validation with table
I have a table of rows/columns with input boxes, created like this:

Using this code (simplified):

```<code><table>
  <thead>
    <!-- Column headings -->
    <tr>
      <th repeat.for="column of columns">
        ${column.display}
      </th>
    </tr>
  </thead>

  <tbody>
    <!-- Display all records -->
    <tr repeat.for="record of records">

      <!-- Show all column data for each record -->
      <td repeat.for="column of columns">
        <input type="text" value.bind="record[column.bind] & validate">
      </td>

    </tr>
  </tbody>
</table>
</code>```

I have created a set of rules like this:

```<code>this.rules = ValidationRules
  .ensure("gs_mark").required().minLength(1).maxLength(3)
  .ensure("gs_min").required().minLength(1).maxLength(3)
  .ensure("gs_max").required().minLength(1).maxLength(3)
  .ensure("gs_description").required().minLength(2).maxLength(20)
  .rules;
</code>```

Now I need to apply those rules to the records, so that I can validate all input boxes.

How can I do that?  Should I .map() the records and do this.validationCtrl.addObject(this.record, this.rules); on each one?  Can I somehow set up the validation on the binding of each type of control without the need to apply it to each record?  Am I approaching this the wrong way?

答:
In the end, it seems the way to get it to work is to loop through the records and apply the rules to each row.

```<code>this.records.map((record) => {
  if ((typeof this.rules == 'object') && (this.rules.length)) {
    this.validationCtrl.removeObject(record);
    this.validationCtrl.addObject(record, this.rules);
  }
});
</code>```

Works like a charm!  I'm slightly concerned about the amount of memory this will consume for very large tables, but at least it works!

Title: Using Aurelia validation with table

Body:
I have a table of rows/columns with input boxes, created like this:

Using this code (simplified):

        ${column.display}

        <input type="text" value.bind="record[column.bind] & validate">

I have created a set of rules like this:

this.rules = ValidationRules
  .ensure("gs_mark").required().minLength(1).maxLength(3)
  .ensure("gs_min").required().minLength(1).maxLength(3)
  .ensure("gs_max").required().minLength(1).maxLength(3)
  .ensure("gs_description").required().minLength(2).maxLength(20)
  .rules;

Now I need to apply those rules to the records, so that I can validate all input boxes.

How can I do that?  Should I .map() the records and do this.validationCtrl.addObject(this.record, this.rules); on each one?  Can I somehow set up the validation on the binding of each type of control without the need to apply it to each record?  Am I approaching this the wrong way?

Body:
In the end, it seems the way to get it to work is to loop through the records and apply the rules to each row.

this.records.map((record) => {
  if ((typeof this.rules == 'object') && (this.rules.length)) {
    this.validationCtrl.removeObject(record);
    this.validationCtrl.addObject(record, this.rules);
  }
});

Works like a charm!  I'm slightly concerned about the amount of memory this will consume for very large tables, but at least it works!


问:
How do I get session data in Django?
Basically, what I'm looking for is the Django/Python equivalent to the PHP

```<code>session_start();
print_R($_SESSION);
</code>```

That is, I'd like to dump all the information I currently have stored in the session so I can see what's in there.

答:
The session is a dict-like object so you can simply print request.session to see what's in it.

The output will show up on the console of the server when using the development server - usually that's actually much better than print_r in PHP which dumps it to the webbrowser, next to whatever HTML you might have.

However, you could also return HttpResponse(repr(request.session)) if you do want to send it to the browser.

Title: How do I get session data in Django?

Body:
Basically, what I'm looking for is the Django/Python equivalent to the PHP

session_start();
print_R($_SESSION);

That is, I'd like to dump all the information I currently have stored in the session so I can see what's in there.