问:
Android MultiDex app crashing on low APIs on Android Studio 3.0
I was trying to run an app that requires MultiDex using Android Studio 3.0 on an API 16 device and when the app is finally trying to launch, it crashes.
The same occurs on other low APIs (eg.: 17, 18, 19)

But, when I tried to run the app using the Android Studio 3.1 (beta version), no crashes occur.

Is there any way this crash can be fixed?

```<code>   FATAL EXCEPTION: main
  java.lang.ExceptionInInitializerError
      at android.support.multidex.MultiDexApplication.<init>(MultiDexApplication.java:35)
      at MY_APP_PATH.MY_CUSTOM_APPLICATION_CLASS.<init>(MY_CUSTOM_APP_CLASS.java:23)
      at java.lang.Class.newInstanceImpl(Native Method)
      at java.lang.Class.newInstance(Class.java:1319)
      at android.app.Instrumentation.newApplication(Instrumentation.java:997)
      at android.app.Instrumentation.newApplication(Instrumentation.java:982)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4170)
      at android.app.ActivityThread.access$1400(ActivityThread.java:134)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4867)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
      at dalvik.system.NativeStart.main(Native Method)
   Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1306]:  1674 cannot locate '__isnanf'...

      at java.lang.Runtime.loadLibrary(Runtime.java:370)
      at java.lang.System.loadLibrary(System.java:535)
      at com.android.tools.profiler.support.ProfilerService.<clinit>(ProfilerService.java:41)
      at android.support.multidex.MultiDexApplication.<init>(MultiDexApplication.java:35)
      at MY_APP_PATH.MY_CUSTOM_APPLICATION_CLASS.<init>(MY_CUSTOM_APPLICATION_CLASS.java:23)
      at java.lang.Class.newInstanceImpl(Native Method)
      at java.lang.Class.newInstance(Class.java:1319)
      at android.app.Instrumentation.newApplication(Instrumentation.java:997)
      at android.app.Instrumentation.newApplication(Instrumentation.java:982)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4170)
      at android.app.ActivityThread.access$1400(ActivityThread.java:134)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4867)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
      at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
Issue should be about enabling "advanced profiling" feature in AS 3.0, if you've done so just disable it:

Go to "Edit Configurations...",

Select your app configuration under "Android App",

Then go "Profiling" tab and

Uncheck "Enable advanced profiling"

Problem should be gone.

Body:
I was trying to run an app that requires MultiDex using Android Studio 3.0 on an API 16 device and when the app is finally trying to launch, it crashes.
The same occurs on other low APIs (eg.: 17, 18, 19)

But, when I tried to run the app using the Android Studio 3.1 (beta version), no crashes occur.

Is there any way this crash can be fixed?

   FATAL EXCEPTION: main
  java.lang.ExceptionInInitializerError
      at android.support.multidex.MultiDexApplication.<init>(MultiDexApplication.java:35)
      at MY_APP_PATH.MY_CUSTOM_APPLICATION_CLASS.<init>(MY_CUSTOM_APP_CLASS.java:23)
      at java.lang.Class.newInstanceImpl(Native Method)
      at java.lang.Class.newInstance(Class.java:1319)
      at android.app.Instrumentation.newApplication(Instrumentation.java:997)
      at android.app.Instrumentation.newApplication(Instrumentation.java:982)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4170)
      at android.app.ActivityThread.access$1400(ActivityThread.java:134)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4867)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
      at dalvik.system.NativeStart.main(Native Method)
   Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1306]:  1674 cannot locate '__isnanf'...

      at java.lang.Runtime.loadLibrary(Runtime.java:370)
      at java.lang.System.loadLibrary(System.java:535)
      at com.android.tools.profiler.support.ProfilerService.<clinit>(ProfilerService.java:41)
      at android.support.multidex.MultiDexApplication.<init>(MultiDexApplication.java:35)
      at MY_APP_PATH.MY_CUSTOM_APPLICATION_CLASS.<init>(MY_CUSTOM_APPLICATION_CLASS.java:23)
      at java.lang.Class.newInstanceImpl(Native Method)
      at java.lang.Class.newInstance(Class.java:1319)
      at android.app.Instrumentation.newApplication(Instrumentation.java:997)
      at android.app.Instrumentation.newApplication(Instrumentation.java:982)
      at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
      at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4170)
      at android.app.ActivityThread.access$1400(ActivityThread.java:134)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4867)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
      at dalvik.system.NativeStart.main(Native Method)


来源: stackexchange

问:
Detect Android orientation: landscape-Left v. landscape-Right
How can I detect which one of 4 sides of the phone is up.

I can detect portrait/landscape mode, but how do I tell landscape-turned-on-left-side from landscape-turned-on-right-side?

Basically I want to make a nice transition animation when user turns phone. You know, like in iPhone's Safari: a swift 400ms rotation from the previous layout to the new.

答:
Use an OrientationEventListener:

```<code>mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL)
{
 @Override
 public void onOrientationChanged(int orientation)
 {
  mDeviceOrientation = orientation;
 }
};

if(mOrientationEventListener.canDetectOrientation())
{
 mOrientationEventListener.enable();
}
</code>```

mDeviceOrientation should then be an integer telling you the angle your device is rotated to, if you do some clever rounding you should be able to see which of the four orientations it is in:

```<code>// Divide by 90 into an int to round, then multiply out to one of 5 positions, either 0,90,180,270,360.
int orientation = 90*Math.round(mDeviceOrientation / 90);

// Convert 360 to 0
if(orientation == 360)
{
    orientation = 0;
}
</code>```

Enjoy!

ContentLicense: CC BY-SA 2.5

Body:
Use an OrientationEventListener:

mOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL)
{
 @Override
 public void onOrientationChanged(int orientation)
 {
  mDeviceOrientation = orientation;
 }
};

if(mOrientationEventListener.canDetectOrientation())
{
 mOrientationEventListener.enable();
}

mDeviceOrientation should then be an integer telling you the angle your device is rotated to, if you do some clever rounding you should be able to see which of the four orientations it is in:

// Divide by 90 into an int to round, then multiply out to one of 5 positions, either 0,90,180,270,360.
int orientation = 90*Math.round(mDeviceOrientation / 90);

// Convert 360 to 0
if(orientation == 360)
{
    orientation = 0;
}

Enjoy!


问:
ClassCastException writing a Gephi plugin
I am trying to write a plugin for Gephi and get the following error message:

```<code>java.lang.ClassCastException: org.gephi.graph.impl.GraphStore$NodeIterableWrapper cannot be cast to org.gephi.graph.api.Node at org.............execute(.....java:92)
</code>```

The code in which the error occurred:

```<code>Node[] nodes = graph.getNodes().toArray();
for (Node n: nodes){
    .....
    List<Node> neighborNodes = new LinkedList<Node>();
    for(Node m: nodes){
        NodeIterable iter = graph.getNeighbors(m);
        neighborNodes.add((Node) iter);
</code>```

The last line causes the error. Is it possible via NodeIterable to insert the neighbors as nodes in the list neighborNodes without this cast? I'm new to writing Java plugins.

答:
According to this javadoc, NodeIterable is an Iterable of Nodes.

So you probably should use a loop:

```<code>NodeIterable iter = graph.getNeighbors(m);
for (Node n: iter) {
    neighborNodes.add(n);
}
</code>```

or addAll and toCollection:

```<code>NodeIterable iter = graph.getNeighbors(m);
neighborNodes.addAll(iter.toCollection());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a plugin for Gephi and get the following error message:

java.lang.ClassCastException: org.gephi.graph.impl.GraphStore$NodeIterableWrapper cannot be cast to org.gephi.graph.api.Node at org.............execute(.....java:92)

The code in which the error occurred:

Node[] nodes = graph.getNodes().toArray();
for (Node n: nodes){
    .....
    List<Node> neighborNodes = new LinkedList<Node>();
    for(Node m: nodes){
        NodeIterable iter = graph.getNeighbors(m);
        neighborNodes.add((Node) iter);

The last line causes the error. Is it possible via NodeIterable to insert the neighbors as nodes in the list neighborNodes without this cast? I'm new to writing Java plugins.

Body:
According to this javadoc, NodeIterable is an Iterable of Nodes.

So you probably should use a loop:

NodeIterable iter = graph.getNeighbors(m);
for (Node n: iter) {
    neighborNodes.add(n);
}

or addAll and toCollection:

NodeIterable iter = graph.getNeighbors(m);
neighborNodes.addAll(iter.toCollection());


问:
Sort by variables in dropdown from php variables
I have a dropdown/sort select list with 2 options Popularity and Recently Ordered.

I want to filter objects on the page by these attributes and I want to connect the two options in my select to respective functions in my dataloader.php file.

The functions are below but I want to connect $ofpg->reorder to recently ordered and $ofpg->topseller to popularity, but I'm not sure how exactly to load these to my select box and attach JS to sort by. Basically I just want to use JS to reorder the items on the page by these items, but I need some guidance to get started.

Here's the code:

My dropdown/sort by:

```<code><div style="text-align:center;">
   <div>
    <span style="color:#fff;"><strong>Sort by:</strong></span>
    <select class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
    <option class="uk-text-muted" style="font-size: 16px;" value="" selected data-default>Popularity</option>
    <option class="uk-text-muted" style="font-size: 16px;" value="">Recently Ordered</option>
    </select>
   </div>
</div>
</code>```

Top seller and recent order functions:

```<code>$ofpg = new OfDataProductGroup();
        $ofpg->group_code = trim($group['groupCode']);
        $ofpg->group_name = $group['groupName'];
        $ofpg->group_desc = $group['webDsc'];
        $ofpg->ctg = $group['ctg'];

        $ofpg->topseller = 0;
        $ofpg->reorder = 0;

        if($this->reorder){
            foreach($this->reorder as $i){

                if(trim($group['groupCode']) == $i->STYLE){
                    $ofpg->reorder = 1;
                    continue;
                }
            }
        }
        if($this->topsellers){

            foreach($this->topsellers as $i){
                $aa = json_decode($i->metadata);
                $s = $aa->style[0]->prdgroup;
                if(trim($group['groupCode']) == $s){
                    $ofpg->topseller = 1;
                    continue;
                }
            }
        }
</code>```

答:
Something that might work is using an if statement and put continue; within it on the top of your foreach.

Something like:

```<code>foreach($aa as $a)
{
   if($a != $something) // or use ($a == $something), just whatever you need.
   {
      continue;
   }

echo $a;
}
</code>```

In the situation above you use a foreach to do something with every key from your array. But on top of this foreach you have an if statement. The if statement will only show the result if it matches the requirement, otherwise it will do nothing and continues to the next key.

EDIT:
This is written in PHP, not in JS.

Body:
I have a dropdown/sort select list with 2 options Popularity and Recently Ordered.

I want to filter objects on the page by these attributes and I want to connect the two options in my select to respective functions in my dataloader.php file.

The functions are below but I want to connect $ofpg->reorder to recently ordered and $ofpg->topseller to popularity, but I'm not sure how exactly to load these to my select box and attach JS to sort by. Basically I just want to use JS to reorder the items on the page by these items, but I need some guidance to get started.

Here's the code:

My dropdown/sort by:

    Sort by:
    <select class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
    <option class="uk-text-muted" style="font-size: 16px;" value="" selected data-default>Popularity</option>
    <option class="uk-text-muted" style="font-size: 16px;" value="">Recently Ordered</option>
    </select>

Top seller and recent order functions:

$ofpg = new OfDataProductGroup();
        $ofpg->group_code = trim($group['groupCode']);
        $ofpg->group_name = $group['groupName'];
        $ofpg->group_desc = $group['webDsc'];
        $ofpg->ctg = $group['ctg'];

        $ofpg->topseller = 0;
        $ofpg->reorder = 0;

        if($this->reorder){
            foreach($this->reorder as $i){

                if(trim($group['groupCode']) == $i->STYLE){
                    $ofpg->reorder = 1;
                    continue;
                }
            }
        }
        if($this->topsellers){

            foreach($this->topsellers as $i){
                $aa = json_decode($i->metadata);
                $s = $aa->style[0]->prdgroup;
                if(trim($group['groupCode']) == $s){
                    $ofpg->topseller = 1;
                    continue;
                }
            }
        }

Body:
Something that might work is using an if statement and put continue; within it on the top of your foreach.

Something like:

foreach($aa as $a)
{
   if($a != $something) // or use ($a == $something), just whatever you need.
   {
      continue;
   }

echo $a;
}

In the situation above you use a foreach to do something with every key from your array. But on top of this foreach you have an if statement. The if statement will only show the result if it matches the requirement, otherwise it will do nothing and continues to the next key.

EDIT:
This is written in PHP, not in JS.


问:
Widget for IBM Watson conversation chatbot
Anyone can suggest a javascript widget to be used for Watson conversation chatbot?

It should be simple to implement in any page, can remember user session and context, and support RTL interfaces.

答: I think in your case would be the easiest to build one on your own - you may check out their GH to see some samples - https://github.com/watson-developer-cloud/conversation-simple and https://github.com/watson-developer-cloud/text-bot then you can apply your own css/js and just consume their API. As far as I know there no something like generic widget which you can style and just embed in your website.</p>


问:
Pulling data from SAP using Excel Macros
So I am trying to pull data from SAP using excel macros. I am new to VBA so please bear with me. I found a topic on here called VBA pulling data from SAP for dummies and I am confused.
What I am trying to do is as follows:

Copy a notification number from a list in excel.

Go to the appropriate screen in SAP and paste this number in the search box.

Open the long text box.

Copy the long text.

Paste into excel.

Here is the link VBA pulling data from SAP for dummies

I can't seem to get by Set session = connection.Children(0) 'Get the first session (window) on that connection.

Any help is much appreciated. The reason I am doing this is because SAP wont export longtext and it takes an act of God to get it fixed.

答:
If I'm reading this correctly, you're wanting to extract the long text information from a notification.  If that is the case, I have a text file that you can import into the visual basic editor and then run that macro in your spreadsheet.  The only thing you need to have is the first column containing the list of your notification number in your spreadsheet (be sure the first notification number starts in cell A2). In cell A1, input Notification number or something like that.  For cell B2 input Description therefore you'll know what each column represents.  I don't know if you're using transaction IQS3 to access your notification, but this is where I go to view all of our notifications that are created.  If not, then hopefully this template my still be of some use to you as a go by or something.

Simply copy and paste the following code below into notepad and save it somewhere that you can access when importing into your spreadsheet.

```<code>Dim i As Integer
Sub Main()

    Call MsgBox("Excel will minimize during this task to allow you to do some other work while it runs. " _
                & vbCrLf & "" _
                & vbCrLf & "It takes approximately 9 seconds per EWR number to retrieve the data from SAP." _
                & vbCrLf & "" _
                & vbCrLf & "Thanks for your patience and understanding, while the code runs. :)" _
                , vbInformation, "See you soon!")

    With Application
        .ScreenUpdating = False
        .Cursor = xlWait
        .Visible = False
    End With
    On Error GoTo Main_Error

    If Not IsObject(sapApplication) Then
        Set SapGuiAuto = GetObject("SAPGUI")
        Set sapApplication = SapGuiAuto.GetScriptingEngine
    End If
    If Not IsObject(Connection) Then
        Set Connection = sapApplication.Children(0)
    End If
    If Not IsObject(Session) Then
        Set Session = Connection.Children(0)
    End If
    If IsObject(WScript) Then
        WScript.ConnectObject Session, "on"
        WScript.ConnectObject sapApplication, "on"
    End If
    i = 2
    'For i = 2 To LastRow(Sheet1)
    Do Until Cells(i, 1).Value = ""
        If Cells(i, 1).Value = "" Then GoTo errReturn
        Application.StatusBar = "Row: " & i & ": Retrieving details for EWR: " & Cells(i, 1).Value
        Cells(i, 2) = Populate(Session, Cells(i, 1).Value, i)
        Cells(i, 1).VerticalAlignment = xlCenter
        Cells(i, 2).VerticalAlignment = xlCenter
        Cells(i, 2).HorizontalAlignment = xlCenter
        If Not Cells(i, 2).MergeCells = True Then Rows.AutoFit
        i = i + 1
        DoEvents
        'Next i
    Loop

    Columns("A:B").AutoFit

    On Error GoTo 0
errReturn:
    With Application
        .ScreenUpdating = True
        .Cursor = xlNormal
        .StatusBar = False
        .Visible = True
    End With
    Exit Sub

Main_Error:
    MsgBox "You need to connect to the SAP GUI to use this spreadsheet", vbCritical, "Error"
    GoTo errReturn
End Sub

Function Populate(Session, EWRNumber As String, j As Integer) As String
    On Error GoTo continue
    Dim strpopulate As String
    'Dim j As Integer
    strpopulate = ""
    'j = 1
    With Session
        '.findById("wnd[0]").maximize
        .findById("wnd[0]/tbar[0]/okcd").Text = "/nIQS3"
        .findById("wnd[0]").sendVKey 0
        .findById("wnd[0]/usr/ctxtRIWO00-QMNUM").Text = EWRNumber
        .findById("wnd[0]").sendVKey 0
        .findById("wnd[0]/usr/tabsTAB_GROUP_10/tabp10\TAB01/ssubSUB_GROUP_10:SAPLIQS0:7235/subCUSTOM_SCREEN:SAPLIQS0:7212/subSUBSCREEN_1:SAPLIQS0:7715/btnQMICON-LTMELD").press
        .findById("wnd[0]/mbar/menu[2]/menu[2]").Select
        n = 1
        Do Until .findById("wnd[0]/usr/tblSAPLSTXXEDITAREA/txtRSTXT-TXLINE[2," & n & "]").Text = "________________________________________________________________________"
            strpopulate = strpopulate & .findById("wnd[0]/usr/tblSAPLSTXXEDITAREA/txtRSTXT-TXLINE[2," & n & "]").Text
            strpopulate = strpopulate & vbCrLf
            n = n + 1
            'MsgBox (CDbl(n / 29) = CInt(n / 29))
            If CDbl(n / 29) = CInt(n / 29) Then
                Call MergeCells(j)    '= 29
                i = i + 1
                'j = j + 1
            End If
        Loop
        .findById("wnd[0]/tbar[0]/btn[15]").press
        .findById("wnd[0]/tbar[0]/btn[15]").press
    End With
    'MsgBox strpopulate
continue:
    Debug.Print strpopulate
    Populate = strpopulate
End Function

Sub MergeCells(j As Integer)
    Cells(j, 1).Select
    'Insert row below active cell
    ActiveCell.Offset(1).EntireRow.Insert

    'Merge Selected Cells and Newly inserted Cells
    Cells(j, 1).Select
    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(1, 0)).Merge
    Cells(j, 2).Select
    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(1, 0)).Merge

    ActiveCell.Select
    Cells(j, 1).VerticalAlignment = xlCenter
    Cells(j, 2).VerticalAlignment = xlCenter
    Cells(j, 2).HorizontalAlignment = xlCenter
    Cells(j, 2).WrapText = True
    Rows(j).RowHeight = 409
    Rows(j + 1).RowHeight = 409
End Sub
</code>```

Body:
If I'm reading this correctly, you're wanting to extract the long text information from a notification.  If that is the case, I have a text file that you can import into the visual basic editor and then run that macro in your spreadsheet.  The only thing you need to have is the first column containing the list of your notification number in your spreadsheet (be sure the first notification number starts in cell A2). In cell A1, input Notification number or something like that.  For cell B2 input Description therefore you'll know what each column represents.  I don't know if you're using transaction IQS3 to access your notification, but this is where I go to view all of our notifications that are created.  If not, then hopefully this template my still be of some use to you as a go by or something.

Simply copy and paste the following code below into notepad and save it somewhere that you can access when importing into your spreadsheet.

Dim i As Integer
Sub Main()

    Call MsgBox("Excel will minimize during this task to allow you to do some other work while it runs. " _
                & vbCrLf & "" _
                & vbCrLf & "It takes approximately 9 seconds per EWR number to retrieve the data from SAP." _
                & vbCrLf & "" _
                & vbCrLf & "Thanks for your patience and understanding, while the code runs. :)" _
                , vbInformation, "See you soon!")

    With Application
        .ScreenUpdating = False
        .Cursor = xlWait
        .Visible = False
    End With
    On Error GoTo Main_Error

    If Not IsObject(sapApplication) Then
        Set SapGuiAuto = GetObject("SAPGUI")
        Set sapApplication = SapGuiAuto.GetScriptingEngine
    End If
    If Not IsObject(Connection) Then
        Set Connection = sapApplication.Children(0)
    End If
    If Not IsObject(Session) Then
        Set Session = Connection.Children(0)
    End If
    If IsObject(WScript) Then
        WScript.ConnectObject Session, "on"
        WScript.ConnectObject sapApplication, "on"
    End If
    i = 2
    'For i = 2 To LastRow(Sheet1)
    Do Until Cells(i, 1).Value = ""
        If Cells(i, 1).Value = "" Then GoTo errReturn
        Application.StatusBar = "Row: " & i & ": Retrieving details for EWR: " & Cells(i, 1).Value
        Cells(i, 2) = Populate(Session, Cells(i, 1).Value, i)
        Cells(i, 1).VerticalAlignment = xlCenter
        Cells(i, 2).VerticalAlignment = xlCenter
        Cells(i, 2).HorizontalAlignment = xlCenter
        If Not Cells(i, 2).MergeCells = True Then Rows.AutoFit
        i = i + 1
        DoEvents
        'Next i
    Loop

    Columns("A:B").AutoFit

    On Error GoTo 0
errReturn:
    With Application
        .ScreenUpdating = True
        .Cursor = xlNormal
        .StatusBar = False
        .Visible = True
    End With
    Exit Sub

Main_Error:
    MsgBox "You need to connect to the SAP GUI to use this spreadsheet", vbCritical, "Error"
    GoTo errReturn
End Sub

Function Populate(Session, EWRNumber As String, j As Integer) As String
    On Error GoTo continue
    Dim strpopulate As String
    'Dim j As Integer
    strpopulate = ""
    'j = 1
    With Session
        '.findById("wnd[0]").maximize
        .findById("wnd[0]/tbar[0]/okcd").Text = "/nIQS3"
        .findById("wnd[0]").sendVKey 0
        .findById("wnd[0]/usr/ctxtRIWO00-QMNUM").Text = EWRNumber
        .findById("wnd[0]").sendVKey 0
        .findById("wnd[0]/usr/tabsTAB_GROUP_10/tabp10\TAB01/ssubSUB_GROUP_10:SAPLIQS0:7235/subCUSTOM_SCREEN:SAPLIQS0:7212/subSUBSCREEN_1:SAPLIQS0:7715/btnQMICON-LTMELD").press
        .findById("wnd[0]/mbar/menu[2]/menu[2]").Select
        n = 1
        Do Until .findById("wnd[0]/usr/tblSAPLSTXXEDITAREA/txtRSTXT-TXLINE[2," & n & "]").Text = "________________________________________________________________________"
            strpopulate = strpopulate & .findById("wnd[0]/usr/tblSAPLSTXXEDITAREA/txtRSTXT-TXLINE[2," & n & "]").Text
            strpopulate = strpopulate & vbCrLf
            n = n + 1
            'MsgBox (CDbl(n / 29) = CInt(n / 29))
            If CDbl(n / 29) = CInt(n / 29) Then
                Call MergeCells(j)    '= 29
                i = i + 1
                'j = j + 1
            End If
        Loop
        .findById("wnd[0]/tbar[0]/btn[15]").press
        .findById("wnd[0]/tbar[0]/btn[15]").press
    End With
    'MsgBox strpopulate
continue:
    Debug.Print strpopulate
    Populate = strpopulate
End Function

Sub MergeCells(j As Integer)
    Cells(j, 1).Select
    'Insert row below active cell
    ActiveCell.Offset(1).EntireRow.Insert

    'Merge Selected Cells and Newly inserted Cells
    Cells(j, 1).Select
    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(1, 0)).Merge
    Cells(j, 2).Select
    Range(ActiveCell.Offset(0, 0), ActiveCell.Offset(1, 0)).Merge

    ActiveCell.Select
    Cells(j, 1).VerticalAlignment = xlCenter
    Cells(j, 2).VerticalAlignment = xlCenter
    Cells(j, 2).HorizontalAlignment = xlCenter
    Cells(j, 2).WrapText = True
    Rows(j).RowHeight = 409
    Rows(j + 1).RowHeight = 409
End Sub


问:
How can I scrape data from a Webpage after searching desired data using HTML Agility
I want to get information from this website

into my ASPX page using the HTML Agility Pack. But I cannot do that, since the data is loaded after I search the data in the webpage.

I need some data to be done continuously after an interval of 5 mins.

答:
Results for searches in the website you've mentioned are rendered dynamically using Javascript and the data comes as Json response via Ajax. HtmlAgilityPack is intended to parse Html, not Json.

Consider using Selenium or iMacros drivers for .Net, or WebBrowser class provided Microsoft Framework. These tools run a browser in background, so they can run Javascript code in that page and render Html you want to scrape.

Just need to set up proper time out, so they will keep waiting until search results appear onto the page.


问:
distribute R pop-up figures on different parts of the screen
If I have multiple pop-up figures in R initiated with window(). However, they are all plotted in the same spot, masking each other. Is there a way to automatically space them out on the screen(s). What I am looking for is an R implementation of this Matlab function: https://se.mathworks.com/matlabcentral/fileexchange/37176-distribute-figures.
I am aware of the par(mfrow) and the layout() options for multipanel figures but they are not what I am looking for.

答:
The function name is windows, not window.  (It is only available in MS Windows, not other platforms.)  It has arguments xpos and ypos that set the position.  If you want your windows in random positions, do something like this:

```<code>windows(xpos = -300*runif(1), ypos = 200*runif(1))
</code>```

(The negative value for xpos measures from the right side of the screen.)

If the graphics windows already exist, you can use arrangeWindows() to distribute them on your screen.  (Again, only in MS Windows.)

Body:
The function name is windows, not window.  (It is only available in MS Windows, not other platforms.)  It has arguments xpos and ypos that set the position.  If you want your windows in random positions, do something like this:

windows(xpos = -300*runif(1), ypos = 200*runif(1))

(The negative value for xpos measures from the right side of the screen.)

If the graphics windows already exist, you can use arrangeWindows() to distribute them on your screen.  (Again, only in MS Windows.)


问:
How to pass several files to a command function and output them to different files?
I have a directory made  of 50 files, here's an excerpt about how the files are names :

```<code>    input1.txt
    input2.txt
    input3.txt
    input4.txt
</code>```

I'm writing the script in R but I'm using bash commands inside it using "system"
I have a system command X that takes one file and outputs it to one file
example :

```<code>X input1.txt output1.txt
</code>```

I want input1.txt to output to output1.txt, input2.txt to output to output2.txt etc..

I've been trying this:

```<code>    for(i in 1:50)
    {
     setwd("outputdir");
     create.file(paste("output",i,".txt",sep=""));
     setwd("homedir");
     system(paste("/usr/local/bin/command" , paste("input",i,".txt",sep=""),paste("/outputdir/output",i,".txt",sep="")));
    }
</code>```

What am I doing wrong? I'm getting an error at the line of system  , it says incorrect string constant , I don't get it.. Did I apply the system command in a wrong manner?

Is there a way to get all the input files and output files without going through the paste command to get them inside system?

答:
There is a pretty easy method in R to copy files to a new directory without using the system commands. This also has the benefit of being cross-capable on different operating systems (just have to change the files structures).

Modified code from:  "Copying files with R" by Amy Whitehead

Using your method of running for files 1:50 I have some psudocode here. You will need to change the current.folder and new.folder to something

```<code># identify the folders
current.folder <- "/usr/local/bin/command"
new.folder <- "/outputdir/output"

# find the files that you want
i <- 1:50
# Instead of looping we can use vector pasting to get multiple results at once!
inputfiles <- paste0(current.folder,"/input",i,".txt")
outputfiles <- paste0(new.folder,"/output",i,".txt")

# copy the files to the new folder
file.copy(inputfiles, outputfiles)
</code>```

Body:
I have a directory made  of 50 files, here's an excerpt about how the files are names :

    input1.txt
    input2.txt
    input3.txt
    input4.txt

I'm writing the script in R but I'm using bash commands inside it using "system"
I have a system command X that takes one file and outputs it to one file
example :

X input1.txt output1.txt

I want input1.txt to output to output1.txt, input2.txt to output to output2.txt etc..

I've been trying this:

    for(i in 1:50)
    {
     setwd("outputdir");
     create.file(paste("output",i,".txt",sep=""));
     setwd("homedir");
     system(paste("/usr/local/bin/command" , paste("input",i,".txt",sep=""),paste("/outputdir/output",i,".txt",sep="")));
    }

What am I doing wrong? I'm getting an error at the line of system  , it says incorrect string constant , I don't get it.. Did I apply the system command in a wrong manner?

Is there a way to get all the input files and output files without going through the paste command to get them inside system?

Body:
There is a pretty easy method in R to copy files to a new directory without using the system commands. This also has the benefit of being cross-capable on different operating systems (just have to change the files structures).

Modified code from:  "Copying files with R" by Amy Whitehead

Using your method of running for files 1:50 I have some psudocode here. You will need to change the current.folder and new.folder to something

# identify the folders
current.folder <- "/usr/local/bin/command"
new.folder <- "/outputdir/output"

# find the files that you want
i <- 1:50
# Instead of looping we can use vector pasting to get multiple results at once!
inputfiles <- paste0(current.folder,"/input",i,".txt")
outputfiles <- paste0(new.folder,"/output",i,".txt")

# copy the files to the new folder
file.copy(inputfiles, outputfiles)


问:
Format string as UK phone number
I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.

My phone numbers are stored in the database as strings, containing only numeric characters.

So far I have come up with this, but the performance seems poor.

```<code>/// <summary>
/// Formats a string as a UK phone number
/// </summary>
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
    string formattedPhoneNumber = null;

    if (!string.IsNullOrEmpty(phoneNumber))
    {
        System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
        System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");

        string formatString;

        if (area1.Match(phoneNumber).Success)
        {
            formatString = "0{0:00 0000 0000}";
        }
        else if (area2.Match(phoneNumber).Success)
        {
            formatString = "0{0:000 000 0000}";
        }
        else
        {
            formatString = "0{0:0000 000000}";
        }

        formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
    }

    return formattedPhoneNumber;
}
</code>```

Thoughts welcomed on how to improve this...

Edit

My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and know that they are truly numeric.

Edit 2

The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered

答:
UK telephone numbers vary in length from 7 digits to 10 digits, not including the leading zero.  "area" codes can vary between 2 and usually 4 (but occasionally 5) digits.

All of the tables that show the area code and total length for each number prefix are available from OFCOM's website.   NB: These tables are very long.

Also, there's no standard for exactly where spaces are put.  Some people might put them in difference places depending on how "readable" it makes the resulting text.

OwnerDisplayName: Richard E

Title: Format string as UK phone number

Body:
I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.

My phone numbers are stored in the database as strings, containing only numeric characters.

So far I have come up with this, but the performance seems poor.

///
/// Formats a string as a UK phone number
///
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
    string formattedPhoneNumber = null;

    if (!string.IsNullOrEmpty(phoneNumber))
    {
        System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
        System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");

        string formatString;

        if (area1.Match(phoneNumber).Success)
        {
            formatString = "0{0:00 0000 0000}";
        }
        else if (area2.Match(phoneNumber).Success)
        {
            formatString = "0{0:000 000 0000}";
        }
        else
        {
            formatString = "0{0:0000 000000}";
        }

        formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
    }

    return formattedPhoneNumber;
}

Thoughts welcomed on how to improve this...

Edit

My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and know that they are truly numeric.

Edit 2

The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered

LastEditorDisplayName: Richard E

OwnerDisplayName: Alnitak


问:
More Complex Data Types in WCF, Association Attribute, Include Attribute etc
I have found this question: Complex data types in WCF? which has a very similiar problem, except it's based on enumvalue problems. My problem is a little more complex. I have a service with methods that function perfectly fine, except for one. The one method (operationcontract) call that fails is for a method returning a complex object. This object has a property with the [Include] and [Association] fields, which in turn has its own [Include] and [Association] fields (these are actually recursive, pointing to each other, buildiing a potentially infinite list.

The biggest problem is that in my development environment Win 7 x64, vs2010, iis, it functions as expected, but in my production environment Server 2008 R2, it breaks, giving me the "An error occurred while receiving the HTTP response to"  error.

I have checked the Service Trace Viewer on the message log, but all that is apparant is that there is no response being sent at all for that particular request. All other requests get a "ServiceLevelSendReply" Record, whereas this particular method does not.

Any Ideas?

答:
Since you have objects referencing other objects in a possible circular manner, you're basically attempting to send an object graph rather than an object tree. WCF only added support for sending object graphs in .NET 3.5 SP1, so if your server has .NET 3.5 without SP1 or lower, it will fail when attempting to send an object graph.

To figure out exactly why your service isn't responding, you may want to enable WCF tracing which produces a very detailed log of what's going on inside your service.


问:
Getting text inside p element inside div
I have following rendered html

```<code><div class="footer text-center">
  <p>By signing up, you agree to abc's <b>Terms of Service</b>, <b>Cookie Policy</b>, <b>Privacy Policy and Content Policies.</b></p>
</div>
</code>```

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

```<code>element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});
</code>```

答:
You should use the innerHtml property.
Check this:

https://www.w3schools.com/jsref/prop_html_innerhtml.asp

Body:
I have following rendered html

By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});


问:
How to use if statement PyTorch using torch.FloatTensor
I am trying to use the if statement in my PyTorch code using torch.FloatTensor as data type, to speed it up into the GPU.

This is my code:

```<code>import torch
import time
def fitness(x):
     return torch.pow(x, 2)

def velocity(v, gxbest, pxbest, pybest, x, pop):
     return torch.rand(pop).type(dtype)*v + \
            torch.rand(pop).type(dtype)*(pxbest - x) + \
            torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x)

dtype = torch.cuda.FloatTensor
def main():

    pop, xmax, xmin, niter = 300000, 50, -50, 100
    v                      = torch.rand(pop).type(dtype)
    x                      = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y                      = fitness(x)
    [miny, indexminy]      = y.min(0)
    gxbest                 = x[indexminy]
    pxbest                 = x
    pybest                 = y

    for K in range(niter):

        vnext = velocity(v, gxbest, pxbest, pybest, x, pop)

        xnext = x + vnext
        ynext = fitness(x)
        [minynext, indexminynext]  = ynext.min(0)

        if (minynext < miny):
            miny   = minynext
            gxbest = xnext[indexminynext]

        indexpbest         = (ynext < pybest)
        pxbest[indexpbest] = xnext[indexpbest]
        pybest[indexpbest] = ynext[indexpbest]
        x                  = xnext
        v                  = vnext
main()
</code>```

Unfortanally it is not working. It is giving me a error message and I can not figure it out what is the problem.

RuntimeError: bool value of non-empty torch.cuda.ByteTensor objects is ambiguous

How can I use the if in PyTorch? I tried to convert the cuda.Tensor into a numpy array but it did not work also.

```<code>  minynext = minynext.cpu().numpy()
  miny = miny.cpu().numpy()
</code>```

PS: Am I doing the code the efficient/faster way possible ? Or should I change something to achieve faster results?

答:
If you look into the following simple example:

```<code>import torch

a = torch.LongTensor([1])
b = torch.LongTensor([5])

print(a > b)
</code>```

Output:

```<code> 0
[torch.ByteTensor of size 1]
</code>```

Comparing tensors a and b results in a torch.ByteTensor which is obviously not equivalent to boolean. So, you can do the following.

```<code>print(a[0] > b[0]) # False
</code>```

So, you should change your if condition as follows.

```<code>if (minynext[0] < miny[0])
</code>```

Body:
I am trying to use the if statement in my PyTorch code using torch.FloatTensor as data type, to speed it up into the GPU.

This is my code:

import torch
import time
def fitness(x):
     return torch.pow(x, 2)

def velocity(v, gxbest, pxbest, pybest, x, pop):
     return torch.rand(pop).type(dtype)*v + \
            torch.rand(pop).type(dtype)*(pxbest - x) + \
            torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x)

dtype = torch.cuda.FloatTensor
def main():

    pop, xmax, xmin, niter = 300000, 50, -50, 100
    v                      = torch.rand(pop).type(dtype)
    x                      = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
    y                      = fitness(x)
    [miny, indexminy]      = y.min(0)
    gxbest                 = x[indexminy]
    pxbest                 = x
    pybest                 = y

    for K in range(niter):

        vnext = velocity(v, gxbest, pxbest, pybest, x, pop)

        xnext = x + vnext
        ynext = fitness(x)
        [minynext, indexminynext]  = ynext.min(0)

        if (minynext < miny):
            miny   = minynext
            gxbest = xnext[indexminynext]

        indexpbest         = (ynext < pybest)
        pxbest[indexpbest] = xnext[indexpbest]
        pybest[indexpbest] = ynext[indexpbest]
        x                  = xnext
        v                  = vnext
main()

Unfortanally it is not working. It is giving me a error message and I can not figure it out what is the problem.

RuntimeError: bool value of non-empty torch.cuda.ByteTensor objects is ambiguous

How can I use the if in PyTorch? I tried to convert the cuda.Tensor into a numpy array but it did not work also.

  minynext = minynext.cpu().numpy()
  miny = miny.cpu().numpy()

PS: Am I doing the code the efficient/faster way possible ? Or should I change something to achieve faster results?

Body:
If you look into the following simple example:

import torch

a = torch.LongTensor([1])
b = torch.LongTensor([5])

print(a > b)

Output:

 0
[torch.ByteTensor of size 1]

Comparing tensors a and b results in a torch.ByteTensor which is obviously not equivalent to boolean. So, you can do the following.

print(a[0] > b[0]) # False

So, you should change your if condition as follows.

if (minynext[0] < miny[0])


问:
WebGL 2.0: Draw call succeeds even VBO is deleted
So I am using a VAO to store pointers from a VBO. I wanted to test what happens when I delete my data buffers (vbo, ibo, etc.) before binding the VAO and calling a draw. Since VAOs store pointers to the data in the corresponding data buffers, I expected the renderer to crash. However, everything keeps working. How is this possible? I am using a WebGL 2.0 context. The documentation states that VAOs are implemented according to OpenGL documentation. Does this has to do with how JavaScript works with objects? Maybe my vbo gets cached somewhere (unknowingly) before I call a deleteBuffer on it. Is this possible? What is happening here?</p>

答:
If a buffer object is tried to be deleted by gl.DeleteBuffers, then the buffer object is not deleted, if it attached to a vertex array object, which is unbound. In this case the name of the object becomes invalid and it is marked unused:

```<code>gl.bindVertexArray( vao );
gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
gl.vertexAttribPointer( ... );
.....
gl.bindVertexArray( 0 );
gl.deleteBuffers( 1, vbo );
</code>```

But if the vertex array object is bound, then the buffer object is detached and deleted:

```<code>gl.bindVertexArray( vao );
gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
gl.vertexAttribPointer( ... );
.....
gl.deleteBuffers( 1, vbo );
gl.bindVertexArray( 0 );
</code>```

See OpenGL ES Specification 3.2 - 5.1.3 Deleted Object and Object Name Lifetimes, page 45:

When a buffer, texture, transform feedback or renderbuffer object is successfully deleted, it is unbound from any bind points it is bound to in the current context, and detached from any attachments of container objects that are bound to the current context ....

Attachments to unbound container objects, such as deletion of a buffer attached to a vertex array object which is not bound to the context, are not affected and continue to act as references on the deleted object ....

When a buffer, query, renderbuffer, sampler, sync, or texture object is deleted, its name immediately becomes invalid (e.g. is marked unused), but the underlying object will not be deleted until it is no longer in use.

Body:
If a buffer object is tried to be deleted by gl.DeleteBuffers, then the buffer object is not deleted, if it attached to a vertex array object, which is unbound. In this case the name of the object becomes invalid and it is marked unused:

gl.bindVertexArray( vao );
gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
gl.vertexAttribPointer( ... );
.....
gl.bindVertexArray( 0 );
gl.deleteBuffers( 1, vbo );

But if the vertex array object is bound, then the buffer object is detached and deleted:

gl.bindVertexArray( vao );
gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
gl.vertexAttribPointer( ... );
.....
gl.deleteBuffers( 1, vbo );
gl.bindVertexArray( 0 );

See OpenGL ES Specification 3.2 - 5.1.3 Deleted Object and Object Name Lifetimes, page 45:

When a buffer, texture, transform feedback or renderbuffer object is successfully deleted, it is unbound from any bind points it is bound to in the current context, and detached from any attachments of container objects that are bound to the current context ....

Attachments to unbound container objects, such as deletion of a buffer attached to a vertex array object which is not bound to the context, are not affected and continue to act as references on the deleted object ....

When a buffer, query, renderbuffer, sampler, sync, or texture object is deleted, its name immediately becomes invalid (e.g. is marked unused), but the underlying object will not be deleted until it is no longer in use.


问:
Is there a way to install and run a local server on my Windows XP Home laptop?
I'm looking to set up a local server on my laptop which is running Windows XP Home Edition. I've noticed that it is impossible to install IIS on the Home Edition, but is there a way around this? Is there other software that I can install to run a server?

the purpose behind this is to mess around and play with ASP to create dynamic websites and my only computer I own has Home Edition.

Also, would running a server on my 5 year old laptop with 2GB of RAM be a good idea?

答:
This is what I use: http://www.aprelium.com/abyssws/

The X1 version is totally free and works great. You can then add PHP as needed (or not)


问:
Function that takes string as Input, evaluate it like a calculator and return the Integer answer
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

```<code>d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i
</code>```

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

答:
It is pretty easy using regular expressions. re.finditer(r'([+-]?\d)', d) will find all occurrences of single digit numbers which may be optionally preceded by a sign. Add a + after [+-]?\d and you can calculate multi digit numbers too.

```<code>import re

d = '-2+2'
total = sum(int(i.group()) for i in re.finditer(r'([+-]?\d+)', d))
</code>```

Body:
I am trying to Implement a function that takes in a string input such as "1+2-3" or "-2+2", evaluate it like a calculator and return the integer answer.

In the example, it would return 0 for both inputs. We can assume that there will only be + or - operator (no multiple/division/or any other operator), as well as input is well formed so we don't need to do any validation (i.e. it's always alternating operator/operand).

I need it with out using existing Python functions like calc() etc. Instead I tried developing a simple code that does this actually.

My code is

d =  {}
sum = 0
for index, value in enumerate(s):
   if value.isdigit():
           pass
   else:
           if not value.isdigit():
                   d[index] = int(s[index]+s[index+1])

for i in d.values():
   sum += i

But it's working only for the case of "-2+2".

How could I make this to work for the case of "1+2-3" also.

Body:
It is pretty easy using regular expressions. re.finditer(r'([+-]?\d)', d) will find all occurrences of single digit numbers which may be optionally preceded by a sign. Add a + after [+-]?\d and you can calculate multi digit numbers too.

import re

d = '-2+2'
total = sum(int(i.group()) for i in re.finditer(r'([+-]?\d+)', d))


问:
Populate random data from another table
```<code>update dataset1.test
   set column4 = (select column1
                 from dataset2
                 order by random()
                 limit 1
                 )
</code>```

I have to update dataset1 of column 4 with each row updating a random entry from dataset 2 column.. But by far now in this above query I get only one random entry in all the rows of dataset1 and its all same which I want it to be random.

答:
Better is to reference the outer table from the subquery. Then the subquery has to be evalued for every row:</p>

```<code>update dataset1.test
   set column4 = (select
        case when dataset1.test.column4 = dataset1.test.column4
             then column1 end
        from dataset2
        order by random()
        limit 1
   )
</code>```

Title: Populate random data from another table

Body:
update dataset1.test
   set column4 = (select column1
                 from dataset2
                 order by random()
                 limit 1
                 )

I have to update dataset1 of column 4 with each row updating a random entry from dataset 2 column.. But by far now in this above query I get only one random entry in all the rows of dataset1 and its all same which I want it to be random.

Body:
Better is to reference the outer table from the subquery. Then the subquery has to be evalued for every row:

update dataset1.test
   set column4 = (select
        case when dataset1.test.column4 = dataset1.test.column4
             then column1 end
        from dataset2
        order by random()
        limit 1
   )


问:
Get id of an element with the same class
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

答:
You could use $(this).find() similar to the below.

What jQuery find does, is get all descendants by the specified selector .printPicOverlay and toggle only those matched elements.

Using $(this) will use the context of the currently hovered over element only.

$(".printPic").hover(function () {
  $(this).find(".printPicOverlay").toggle();
}, function () {
  $(this).find(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

Body:
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

Body:
You could use $(this).find() similar to the below.

What jQuery find does, is get all descendants by the specified selector .printPicOverlay and toggle only those matched elements.

Using $(this) will use the context of the currently hovered over element only.

$(".printPic").hover(function () {
  $(this).find(".printPicOverlay").toggle();
}, function () {
  $(this).find(".printPicOverlay").toggle();
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "printPic" id = "1">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "2">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "3">
  <div class = "printPicOverlay"></div>
</div>


问:
Bundling a private JRE on Mac OS X
Starting with the next version of Mac OS X, Java will no longer be included in the system and I don't want to force my customers to install it themselves. So I would like to do what I do on Windows - bundle it with my app. It also gives me some hope that it could get included in the Mac App Store.

Where can I download a Mac OS X JRE that I could include with my application? Or can I just copy the one that's installed on my Mac?

答:
Update (4/15/2013):

As Thorbjørn helpfully pointed out, Oracle now has a solution for this.  See http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/packagingAppsForMac.html.  However, I'm keeping the original content for "historical purposes", and because it was a fun research project.

Previous version (with edits):

This is a great question.  I was going to respond that you are simply ahead of your time -- as you pointed out, Java is not going to be removed until the Lion release.  However, this article makes it clear that using Java today is not allowed:

Apps that use deprecated or optionally installed technologies (e.g., Java, [PowerPC code requiring] Rosetta) will be rejected.

At the same time, no one has announced a redistributable JRE for Mac OS X yet.  I think your best bet, bearing in mind that you are forging new ground, is to check out the Mac OS X Port wiki page of the OpenJDK project.  It does describe how to compile your own JDK, but it does not clearly state whether or not the resulting JDK can be "bundled" cleanly or not.  I think you will have to try it and see :-(.

Also, it's not clear if the OpenJDK licensing allows this at all (IANAL).  Hopefully someone else has already figured this out with regard to Linux/Windows, although of course the rules may be different for the Apple contributions.

Hope this helps.  If nothing else, it's a starting point.

EDIT: I am going to throw out one additional suggestion.  We now know that Mono apps can be packaged for the App Store.  Furthermore, IKVM.NET is a complete implementation of Java that runs on top of Mono.  You could try, in theory, to put these two pieces together and get a Java app, bundled for the App Store, that does not in fact require a JRE!

If you try this, I would love to hear how it works out :-).

EDIT 2: Unfortunately, the App Store and the GPL do not appear to be compatible (see http://www.zdnet.com/blog/open-source/no-gpl-apps-for-apples-app-store/8046).  The OpenJDK license isn't exactly the same as the GPL, but it's pretty close (again, IANAL).  Therefore, Mono & IKVM.NET may be your best bet.  Good luck!

Title: Bundling a private JRE on Mac OS X


问:
Visual Studio Code - filename color
For some reason, after the update, some filenames appear yellow.

How do I disable it?

答:
As part of the update, Visual Studio Code integrates the colour highlighting of Git version control into the main file explorer.

That’s why you’re seeing yellow for some files as changes have been made to them that have not yet been committed in Git.

You can remove the colour highlighting by adding this line to your settings.json file in VS Code, accessible via Preferences.

"git.decorations.enabled": false

If you wish, you can disable the Git integration entirely by adding these lines to the settings.json file instead.

```<code>{
...
  // Disable Git
  "git.enabled": false,
  "git.path": null,
  "git.autofetch": false
}
</code>```

Title: Visual Studio Code - filename color

Body:
As part of the update, Visual Studio Code integrates the colour highlighting of Git version control into the main file explorer.

That’s why you’re seeing yellow for some files as changes have been made to them that have not yet been committed in Git.

You can remove the colour highlighting by adding this line to your settings.json file in VS Code, accessible via Preferences.

"git.decorations.enabled": false

If you wish, you can disable the Git integration entirely by adding these lines to the settings.json file instead.

{
...
  // Disable Git
  "git.enabled": false,
  "git.path": null,
  "git.autofetch": false
}


答:
Instead use $(this), with $(this).find() like:

```<code>$(this).find(".printPicOverlay").toggle();
</code>```

Have a look at the snippet below:

$(".printPic").hover(function () {
$(this).find(".printPicOverlay").toggle();
}, function () {
$(this).find(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

Hope this helps!

Title: Get id of an element with the same class

Body:
Instead use $(this), with $(this).find() like:

$(this).find(".printPicOverlay").toggle();

Have a look at the snippet below:

$(".printPic").hover(function () {
$(this).find(".printPicOverlay").toggle();
}, function () {
$(this).find(".printPicOverlay").toggle();
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "printPic" id = "1">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "2">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "3">
  <div class = "printPicOverlay"></div>
</div>

Hope this helps!


问:
Can't update or delete dynamically with twig and php oop
I'm learning php oop and I'm going crazy with this ...

I want to update my database with a form in my website.

I create my model like this :

```<code>public function update(Post $post){

$q = $this->_db->prepare('UPDATE posts SET title = :title, featuredImg = :featuredImg, content = :content, author = :author, date = :date, header = :header WHERE id = :id');

$q->bindValue(':title', $post->title(), PDO::PARAM_STR );
$q->bindValue(':content', $post->content(), PDO::PARAM_STR );
$q->bindValue(':author', $post->author(), PDO::PARAM_STR );
$q->bindValue(':header', $post->header(), PDO::PARAM_STR );
$q->bindValue(':date', $post->date(), PDO::PARAM_STR );
$q->bindValue(':featuredImg', $post->featuredImg(), PDO::PARAM_STR);
$q->bindValue(':id', $post->id(), PDO::PARAM_INT);

$q->execute();
</code>```

and my method :

```<code>public function updatePost(){
        $manager = new PostsManager($this->db);
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $p = new Post([
                          'title' => $_POST['title'],
                          'header' => $_POST['header'],
                          'author' => $_POST['author'],
                          'date' => date("Y-m-d H:i:s"),
                          'content' => $_POST['content']
                          ]);
            $manager->update($p);
        }
    }
</code>```

When I var_dump($p)
I have my datas from my form, but when I try it with my method
$manager->update($p)
it says null so nothing change in my db.

I'm not using Doctrine or another DBAL layer.

Please can you tell me what I'm doing bad ? I repeat, I'm learning.
Thanks a lot

EDIT :

My bad, when I var_dump($p), my id is null, it's not good right? :

```<code>$object(Post)[13]
    private '_id' => null
    private '_title' => string 'Spicy jalapeno enim flank laborum prosciutto' (length=44)
    private '_content' => string 'Commodo shankle t-bone, pork loin occaecat ea andouille shoulder venison sausage chicken ... (length=1573)
    private '_author' => string 'aaaaaaaaaaa' (length=11)
    private '_date' => null
    private '_header' => string 'Spicy jalapeno ...' (length=190)
    private '_featuredImg' => null_
</code>```

答:
Just adding the ID in my Post object and everything is back in order</p>

```<code>  $post = new Post([
  'id' => $_POST['id'],
  'title' => $_POST['title'],
  'header' => $_POST['header'],
  'author' => $_POST['author'],
  'date' => date("Y-m-d H:i:s"),
  'content' => $_POST['content'],
  'featuredImg' => $image
]);
</code>```

Body:
I'm learning php oop and I'm going crazy with this ...

I want to update my database with a form in my website.

I create my model like this :

public function update(Post $post){

$q = $this->_db->prepare('UPDATE posts SET title = :title, featuredImg = :featuredImg, content = :content, author = :author, date = :date, header = :header WHERE id = :id');

$q->bindValue(':title', $post->title(), PDO::PARAM_STR );
$q->bindValue(':content', $post->content(), PDO::PARAM_STR );
$q->bindValue(':author', $post->author(), PDO::PARAM_STR );
$q->bindValue(':header', $post->header(), PDO::PARAM_STR );
$q->bindValue(':date', $post->date(), PDO::PARAM_STR );
$q->bindValue(':featuredImg', $post->featuredImg(), PDO::PARAM_STR);
$q->bindValue(':id', $post->id(), PDO::PARAM_INT);

$q->execute();

and my method :

public function updatePost(){
        $manager = new PostsManager($this->db);
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $p = new Post([
                          'title' => $_POST['title'],
                          'header' => $_POST['header'],
                          'author' => $_POST['author'],
                          'date' => date("Y-m-d H:i:s"),
                          'content' => $_POST['content']
                          ]);
            $manager->update($p);
        }
    }

When I var_dump($p)
I have my datas from my form, but when I try it with my method
$manager->update($p)
it says null so nothing change in my db.

I'm not using Doctrine or another DBAL layer.

Please can you tell me what I'm doing bad ? I repeat, I'm learning.
Thanks a lot

EDIT :

My bad, when I var_dump($p), my id is null, it's not good right? :

$object(Post)[13]
    private '_id' => null
    private '_title' => string 'Spicy jalapeno enim flank laborum prosciutto' (length=44)
    private '_content' => string 'Commodo shankle t-bone, pork loin occaecat ea andouille shoulder venison sausage chicken ... (length=1573)
    private '_author' => string 'aaaaaaaaaaa' (length=11)
    private '_date' => null
    private '_header' => string 'Spicy jalapeno ...' (length=190)
    private '_featuredImg' => null_

Body:
Just adding the ID in my Post object and everything is back in order

  $post = new Post([
  'id' => $_POST['id'],
  'title' => $_POST['title'],
  'header' => $_POST['header'],
  'author' => $_POST['author'],
  'date' => date("Y-m-d H:i:s"),
  'content' => $_POST['content'],
  'featuredImg' => $image
]);


问:
Mysql stop slave at log position
I want to re-dump a MySQL table from a master to its slave.

Can I

stop the slave

create a dump of the table I want with --single-transaction --master-flag to take note of its log position

start the slave, but have it stop once it reaches that log position

apply the dump to replace the table

start the slave again normally

How can I do step 3?

答:
After you stop your slave, you can specify the positions you want to process up to in your START SLAVE statement.  Something like:

```<code>START SLAVE UNTIL MASTER_LOG_FILE='xxxxx', MASTER_LOG_POS=yyyyyy;
</code>```

Documented here.

Title: Mysql stop slave at log position

Body:
After you stop your slave, you can specify the positions you want to process up to in your START SLAVE statement.  Something like:

START SLAVE UNTIL MASTER_LOG_FILE='xxxxx', MASTER_LOG_POS=yyyyyy;

Documented here.


问:
GoDaddy DNS Forwading http vs https
I've got a website hosted with Heroku, DNS through GoDaddy.

I've setup forwarding so that example.com should forward to www.example.com.
http forwards properly, https does not:

```<code>http://example.com -> https://www.example.com
https://example.com -> DNS Error
</code>```

In the Heroku panel, the SSL verification has failed for example.com but succeeded for www.example.com.

答:
FROM Heroku Support:

Some DNS providers will only offer A records for root domains. Unfortunately, A records will not suffice for pointing your root domains to Heroku because they require a static IP. Since Heroku uses dynamic IP addresses, it’s necessary to use a CNAME-like record (often referred to as ALIAS or ANAME records) so that you can point your root domain to another domain.

GoDaddy only supports A records for root domains and is thus an insufficient DNS provider.

Heroku offers suggestions for alternative DNS providers:
https://devcenter.heroku.com/articles/custom-domains#configuring-dns-for-root-domains

EDIT:
Working solution with CloudFlare:

```<code>SSL Managed Automatically (ACM) on Heroku
SSL Set to "Full" on CloudFlare
CloudFlare DNS Records:
    CNAME, @, mysite.herokudns.com
    CNAME, www, www.mysite.herokudns.com
CloudFlare CNAME statuses set to "DNS Only" (Gray cloud)
Heroku Domains:
    mysite.com
    www.mysite.com
</code>```

ContentLicense: CC BY-SA 4.0

Title: GoDaddy DNS Forwading http vs https

Body:
I've got a website hosted with Heroku, DNS through GoDaddy.

I've setup forwarding so that example.com should forward to www.example.com.
http forwards properly, https does not:

http://example.com -> https://www.example.com
https://example.com -> DNS Error

In the Heroku panel, the SSL verification has failed for example.com but succeeded for www.example.com.

Body:
FROM Heroku Support:

Some DNS providers will only offer A records for root domains. Unfortunately, A records will not suffice for pointing your root domains to Heroku because they require a static IP. Since Heroku uses dynamic IP addresses, it’s necessary to use a CNAME-like record (often referred to as ALIAS or ANAME records) so that you can point your root domain to another domain.

GoDaddy only supports A records for root domains and is thus an insufficient DNS provider.

Heroku offers suggestions for alternative DNS providers:
https://devcenter.heroku.com/articles/custom-domains#configuring-dns-for-root-domains

EDIT:
Working solution with CloudFlare:

SSL Managed Automatically (ACM) on Heroku
SSL Set to "Full" on CloudFlare
CloudFlare DNS Records:
    CNAME, @, mysite.herokudns.com
    CNAME, www, www.mysite.herokudns.com
CloudFlare CNAME statuses set to "DNS Only" (Gray cloud)
Heroku Domains:
    mysite.com
    www.mysite.com


问:
Delete 5 messages if two users have sent 6 messages to each other
I want to delete 5 messages in Ascending order from the table if any user has sent 6 messages to other user and show the 6th message. For example if Tapy has sent 6 messages to Nomi than first 5 messages will be deleted in ascending order and 6th message will be shown.
I have counted number of messages sent but can't find out the way to delete first 5 messages.

Table name :

t_chat_msg

The fields in the database are:

chat_msg_id

message

from_user_email

to_user_email

timestamp

Here is the model

```<code>function deletemessages($data)
{
 $this->db->select('message as receiver,timestamp');
    $this->db->from('t_chat_msg');
    $this->db->where('from_user_email', $data['fromuser']);
    $this->db->where('to_user_email', $data['touser']);
    $this->db->order_by("timestamp", "asc");
    $num=$this->db->count_all_results();
    return $num;
}
</code>```

Here is the controller

```<code> public function deletemessage()
{
    $data = json_decode(file_get_contents('php://input'));

    $touser = $data->{'touser'};
    $fromuser = $data->{'fromuser'};
    $data = array('touser' => $touser,
                  'fromuser' =>$fromuser);
    $status=$this->um->deletemessage($data);
    echo json_encode($status);
}
</code>```

答:
To get how much messages in total one user have sent to another use query

```<code> SELECT COUNT(*) AS K FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'
</code>```

Then you have a total number of messages, you can delete old one leaving desired amount of messages using query

```<code>DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit
</code>```

IF PUT EVERYTHING TO FUNCTION

```<code>// $amt - amount of messages to keep
// $fromuser - message sender
// $touser - message recipient
function delete_old($amt,$fromuser,$touser)
{
   $ma=mysqli_fetch_assoc(mysqli_query($db,"SELECT COUNT(*) AS K FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'"));
   $limit=$ma['K']-$amt;
   mysqli_query($db,"DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit");
}
</code>```

For codeigniter should work something like this

```<code>// $amt - amount of messages to keep
// $fromuser - message sender
// $touser - message recipient
function delete_old($amt,$fromuser,$touser)
{
    $limit=$this->db->query("SELECT COUNT(*) FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'")->row()-$amt;
    $this->db->query("DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit");
}
</code>```

I don't use it, but based on this it should work properly.

Body:
I want to delete 5 messages in Ascending order from the table if any user has sent 6 messages to other user and show the 6th message. For example if Tapy has sent 6 messages to Nomi than first 5 messages will be deleted in ascending order and 6th message will be shown.
I have counted number of messages sent but can't find out the way to delete first 5 messages.

Table name :

t_chat_msg

The fields in the database are:

chat_msg_id

message

from_user_email

to_user_email

timestamp

Here is the model

function deletemessages($data)
{
 $this->db->select('message as receiver,timestamp');
    $this->db->from('t_chat_msg');
    $this->db->where('from_user_email', $data['fromuser']);
    $this->db->where('to_user_email', $data['touser']);
    $this->db->order_by("timestamp", "asc");
    $num=$this->db->count_all_results();
    return $num;
}

Here is the controller

 public function deletemessage()
{
    $data = json_decode(file_get_contents('php://input'));

    $touser = $data->{'touser'};
    $fromuser = $data->{'fromuser'};
    $data = array('touser' => $touser,
                  'fromuser' =>$fromuser);
    $status=$this->um->deletemessage($data);
    echo json_encode($status);
}

Body:
To get how much messages in total one user have sent to another use query

 SELECT COUNT(*) AS K FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'

Then you have a total number of messages, you can delete old one leaving desired amount of messages using query

DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit

IF PUT EVERYTHING TO FUNCTION

// $amt - amount of messages to keep
// $fromuser - message sender
// $touser - message recipient
function delete_old($amt,$fromuser,$touser)
{
   $ma=mysqli_fetch_assoc(mysqli_query($db,"SELECT COUNT(*) AS K FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'"));
   $limit=$ma['K']-$amt;
   mysqli_query($db,"DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit");
}

For codeigniter should work something like this

// $amt - amount of messages to keep
// $fromuser - message sender
// $touser - message recipient
function delete_old($amt,$fromuser,$touser)
{
    $limit=$this->db->query("SELECT COUNT(*) FROM t_chat_msg WHERE touser='$touser' AND fromuser='$fromuser'")->row()-$amt;
    $this->db->query("DELETE FROM t_chat_msg ORDER BY timestamp ASC LIMIT $limit");
}

I don't use it, but based on this it should work properly.


问:
Using Bing Image API in Jave to search for images
I found this sample code at this link
I replace {subscription key} by my key but the result is always:

```<code>{ "statusCode": 404, "message": "Resource not found" }
</code>```

I'm confused with this line:

```<code>StringEntity reqEntity = new StringEntity("{body}");
</code>```

What should I replace "{body}" by ?
Full code in the example from https://dev.cognitive.microsoft.com is below

```<code>// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/images/search");

            builder.setParameter("q", "cats");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "multipart/form-data");
            request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");

            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

答:
It seems the issue here is the wrong method. For images/search endpoint, http method should be GET and not POST. POST method has a different endpoint for images API - to get insights.

All endpoints are here: https://dev.cognitive.microsoft.com/docs/services/8336afba49a84475ba401758c0dbf749/operations/56b4433fcf5ff8098cef380c.

Body:
I found this sample code at this link
I replace {subscription key} by my key but the result is always:

{ "statusCode": 404, "message": "Resource not found" }

I'm confused with this line:

StringEntity reqEntity = new StringEntity("{body}");

What should I replace "{body}" by ?
Full code in the example from https://dev.cognitive.microsoft.com is below

// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample
{
    public static void main(String[] args)
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/images/search");

            builder.setParameter("q", "cats");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "multipart/form-data");
            request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");

            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}


问:
Swapping arguments inside a list of liss of tuples
I have a list of lists of tuples in the following form:

```<code>a = [[( 0,  1),
      ( 2,  3),
      ( 4,  5)],

     [( 6,  7),
      ( 8,  9),
      (10, 11)],

     [(12, 13),
      (14, 15),
      (16, 17)]]
</code>```

What I want to do, is to swap the two arguments inside the tuples.

I have tried the two following options, but without succes, the argumets keep their positions:

```<code>for i in range(0, len(a)-1):
    for j in range(0, len(a)/2):

        a[i][j] = a[i][j][1], a[i][j][0]

        a[i][j] = tuple(reversed(a[i][j]))
</code>```

Every help would be very much appreciated

答:
Tuples are immutable, so you should replace the tuples with the reversed tuples, not try to modify the first tuple in-place:

```<code>for lst in a:
   for i, x in enumerate(lst):
      lst[i] = x[::-1]
</code>```

This takes updates the items at the position of each tuple in the list with a new reversed tuple (with reversed slice notation [::-1]) using list subscription.

To create a new list of lists with the swapped objects, you can use a list comprehension:

```<code>new_a = [[tup[::-1] for tup in lst]for lst in a]
</code>```

Body:
I have a list of lists of tuples in the following form:

a = [[( 0,  1),
      ( 2,  3),
      ( 4,  5)],

     [( 6,  7),
      ( 8,  9),
      (10, 11)],

     [(12, 13),
      (14, 15),
      (16, 17)]]

What I want to do, is to swap the two arguments inside the tuples.

I have tried the two following options, but without succes, the argumets keep their positions:

for i in range(0, len(a)-1):
    for j in range(0, len(a)/2):

        a[i][j] = a[i][j][1], a[i][j][0]

        a[i][j] = tuple(reversed(a[i][j]))

Every help would be very much appreciated

Body:
Tuples are immutable, so you should replace the tuples with the reversed tuples, not try to modify the first tuple in-place:

for lst in a:
   for i, x in enumerate(lst):
      lst[i] = x[::-1]

This takes updates the items at the position of each tuple in the list with a new reversed tuple (with reversed slice notation [::-1]) using list subscription.

To create a new list of lists with the swapped objects, you can use a list comprehension:

new_a = [[tup[::-1] for tup in lst]for lst in a]


问:
Unity - Inject different classes for the same interface
I have one interface: IFoo

Two classes implementing that interface: FooOne and FooTwo

And two classes ClassOne and ClassTwo receiving an IFoo parameter in the constructor.

How I configure unity so ClassOne receives a FooOne instance and ClassTwo receives a FooTwo using only one container?

I can't do it at runtime so it must be in the config file.

答:
I setup in my application like this

Installed Nuget Package Unity version 4.0.1

```<code><package id="Unity" version="4.0.1" targetFramework="net452" />
</code>```

In my App.config

```<code><configSections>
     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>

<unity>
    <container>
        <register type="MyApp.MainWindow, MyApp">
            <lifetime type="singleton" />
        </register>
        <register name="UnityResolver" type="MyApp.Core.Interface.IResolver, MyApp.Core.Interface" mapTo="Avelyn.Core.Container.UnityResolver, Avelyn.Core" />
        <register name="NinjectResolver" type="MyApp.Core.Interface.IResolver, MyApp.Core.Interface" mapTo="Avelyn.Core.Container.NinjectResolver, Avelyn.Core" />
    </container>
</unity>
</code>```

In My App.xaml.cs

```<code>var _container = new UnityContainer();
_container.LoadConfiguration();

IResolver _unityResolver = _container.Resolve<IResolver>("UnityResolver");
IResolver _ninject  = _container.Resolve<IResolver>("NinjectResolver");
MainWindow _win = _container.Resolve<MainWindow>();
</code>```

Body:
I setup in my application like this

Installed Nuget Package Unity version 4.0.1

<package id="Unity" version="4.0.1" targetFramework="net452" />

In my App.config

<configSections>
     <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>

<unity>
    <container>
        <register type="MyApp.MainWindow, MyApp">
            <lifetime type="singleton" />
        </register>
        <register name="UnityResolver" type="MyApp.Core.Interface.IResolver, MyApp.Core.Interface" mapTo="Avelyn.Core.Container.UnityResolver, Avelyn.Core" />
        <register name="NinjectResolver" type="MyApp.Core.Interface.IResolver, MyApp.Core.Interface" mapTo="Avelyn.Core.Container.NinjectResolver, Avelyn.Core" />
    </container>
</unity>

In My App.xaml.cs

var _container = new UnityContainer();
_container.LoadConfiguration();

IResolver _unityResolver = _container.Resolve<IResolver>("UnityResolver");
IResolver _ninject  = _container.Resolve<IResolver>("NinjectResolver");
MainWindow _win = _container.Resolve<MainWindow>();


问:
Get selected value from jqueryui autocomplete combobox
I'm trying to get selected value from jqueryui autocomplete combobox.

Here is the Demo.

I have added below code to get selected value. but it is not worked.

```<code>$( "#combobox" ).autocomplete({
   select: function(event, ui) {
       alert($(ui).val());
   }
});
</code>```

How can I solve this?

答:
First set id of textbox and then get value of that textbox and match it with text of option of dropdown, if option's text match then get its value. you can see example here in jsfiddle</p>

```<code>this.input = $("<input>")
     .appendTo(this.wrapper)
     .val(value)
     .attr('placeholder', "Enter Type...")
     .attr("title", "")

     // Set Id of Input Type Text

     .attr('id', 'Mach')
     .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
     .autocomplete({
     delay: 0,
     minLength: 0,
     source: $.proxy(this, "_source")
     })
</code>```

Body:
I'm trying to get selected value from jqueryui autocomplete combobox.

Here is the Demo.

I have added below code to get selected value. but it is not worked.

$( "#combobox" ).autocomplete({
   select: function(event, ui) {
       alert($(ui).val());
   }
});

How can I solve this?

Body:
First set id of textbox and then get value of that textbox and match it with text of option of dropdown, if option's text match then get its value. you can see example here in jsfiddle

this.input = $("<input>")
     .appendTo(this.wrapper)
     .val(value)
     .attr('placeholder', "Enter Type...")
     .attr("title", "")

     // Set Id of Input Type Text

     .attr('id', 'Mach')
     .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
     .autocomplete({
     delay: 0,
     minLength: 0,
     source: $.proxy(this, "_source")
     })


问:
How to send task to exchange rather then queue in celery python
What I understood from celery's documentations, when publishing tasks, you send them to exchange first and then exchange delegates it to queues. Now I want to send a task to specific custom made exchange which will delegate all tasks it receives to 3 different queues, which will have different consumers in the background, performing different tasks.

```<code>class Tasks(object):

    def __init__(self, config_object={}):
        self.celery = Celery()
        self.celery.config_from_object(config_object)
        self.task_publisher = task_publisher

    def publish(self, task_name, job_id=None, params={}):

        if not job_id:
        job_id = uuid.uuid4()
        self.celery.send_task(task_name, [job_id, params], queue='new_queue')

class config_object(object):

    CELERY_IGNORE_RESULT = True
    BROKER_PORT = 5672
    BROKER_URL = 'amqp://guest:guest@localhost'
    CELERY_RESULT_BACKEND = 'amqp'

tasks_service = Tasks(config_object)
tasks_service.publish('logger.log_event', params={'a': 'b'})
</code>```

This is how I can send a task to specific queue, if I Dont define the queue it gets sent to a default one, but my question is how do I define the exchange to send to?

答:
not sure if you have solved this problem.
i came across the same thing last week.
I am on Celery 4.1 and the solution I came up with was to just define the exchange name and the routing_key

so in your publish method, you would do something like:

```<code>    def publish(self, task_name, job_id=None, params={}):

        if not job_id:
            job_id = uuid.uuid4()
            self.celery.send_task(
                task_name,
                [job_id, params],
                exchange='name.of.exchange',
                routing_key='*'
            )
</code>```

Body:
What I understood from celery's documentations, when publishing tasks, you send them to exchange first and then exchange delegates it to queues. Now I want to send a task to specific custom made exchange which will delegate all tasks it receives to 3 different queues, which will have different consumers in the background, performing different tasks.

class Tasks(object):

    def __init__(self, config_object={}):
        self.celery = Celery()
        self.celery.config_from_object(config_object)
        self.task_publisher = task_publisher

    def publish(self, task_name, job_id=None, params={}):

        if not job_id:
        job_id = uuid.uuid4()
        self.celery.send_task(task_name, [job_id, params], queue='new_queue')

class config_object(object):

    CELERY_IGNORE_RESULT = True
    BROKER_PORT = 5672
    BROKER_URL = 'amqp://guest:guest@localhost'
    CELERY_RESULT_BACKEND = 'amqp'

tasks_service = Tasks(config_object)
tasks_service.publish('logger.log_event', params={'a': 'b'})

This is how I can send a task to specific queue, if I Dont define the queue it gets sent to a default one, but my question is how do I define the exchange to send to?

Body:
not sure if you have solved this problem.
i came across the same thing last week.
I am on Celery 4.1 and the solution I came up with was to just define the exchange name and the routing_key

so in your publish method, you would do something like:

    def publish(self, task_name, job_id=None, params={}):

        if not job_id:
            job_id = uuid.uuid4()
            self.celery.send_task(
                task_name,
                [job_id, params],
                exchange='name.of.exchange',
                routing_key='*'
            )


问:
Geocoder,s gem near method not working on rails 5
Been trying to use the geocoder gem to find locations using the geocoders method near for finding certain locations near to certain points.

```<code>def index
  @data = Datum.all

   @emergency = Emergency.last
   @data_near = Datum.near([@emergency.longitude,@emergency.latitude],100,:units => :km)

  @geojson = Array.new

  @data_near.each do |mapdata|
     @geojson << {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [mapdata.longitude, mapdata.latitude]
          },
          properties: {
            name: mapdata.description,
            address: mapdata.address,
            BusType: 'hospital',
            popupContent: "#{mapdata.address} is a #{mapdata.description}",
            :'marker-color' => '#00607d',
            :'marker-symbol' => 'circle',
            :'marker-size' => 'medium'
          }
        }
  end
  respond_to do |format|
     format.html
     format.json{ render json: @geojson }
  end
</code>```

end

That's the code i am trying to run,it returns an empty array even when the  locations near within the specified parameters are present. When i try to run the code directly in the rails console with real points.eg.

```<code>data = Datum.near([36.7689503,-1.381776],10,:units => :km)
</code>```

I do not get any error generated but the output i get is less than readable or comprehensible.The output is:

```<code>Datum Load (0.3ms)  SELECT  data.*, (111.19492664455873 * ABS(data.latitude - 36.7689503) * 0.7071067811865475) + (96.29763124613503 * ABS(data.longitude - -1.381776) * 0.7071067811865475) AS distance, CASE WHEN (data.latitude >= 36.7689503 AND data.longitude >= -1.381776) THEN  45.0 WHEN (data.latitude <  36.7689503 AND data.longitude >= -1.381776) THEN 135.0 WHEN (data.latitude <  36.7689503 AND data.longitude <  -1.381776) THEN 225.0 WHEN (data.latitude >= 36.7689503 AND data.longitude <  -1.381776) THEN 315.0 END AS bearing FROM "data" WHERE (data.latitude BETWEEN 36.67901813940813 AND 36.85888246059187 AND data.longitude BETWEEN -1.4940430256783075 AND -1.2695089743216923) ORDER BY distance ASC LIMIT ?  [["LIMIT", 11]]

 => #<ActiveRecord::Relation []>
</code>```

Any help will be highly appreciated.

答:
```<code>t.string "longitude"
t.string "latitude"
</code>```

Had saved up my coordinates in the database with the string data-type which is wrong ,the coordinates should be saved with the float data attribute.This solved my problem for anyone that maybe experiencing the same problem.Its a good place to start checking.

Body:
Been trying to use the geocoder gem to find locations using the geocoders method near for finding certain locations near to certain points.

def index
  @data = Datum.all

   @emergency = Emergency.last
   @data_near = Datum.near([@emergency.longitude,@emergency.latitude],100,:units => :km)

  @geojson = Array.new

  @data_near.each do |mapdata|
     @geojson << {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [mapdata.longitude, mapdata.latitude]
          },
          properties: {
            name: mapdata.description,
            address: mapdata.address,
            BusType: 'hospital',
            popupContent: "#{mapdata.address} is a #{mapdata.description}",
            :'marker-color' => '#00607d',
            :'marker-symbol' => 'circle',
            :'marker-size' => 'medium'
          }
        }
  end
  respond_to do |format|
     format.html
     format.json{ render json: @geojson }
  end

end

That's the code i am trying to run,it returns an empty array even when the  locations near within the specified parameters are present. When i try to run the code directly in the rails console with real points.eg.

data = Datum.near([36.7689503,-1.381776],10,:units => :km)

I do not get any error generated but the output i get is less than readable or comprehensible.The output is:

Datum Load (0.3ms)  SELECT  data.*, (111.19492664455873 * ABS(data.latitude - 36.7689503) * 0.7071067811865475) + (96.29763124613503 * ABS(data.longitude - -1.381776) * 0.7071067811865475) AS distance, CASE WHEN (data.latitude >= 36.7689503 AND data.longitude >= -1.381776) THEN  45.0 WHEN (data.latitude <  36.7689503 AND data.longitude >= -1.381776) THEN 135.0 WHEN (data.latitude <  36.7689503 AND data.longitude <  -1.381776) THEN 225.0 WHEN (data.latitude >= 36.7689503 AND data.longitude <  -1.381776) THEN 315.0 END AS bearing FROM "data" WHERE (data.latitude BETWEEN 36.67901813940813 AND 36.85888246059187 AND data.longitude BETWEEN -1.4940430256783075 AND -1.2695089743216923) ORDER BY distance ASC LIMIT ?  [["LIMIT", 11]]

 => #<ActiveRecord::Relation []>

Any help will be highly appreciated.

Body:
t.string "longitude"
t.string "latitude"

Had saved up my coordinates in the database with the string data-type which is wrong ,the coordinates should be saved with the float data attribute.This solved my problem for anyone that maybe experiencing the same problem.Its a good place to start checking.


问:
Looping over a variant
I am declaring these two variables in VBA

```<code>Dim MyInteger As Integer
Dim MyVariant As Variant
</code>```

I would like bind a number to MyVariant so it numerically increments an integer value to a variant in the following manner:

```<code>MyVariant1 , MyVariant2, MyVariant3, MyVariant4, MyVariant5
</code>```

I am trying to do this rather than having to declare hundreds of variants in the following way:

```<code>MyVariant As Variant
MyVariant1 As Variant
MyVariant2 As Variant
MyVariant3 As Variant
MyVariant4 As Variant
MyVariant5 As Variant
</code>```

I am trying to do this using a for loop, but it does not seem to work

```<code>Dim MyInteger As Integer
Dim MyVariant As Variant
For MyInteger = 1 To 5
MyVariant & MyInteger
Next MyInteger
</code>```

答:
Just declare your myVariant as an array of variant variables.

```<code>Option Explicit

Sub Test()

    Dim myInteger As Integer, myVariants(1 To 255) As Variant

    For myInteger = 1 To 255
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub
</code>```

If you are unsure the number of variables you will need, you can go about it this way:

```<code>Option Explicit

Sub Test()

    Dim myInteger As Long, myVariants() As Variant
    Dim NumberNeeded As Long

    NumberNeeded = 'Some value
    ReDim myVariants(1 To NumberNeeded)

    For myInteger = 1 To UBound(myVariants)
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub
</code>```

Title: Looping over a variant

Body:
I am declaring these two variables in VBA

Dim MyInteger As Integer
Dim MyVariant As Variant

I would like bind a number to MyVariant so it numerically increments an integer value to a variant in the following manner:

MyVariant1 , MyVariant2, MyVariant3, MyVariant4, MyVariant5

I am trying to do this rather than having to declare hundreds of variants in the following way:

MyVariant As Variant
MyVariant1 As Variant
MyVariant2 As Variant
MyVariant3 As Variant
MyVariant4 As Variant
MyVariant5 As Variant

I am trying to do this using a for loop, but it does not seem to work

Dim MyInteger As Integer
Dim MyVariant As Variant
For MyInteger = 1 To 5
MyVariant & MyInteger
Next MyInteger

Body:
Just declare your myVariant as an array of variant variables.

Option Explicit

Sub Test()

    Dim myInteger As Integer, myVariants(1 To 255) As Variant

    For myInteger = 1 To 255
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub

If you are unsure the number of variables you will need, you can go about it this way:

Option Explicit

Sub Test()

    Dim myInteger As Long, myVariants() As Variant
    Dim NumberNeeded As Long

    NumberNeeded = 'Some value
    ReDim myVariants(1 To NumberNeeded)

    For myInteger = 1 To UBound(myVariants)
        myVariants(myInteger) = "SomeValue"
    Next myInteger

End Sub