问:
Is it legal to use youtube-api to download videos and convert to mp3
(site issue with youtube api)

Is it legal to use youtube-api to download videos and convert to mp3,include youtube icon refrenece that video belong to them,
Listen and when finish delete the converted mp3 include the video?

The idea is to pick 20 songs from youtube api search download and convert to mp3 and listen to music and when done listen delete all files.

Thanks.

答:
This depends on the video you intend to download and convert. There are videos that still have Copyright claims and distribution without consent is illegal.

There are some videos that can usually be subject for Fair Use, but you'll have to check them accordingly just to be sure.

David Swisher's answer in this Quora post explains things very well:

Such converters are merely technology, and technology is morally neutral; it is rarely illegal to use a specific form of technology.  It's what you do with it that makes it legal or illegal.

You can use a YouTube to MP3 (or to MOV/MP4) converter legally to:

Download or convert one of your own videos to audio

Download or convert a public domain video to audio (one either produced solely by the federal government, or where the copyright has expired - which is usually 70 years after the author's death, or one in which the author has specifically released it to the public domain)

Download or convert a video to audio which has a Creative Commons license (as long as you follow the terms of that license)

Download or convert a video to audio within the specific and very narrow exceptions of "fair use" under 17 U.S. Code § 107

Download or convert a video to audio for educational use within the terms of the T.E.A.C.H. Act (if your institution complies with all of the criteria for availing itself of its provisions)

Download or convert a video to audio to create a new creative work specifically for the purpose of criticism/commentary or parody (under the very narrow criteria for those defined by the copyright law)

If your use doesn't fall into one of those specific exemptions, then you have to request written permission from the copyright owner.

This isn't specific to YouTube.  Any time you use copying technology (whether it be a photocopier, a digital camera, a scanner, copying by hand, a converter program, ripping software, etc.) the copyright law1 applies.  The moment something is "fixed into tangible form" (i.e., turned into a video, recorded, written or sketched on a sheet of paper or napkin, etc.), it has a copyright on it, whether or not they actually file proof of that claim.  And outside of the specific exceptions named above, only the person(s) or entit(ies) who created it can determine how and where it may be used.

So if you didn't create it yourself and own (or have the rights to use) all of the content in it, the only way you can do this legally is if it's one of those specific exemptions named in the bullets above.  Any other use would be illegal.


来源: stackexchange

问:
Copy a folder in Alfresco
I want to copy a folder into another, in Alfresco, recursively, with Java.

I only have the NodeRef of each folder.

How to do?

答:
Use CopyService.copyAndRename:

```<code>copyService.copyAndRename(
    sourceNodeRef,
    destinationNodeRef,
    ContentModel.ASSOC_CONTAINS,
    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "New name"),
    true // Recursive
);
</code>```

Inspired from Alfresco's own ScriptNode.java.

ContentLicense: CC BY-SA 3.0

Title: Copy a folder in Alfresco

Body:
Use CopyService.copyAndRename:

copyService.copyAndRename(
    sourceNodeRef,
    destinationNodeRef,
    ContentModel.ASSOC_CONTAINS,
    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "New name"),
    true // Recursive
);

Inspired from Alfresco's own ScriptNode.java.


问:
Passing parameters to macro. Different results. Assembly
The following macro returns value 17*y+x in register AX
But it gives different results when I call it:

```<code>nr 09h 03h

mov ah,09h
mov al,03h
nr ah al
</code>```

The result should be the same but it is not. Why?

```<code>nr MACRO x, y
push bx
push ax
xor ax,ax
xor bx,bx

mov al,y
mov bl, 17
mul bl     ;ax=17*y

mov bl,x

add ax,bx

pop bx
pop bx
ENDM
</code>```

答:
Unlike a function a macro just substitutes text in the source file just as you had written there.

```<code>nr ah al
</code>```

inserts into the source:

```<code>push bx
push ax
xor ax,ax
xor bx,bx

mov al,al
mov bl, 17
mul bl     ;ax=17*y

mov bl,ah

add ax,bx

pop bx
pop bx
</code>```

mov al,al and mov bl,ah are formed by the macro. The macro inserts just the text "ah" resp. "al", not the values of the registers. However, previously the instructions xor ax,ax and xor bx,bx had destroyed the former values of the registers. Also, mul bl destroys any former value of AX.

Body:
The following macro returns value 17*y+x in register AX
But it gives different results when I call it:

nr 09h 03h

mov ah,09h
mov al,03h
nr ah al

The result should be the same but it is not. Why?

nr MACRO x, y
push bx
push ax
xor ax,ax
xor bx,bx

mov al,y
mov bl, 17
mul bl     ;ax=17*y

mov bl,x

add ax,bx

pop bx
pop bx
ENDM

Body:
Unlike a function a macro just substitutes text in the source file just as you had written there.

nr ah al

inserts into the source:

push bx
push ax
xor ax,ax
xor bx,bx

mov al,al
mov bl, 17
mul bl     ;ax=17*y

mov bl,ah

add ax,bx

pop bx
pop bx

mov al,al and mov bl,ah are formed by the macro. The macro inserts just the text "ah" resp. "al", not the values of the registers. However, previously the instructions xor ax,ax and xor bx,bx had destroyed the former values of the registers. Also, mul bl destroys any former value of AX.


问:
Greater than or equal to condition for dates
Why in this greater than or equal to condition not working.</p>

```<code>Dim start As String
Dim endat As String
start = InputBox("Enter the Starting Date:        Format:  dd-mon-yy")
endat = InputBox("Enter the End Date:        Format:  dd-mon-yy")
Sheets("Data Base").Range("A1:H2000").AutoFilter Field:=5, Criteria1:=">=" & start, Operator:=xlAnd, Criteria2:="<=" & endat
</code>```

答:
If the values in Column E in your "Data Base" sheet are formatted as Date, then you can force the InputBox to allow only date format.

Using the Application.InputBox, together with the FormatDateTime function, will force the user to input in a date format.

To learn more about FormatDateTime MSDN

Code

```<code>Option Explicit

Sub BetweenDates()

Dim StartDate   As Date
Dim EndDate     As Date

Do
    StartDate = Application.InputBox("Enter the Starting Date:", "Format: dd-mm-yyyy", FormatDateTime(Date, vbShortDate), Type:=1)
Loop While StartDate = False ' disable the Cancel option

Do
    EndDate = Application.InputBox("Enter the End Date:", "Format: dd-mm-yyyy", FormatDateTime(Date, vbShortDate), Type:=1)
Loop While EndDate = False ' disable the Cancel option

Sheets("Data Base").Range("A1:H2000").AutoFilter Field:=5, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

End Sub
</code>```

Body:
Why in this greater than or equal to condition not working.

Dim start As String
Dim endat As String
start = InputBox("Enter the Starting Date:        Format:  dd-mon-yy")
endat = InputBox("Enter the End Date:        Format:  dd-mon-yy")
Sheets("Data Base").Range("A1:H2000").AutoFilter Field:=5, Criteria1:=">=" & start, Operator:=xlAnd, Criteria2:="<=" & endat

Body:
If the values in Column E in your "Data Base" sheet are formatted as Date, then you can force the InputBox to allow only date format.

Using the Application.InputBox, together with the FormatDateTime function, will force the user to input in a date format.

To learn more about FormatDateTime MSDN

Code

Option Explicit

Sub BetweenDates()

Dim StartDate   As Date
Dim EndDate     As Date

Do
    StartDate = Application.InputBox("Enter the Starting Date:", "Format: dd-mm-yyyy", FormatDateTime(Date, vbShortDate), Type:=1)
Loop While StartDate = False ' disable the Cancel option

Do
    EndDate = Application.InputBox("Enter the End Date:", "Format: dd-mm-yyyy", FormatDateTime(Date, vbShortDate), Type:=1)
Loop While EndDate = False ' disable the Cancel option

Sheets("Data Base").Range("A1:H2000").AutoFilter Field:=5, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

End Sub


问:
inner join large table with small table , how to speed up
dear php and mysql expertor
i have two table one large for posts artices 200,000records (index colume: sid) , and one small table (index colume topicid ) for topics has 20 record .. have same topicid

curent im using : ( it took round 0.4s)

+do get last 50 record from table:

SELECT sid, aid, title, time, topic, informant, ihome, alanguage, counter, type, images, chainid FROM veryzoo_stories ORDER BY sid DESC LIMIT 0,50

+then do while loop in each records for find the maching name of topic in each post:

while ( .. ) {
SELECT topicname FROM veryzoo_topics WHERE topicid='$topic'"
....
}

+Now
I going to use Inner Join for speed up process but as my test it took much longer from 1.5s up to 3.5s

SELECT a.sid, a.aid, a.title, a.time, a.topic, a.informant, a.ihome, a.alanguage, a.counter, a.type, a.images, a.chainid, t.topicname FROM veryzoo_stories a INNER JOIN veryzoo_topics t ON a.topic = t.topicid ORDER BY sid DESC LIMIT 0,50

It look like the inner join do all joining 200k records from two table fist then limit result at 50 .. that took long time..

Please help to point me right way doing this..
eg take last 50 records from table one.. then join it to table 2 .. ect

答: Do not use inner join unless the two tables share the same primary key, or you'll get duplicate values (and of course a slower query).

ContentLicense: CC BY-SA 2.5


答:
Your all data has following data.like below.

```<code> alldata={"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
</code>```

so each time your list item get the data from that appointment array. so alldata variable will be changed based on the position from the getItem(position) method.

So, alldata is jsonObject.

so you should parse like below,

```<code> JSONObject jsonRowData= new JSONObject(allData);
 try{
   jsonRowData.getString("0");
   jsonRowData.getString("id"):
   jsonRowData.getString("1"):
   jsonRowData.getString("cid"):
   jsonRowData.getString("2"):
   jsonRowData.getString("uid"):
   jsonRowData.getString("3");
   jsonRowData.getString("date"):
   jsonRowData.getString("4");
    }catch(Exception e){
    e.printStackTrace();
   }
</code>```

like you have to call. hope it helps

Title: Android JSON parsing error cannot be converted to JSONArray

Body:
I'm fairly new to Android dev, and am trying to write a programme to parse some JSON from a website and output it in a ListView. However, when I run my programme, I get the error: (There are more then 7 row same as this error)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/FAILED: Json parsing
error: Value
{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/FAILED: Json parsing error:
Value
{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

The JSON I'm trying to parse is:

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"},{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"},{"0":"4","id":"4","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-15","date":"2017-04-15","4":"20","hour":"20"},{"0":"5","id":"5","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-22","date":"2017-04-22","4":"20","hour":"20"},{"0":"6","id":"6","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-24","date":"2017-03-24","4":"17","hour":"17"},{"0":"7","id":"7","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"17","hour":"17"},{"0":"8","id":"8","1":"1","cid":"1","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"16","hour":"16"},{"0":"9","id":"9","1":"2","cid":"2","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"15","hour":"15"},{"0":"10","id":"10","1":"3","cid":"3","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"13","hour":"13"}]}

this my listview custom row java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

This is json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

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

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

If I don't parse:

Body:
Your all data has following data.like below.

 alldata={"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}

so each time your list item get the data from that appointment array. so alldata variable will be changed based on the position from the getItem(position) method.

So, alldata is jsonObject.

so you should parse like below,

 JSONObject jsonRowData= new JSONObject(allData);
 try{
   jsonRowData.getString("0");
   jsonRowData.getString("id"):
   jsonRowData.getString("1"):
   jsonRowData.getString("cid"):
   jsonRowData.getString("2"):
   jsonRowData.getString("uid"):
   jsonRowData.getString("3");
   jsonRowData.getString("date"):
   jsonRowData.getString("4");
    }catch(Exception e){
    e.printStackTrace();
   }

like you have to call. hope it helps


问:
Angular 4 Can't bind to <property> since it isn't a known property of <component>
I'm trying to create my own directive in Angular 4. But, I got this error when bind the property of class into component template.

Console error:

Unhandled Promise rejection: Template parse errors: Can't bind to
'data' since it isn't a known property of 'tree'. ("<tree [ERROR
->][data]="data"></tree>"):
```

<p>My tree-view-component.ts:</p>

```@Component({
    selector: 'app-tree-view',
    template: '<tree [data]="data"></tree>'
})
export class TreeViewComponent implements OnInit {

    @Input() data: any[];

    constructor() {
        this.data = [
        {
            label: 'a1',
            subs: [
                {
                    label: 'a11',
                    subs: [
                        {
                            label: 'a111',
                            subs: [
                                {
                                    label: 'a1111'
                                },
                                {
                                    label: 'a1112'
                                }
                            ]
                        },
                        {
                            label: 'a112'
                        }
                    ]
                },
                {
                    label: 'a12',
                }
            ]
         }
     ];
  }

  ngOnInit() { }

}
```

Here is my complete script file: https://pastebin.com/hDyX2Kjj

Is there anyone know about this? TiA

答:
Every component, directive, and pipe needs to be registered in @NgModule()

```<code>@NgModule({
  declarations: [TreeViewComponent]
})
export class AppModule {}
</code>```

For more details see

https://angular.io/api/core/NgModule

https://angular.io/guide/ngmodules

https://angular.io/guide/ngmodule-api

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create my own directive in Angular 4. But, I got this error when bind the property of class into component template.

Console error:

Unhandled Promise rejection: Template parse errors: Can't bind to
'data' since it isn't a known property of 'tree'. ("<tree [ERROR
->][data]="data"></tree>"):

My tree-view-component.ts:

@Component({
    selector: 'app-tree-view',
    template: '<tree [data]="data"></tree>'
})
export class TreeViewComponent implements OnInit {

    @Input() data: any[];

    constructor() {
        this.data = [
        {
            label: 'a1',
            subs: [
                {
                    label: 'a11',
                    subs: [
                        {
                            label: 'a111',
                            subs: [
                                {
                                    label: 'a1111'
                                },
                                {
                                    label: 'a1112'
                                }
                            ]
                        },
                        {
                            label: 'a112'
                        }
                    ]
                },
                {
                    label: 'a12',
                }
            ]
         }
     ];
  }

  ngOnInit() { }

}

Here is my complete script file: https://pastebin.com/hDyX2Kjj

Is there anyone know about this? TiA

Body:
Every component, directive, and pipe needs to be registered in @NgModule()

@NgModule({
  declarations: [TreeViewComponent]
})
export class AppModule {}

For more details see

https://angular.io/api/core/NgModule

https://angular.io/guide/ngmodules

https://angular.io/guide/ngmodule-api


问:
Check parameter in Lambda Expression
I have this code:

```<code> Function<Integer, String> converter = (num) -> Integer.toString(num);
</code>```

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

答:
To add checks to a lambda expression just use it as if it was a function:

```<code>Function<Number , String> converter = (num) -> {
    final String result;
    if (num instanceof Integer) {
        result = Integer.toString((int)num);
    } else {
        result = "show some error";
       //Or throw an exception
    }
    return result;
};
</code>```

A better way would be to call a method as this could get messy for longer methods.

Maybe somehting like this:

```<code>Function<Number , String> converter = e -> convertString(e);

public static String convertString(Number num) {
    final String result;
    if (num instanceof Integer) {
        result = Integer.toString((int)num);
    } else {
        result = "show some error";
    }
    return result;
}
</code>```

You could also use  FooClass::convertString.

Title: Check parameter in Lambda Expression

Body:
I have this code:

 Function<Integer, String> converter = (num) -> Integer.toString(num);

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

Body:
To add checks to a lambda expression just use it as if it was a function:

Function<Number , String> converter = (num) -> {
    final String result;
    if (num instanceof Integer) {
        result = Integer.toString((int)num);
    } else {
        result = "show some error";
       //Or throw an exception
    }
    return result;
};

A better way would be to call a method as this could get messy for longer methods.

Maybe somehting like this:

Function<Number , String> converter = e -> convertString(e);

public static String convertString(Number num) {
    final String result;
    if (num instanceof Integer) {
        result = Integer.toString((int)num);
    } else {
        result = "show some error";
    }
    return result;
}

You could also use  FooClass::convertString.


问:
Code for capturing QR Code doesn't seem working well in Xcode8 and Swift3
I'm trying to capture QR code using AVCaptureMetadataOutputObjectsDelegate in Swift3 and iOS 10 beta device.

But captureOutput function is not called when QR code is actually captured by device's camera.

Does anyone have a solution for this? If so, please let me know how to fix and work properly.

Thanks,

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()

    let mySession: AVCaptureSession! = AVCaptureSession()
    let devices = AVCaptureDevice.devices()
    var myDevice: AVCaptureDevice!

    for device in devices! {
      if((device as AnyObject).position == AVCaptureDevicePosition.back){
        myDevice = device as! AVCaptureDevice
      }
    }

    let myVideoInput = try! AVCaptureDeviceInput.init(device: myDevice)

    if mySession.canAddInput(myVideoInput) {
      mySession.addInput(myVideoInput)
    }

    let myMetadataOutput: AVCaptureMetadataOutput! = AVCaptureMetadataOutput()

    if mySession.canAddOutput(myMetadataOutput) {
      mySession.addOutput(myMetadataOutput)
      myMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
      myMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    }

    let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
    myVideoLayer?.frame = self.view.bounds
    myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.addSublayer(myVideoLayer!)

    mySession.startRunning()
  }

  // MARK: - AVCaptureMetadataOutputObjectsDelegate

  // This function is not called despite capturing QR code
  func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, from connection: AVCaptureConnection!) {
    if metadataObjects.count > 0 {
      let qrData: AVMetadataMachineReadableCodeObject  = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
      print("\(qrData.type)")
      print("\(qrData.stringValue)")

    }
  }

}
</code>```

答:
SWIFT 3: In my case this code solve the problem:

Old INCORRECT CODE

```<code>private func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {
                print("QR Code: \(metadataObject.stringValue)")
            }
        }
    }
}
</code>```

CORRECT ANSWER

```<code>func captureOutput(_ captureOutput: AVCaptureOutput!,
                   didOutputMetadataObjects metadataObjects: [Any]!,
                   from connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {
                print("QR Code: \(metadataObject.stringValue)")
            }
        }
    }

}
</code>```

Body:
I'm trying to capture QR code using AVCaptureMetadataOutputObjectsDelegate in Swift3 and iOS 10 beta device.

But captureOutput function is not called when QR code is actually captured by device's camera.

Does anyone have a solution for this? If so, please let me know how to fix and work properly.

Thanks,

import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()

    let mySession: AVCaptureSession! = AVCaptureSession()
    let devices = AVCaptureDevice.devices()
    var myDevice: AVCaptureDevice!

    for device in devices! {
      if((device as AnyObject).position == AVCaptureDevicePosition.back){
        myDevice = device as! AVCaptureDevice
      }
    }

    let myVideoInput = try! AVCaptureDeviceInput.init(device: myDevice)

    if mySession.canAddInput(myVideoInput) {
      mySession.addInput(myVideoInput)
    }

    let myMetadataOutput: AVCaptureMetadataOutput! = AVCaptureMetadataOutput()

    if mySession.canAddOutput(myMetadataOutput) {
      mySession.addOutput(myMetadataOutput)
      myMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
      myMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    }

    let myVideoLayer = AVCaptureVideoPreviewLayer.init(session: mySession)
    myVideoLayer?.frame = self.view.bounds
    myVideoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.addSublayer(myVideoLayer!)

    mySession.startRunning()
  }

  // MARK: - AVCaptureMetadataOutputObjectsDelegate

  // This function is not called despite capturing QR code
  func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, from connection: AVCaptureConnection!) {
    if metadataObjects.count > 0 {
      let qrData: AVMetadataMachineReadableCodeObject  = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
      print("\(qrData.type)")
      print("\(qrData.stringValue)")

    }
  }

}

Body:
SWIFT 3: In my case this code solve the problem:

Old INCORRECT CODE

private func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {
                print("QR Code: \(metadataObject.stringValue)")
            }
        }
    }
}

CORRECT ANSWER

func captureOutput(_ captureOutput: AVCaptureOutput!,
                   didOutputMetadataObjects metadataObjects: [Any]!,
                   from connection: AVCaptureConnection!) {
    for item in metadataObjects {
        if let metadataObject = item as? AVMetadataMachineReadableCodeObject {
            if metadataObject.type == AVMetadataObjectTypeQRCode {
                print("QR Code: \(metadataObject.stringValue)")
            }
        }
    }

}


问:
Python - how to populate a list of dictionaries from existing lists
I have a list of lists, e.g. mylist=[[1,2,3],[4,5,6],[7,8,9],...], and I want to populate a list of dicts where the values of the dicts come from the nested lists, e.g.

```<code>dlist[0]['area']=1
dlist[0]['volume']=2
dlist[0]['height']=3
dlist[1]['area']=4
dlist[1]['volume']=5
</code>```

etc.

So far I have:

```<code>dlist = [{'area':mylist[i][0], 'volume':mylist[i][1], 'height':mylist[i][2]} for i in range(len(mylist)]
</code>```

My lists can be very large in the first dimension (i.e. len(mylist) can be very large). Is there a faster way than this list comprehension? Maybe something with zip?

答:
You can use zip in a list comprehension:

Code:

```<code>keys = ('area', 'volume', 'height')
output = [dict(zip(keys, l)) for l in mylist]
</code>```

Data:

```<code>mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

Results:

```<code>[{'volume': 2, 'height': 3, 'area': 1},
 {'volume': 5, 'height': 6, 'area': 4},
 {'volume': 8, 'height': 9, 'area': 7}]
</code>```

But if you want faster than your original solution:

Then skip the zip, use iteration on your original list, and build the dict directly:

```<code>output = [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]
</code>```

Timing Code:

```<code>import timeit

mylist = [[1, 2, 3]] * 100000

def method1():
    keys = ('area', 'volume', 'height')
    return [dict(zip(keys, i)) for i in mylist]

def method2():
    return [{
        'area': mylist[i][0],
        'volume': mylist[i][1],
        'height': mylist[i][2]
    } for i in range(len(mylist))]

def method3():
    return [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]

print(timeit.repeat("method1()", "from __main__ import method1", number=10))
print(timeit.repeat("method2()", "from __main__ import method2", number=10))
print(timeit.repeat("method3()", "from __main__ import method3", number=10))
</code>```

Timing Results:

Zip:

```<code>[1.192184281360701, 1.7045185775655127, 1.2134081278821043]
</code>```

Original:

```<code>[0.38957559529443664, 0.38713287436332866, 0.3920681133687083]
</code>```

Iterate on list, build dict directly:

```<code>[0.2965552921248671, 0.28165834370140264, 0.29972900470716013]
</code>```

Body:
I have a list of lists, e.g. mylist=[[1,2,3],[4,5,6],[7,8,9],...], and I want to populate a list of dicts where the values of the dicts come from the nested lists, e.g.

dlist[0]['area']=1
dlist[0]['volume']=2
dlist[0]['height']=3
dlist[1]['area']=4
dlist[1]['volume']=5

etc.

So far I have:

dlist = [{'area':mylist[i][0], 'volume':mylist[i][1], 'height':mylist[i][2]} for i in range(len(mylist)]

My lists can be very large in the first dimension (i.e. len(mylist) can be very large). Is there a faster way than this list comprehension? Maybe something with zip?

Body:
You can use zip in a list comprehension:

Code:

keys = ('area', 'volume', 'height')
output = [dict(zip(keys, l)) for l in mylist]

Data:

mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Results:

[{'volume': 2, 'height': 3, 'area': 1},
 {'volume': 5, 'height': 6, 'area': 4},
 {'volume': 8, 'height': 9, 'area': 7}]

But if you want faster than your original solution:

Then skip the zip, use iteration on your original list, and build the dict directly:

output = [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]

Timing Code:

import timeit

mylist = [[1, 2, 3]] * 100000

def method1():
    keys = ('area', 'volume', 'height')
    return [dict(zip(keys, i)) for i in mylist]

def method2():
    return [{
        'area': mylist[i][0],
        'volume': mylist[i][1],
        'height': mylist[i][2]
    } for i in range(len(mylist))]

def method3():
    return [{'area': i[0], 'volume': i[1], 'height': i[2]} for i in mylist]

print(timeit.repeat("method1()", "from __main__ import method1", number=10))
print(timeit.repeat("method2()", "from __main__ import method2", number=10))
print(timeit.repeat("method3()", "from __main__ import method3", number=10))

Timing Results:

Zip:

[1.192184281360701, 1.7045185775655127, 1.2134081278821043]

Original:

[0.38957559529443664, 0.38713287436332866, 0.3920681133687083]

Iterate on list, build dict directly:

[0.2965552921248671, 0.28165834370140264, 0.29972900470716013]


问:
node, app.get not found, using parametr
I'm trying to get this route: GET /exercisesadd?id=google-oauth2%7C10385839303782

FrontEnd:

```<code>getResults: function(){
  console.log(this.state.profile.user_id)
  return axios.get('/exercisesadd', {
    params: {
      id: this.state.profile.user_id
    }
  })
  .then(function(response){
    return response;
  });
}
</code>```

Server has:

```<code>app.get('/exercisesadd/:id', (req, res) => {
  console.log(req.params)
});
</code>```

答:
In your case you are making the query request but your server don't have the route for the query request.

When you make  GET /exercisesadd?id=google-oauth2%7C10385839303782 in your server you must have the route with /exercisesadd?id, you only have the route for params

try this and view the console

```<code>app.get('/exercisesadd/:id?', (req, res) => {
    console.log('Query', req.query, 'Params', req.params)
  res.send(req.params);
});
</code>```

GET localhost:3000/exercisesadd?id=google-oauth2%7C10385839303782
where req.query will give you { id: 'google-oauth2|10385839303782' }

AND

GET localhost:3000/exercisesadd/13134124252
where req.params will give you { id: '13134124252' }

Title: node, app.get not found, using parametr

Body:
I'm trying to get this route: GET /exercisesadd?id=google-oauth2%7C10385839303782

FrontEnd:

getResults: function(){
  console.log(this.state.profile.user_id)
  return axios.get('/exercisesadd', {
    params: {
      id: this.state.profile.user_id
    }
  })
  .then(function(response){
    return response;
  });
}

Server has:

app.get('/exercisesadd/:id', (req, res) => {
  console.log(req.params)
});

Body:
In your case you are making the query request but your server don't have the route for the query request.

When you make  GET /exercisesadd?id=google-oauth2%7C10385839303782 in your server you must have the route with /exercisesadd?id, you only have the route for params

try this and view the console

app.get('/exercisesadd/:id?', (req, res) => {
    console.log('Query', req.query, 'Params', req.params)
  res.send(req.params);
});

GET localhost:3000/exercisesadd?id=google-oauth2%7C10385839303782
where req.query will give you { id: 'google-oauth2|10385839303782' }

AND

GET localhost:3000/exercisesadd/13134124252
where req.params will give you { id: '13134124252' }


问:
How to use reflection inside a static method
Ive got a logging method:

```<code>    public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)
    {

        StreamWriter writer;

        //Environment.ExpandEnvironmentVariables("%SystemDrive%") [will get to the c drive]
        if (EnumsAndConstants.EnableApplicationLogging)
        {
            writer = new StreamWriter(logFilePathArg, true);
            writer.Write("Time: " + DateTime.Now.ToString() + " Message: " + messageArg);
            writer.Write(Environment.NewLine);
            writer.Flush();
            writer.Close();
        }

    }
</code>```

And I am trying to access this.GetType().Name inside it but im not allowed to. Is there anyway around this? I want to easily get the calling class name when this method is called without having to rewrite all calls to this method...

答:
As it's static there is no this instance. You'd usually pass the actual instance into to method to provide method data. I have a logging class which accepts a Reflection.MethodInfo instance to output. As you don't want to change the method signature, perhaps you'd have better luck using the StackTrace diagnostics class:

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace%28VS.71%29.aspx

Get the previous Frame, then recover the calling method. The example pretty much says it all.

Body:
Ive got a logging method:

    public static void WriteSimpleDebugTrace(string logFilePathArg, string messageArg)
    {

        StreamWriter writer;

        //Environment.ExpandEnvironmentVariables("%SystemDrive%") [will get to the c drive]
        if (EnumsAndConstants.EnableApplicationLogging)
        {
            writer = new StreamWriter(logFilePathArg, true);
            writer.Write("Time: " + DateTime.Now.ToString() + " Message: " + messageArg);
            writer.Write(Environment.NewLine);
            writer.Flush();
            writer.Close();
        }

    }

And I am trying to access this.GetType().Name inside it but im not allowed to. Is there anyway around this? I want to easily get the calling class name when this method is called without having to rewrite all calls to this method...


问:
'module' object has no attribute 'imread'
I have installed PIL, but I keep getting the following error message:

```<code>'module' object has no attribute 'imread'.
</code>```

I have gone through all posts regarding imread, but have had no luck. Any thoughts?

```<code>Danys-MacBook-Pro:~ danymeneses$ python
/Users/danymeneses/Desktop/autoencoder/main.py --dataset
/Users/danymeneses/Desktop/autoencoder/dataseti --is_train True

{'batch_size': 12,
'beta1': 0.5,
'checkpoint_dir': 'checkpoint',
'dataset': '/Users/danymeneses/Desktop/autoencoder/dataseti',
'epoch': 5,
'image_size': 108,
'is_crop': False,
'is_run': False,
'is_train': True,
'learning_rate': 0.0002,
'noise': 0.5,
'output_dir': 'output',
'sample_dir': 'samples',
'train_size': inf}
WARNING:tensorflow:Passing a `GraphDef` to the SummaryWriter is deprecated.
Pass a `Graph` object instead, such as `sess.graph`.
Traceback (most recent call last):
File "/Users/danymeneses/Desktop/autoencoder/main.py", line 94, in <module>
tf.app.run()
File "/Library/Python/2.7/site-packages/tensorflow/python/platform/app.py",
line 30, in run
sys.exit(main(sys.argv))
File "/Users/danymeneses/Desktop/autoencoder/main.py", line 75, in main
autoencoder.train(FLAGS)
File "/Users/danymeneses/Desktop/autoencoder/model.py", line 186, in train
sample = [get_image(sample_file, self.image_size, is_crop=self.is_crop) for
sample_file in sample_files]
File "/Users/danymeneses/Desktop/autoencoder/utils.py", line 23, in get_image
return transform(imread(image_path), image_size, is_crop)
File "/Users/danymeneses/Desktop/autoencoder/utils.py", line 38, in imread
return scipy.misc.imread(path).astype(np.float)
AttributeError: 'module' object has no attribute 'imread'
</code>```

答:
Thanks for your replies guys! I solved my problem: i didn't notice that i had more than one version of python installed, so i just went like this:

```<code>python2.7 /Users/danymeneses/Desktop/autoencoder/main.py --dataset
/Users/danymeneses/Desktop/autoencoder/datasetii --is_train True
</code>```

specifying the version of python i was using solved my problem, since pip install Pillow didn't of course install Pillow on all versions of Python.

thanks again!

Body:
I have installed PIL, but I keep getting the following error message:

'module' object has no attribute 'imread'.

I have gone through all posts regarding imread, but have had no luck. Any thoughts?

Danys-MacBook-Pro:~ danymeneses$ python
/Users/danymeneses/Desktop/autoencoder/main.py --dataset
/Users/danymeneses/Desktop/autoencoder/dataseti --is_train True

{'batch_size': 12,
'beta1': 0.5,
'checkpoint_dir': 'checkpoint',
'dataset': '/Users/danymeneses/Desktop/autoencoder/dataseti',
'epoch': 5,
'image_size': 108,
'is_crop': False,
'is_run': False,
'is_train': True,
'learning_rate': 0.0002,
'noise': 0.5,
'output_dir': 'output',
'sample_dir': 'samples',
'train_size': inf}
WARNING:tensorflow:Passing a `GraphDef` to the SummaryWriter is deprecated.
Pass a `Graph` object instead, such as `sess.graph`.
Traceback (most recent call last):
File "/Users/danymeneses/Desktop/autoencoder/main.py", line 94, in <module>
tf.app.run()
File "/Library/Python/2.7/site-packages/tensorflow/python/platform/app.py",
line 30, in run
sys.exit(main(sys.argv))
File "/Users/danymeneses/Desktop/autoencoder/main.py", line 75, in main
autoencoder.train(FLAGS)
File "/Users/danymeneses/Desktop/autoencoder/model.py", line 186, in train
sample = [get_image(sample_file, self.image_size, is_crop=self.is_crop) for
sample_file in sample_files]
File "/Users/danymeneses/Desktop/autoencoder/utils.py", line 23, in get_image
return transform(imread(image_path), image_size, is_crop)
File "/Users/danymeneses/Desktop/autoencoder/utils.py", line 38, in imread
return scipy.misc.imread(path).astype(np.float)
AttributeError: 'module' object has no attribute 'imread'

Body:
Thanks for your replies guys! I solved my problem: i didn't notice that i had more than one version of python installed, so i just went like this:

python2.7 /Users/danymeneses/Desktop/autoencoder/main.py --dataset
/Users/danymeneses/Desktop/autoencoder/datasetii --is_train True

specifying the version of python i was using solved my problem, since pip install Pillow didn't of course install Pillow on all versions of Python.

thanks again!


问:
how to send a mail from my iOS application- SWIFT
I want to send a mail from my application. I am doing my first steps with SWIFT and i have stuck at a point. I want to press a button and open up the mail. Can you please tell me how to do the button connection? I think it should be an action but I don't know where to put it on the code </p>

```<code>import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    func sendEmail() {
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([])
        mailVC.setSubject("Subject for email")
        mailVC.setMessageBody("Email message string", isHTML: false)

        presentViewController(mailVC, animated: true, completion: nil)
    }

    // MARK: - Email Delegate

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        controller.dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}
</code>```

答:
Swift 3

```<code>let composer = MFMailComposeViewController()

if MFMailComposeViewController.canSendMail() {
     composer.mailComposeDelegate = self
     composer.setToRecipients(["Email1", "Email2"])
     composer.setSubject("Test Mail")
     composer.setMessageBody("Text Body", isHTML: false)
     present(composer, animated: true, completion: nil)
}
</code>```

Delegate method

```<code>class SendMailViewController: MFMailComposeViewControllerDelegate {
   func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }
}
</code>```

Body:
I want to send a mail from my application. I am doing my first steps with SWIFT and i have stuck at a point. I want to press a button and open up the mail. Can you please tell me how to do the button connection? I think it should be an action but I don't know where to put it on the code

import UIKit
import MessageUI

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    func sendEmail() {
        let mailVC = MFMailComposeViewController()
        mailVC.mailComposeDelegate = self
        mailVC.setToRecipients([])
        mailVC.setSubject("Subject for email")
        mailVC.setMessageBody("Email message string", isHTML: false)

        presentViewController(mailVC, animated: true, completion: nil)
    }

    // MARK: - Email Delegate

    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        controller.dismissViewControllerAnimated(true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

Body:
Swift 3

let composer = MFMailComposeViewController()

if MFMailComposeViewController.canSendMail() {
     composer.mailComposeDelegate = self
     composer.setToRecipients(["Email1", "Email2"])
     composer.setSubject("Test Mail")
     composer.setMessageBody("Text Body", isHTML: false)
     present(composer, animated: true, completion: nil)
}

Delegate method

class SendMailViewController: MFMailComposeViewControllerDelegate {
   func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        dismiss(animated: true, completion: nil)
    }
}


答:
```<code>JSONObject json = new JSONObject(all_data);
 JSONArray jsonArray = json.getJSONArray("appointments");
</code>```

You should get array from the all_data, and use that one instead of json

Body:
I'm fairly new to Android dev, and am trying to write a programme to parse some JSON from a website and output it in a ListView. However, when I run my programme, I get the error: (There are more then 7 row same as this error)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/FAILED: Json parsing
error: Value
{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/FAILED: Json parsing error:
Value
{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

The JSON I'm trying to parse is:

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"},{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"},{"0":"4","id":"4","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-15","date":"2017-04-15","4":"20","hour":"20"},{"0":"5","id":"5","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-22","date":"2017-04-22","4":"20","hour":"20"},{"0":"6","id":"6","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-24","date":"2017-03-24","4":"17","hour":"17"},{"0":"7","id":"7","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"17","hour":"17"},{"0":"8","id":"8","1":"1","cid":"1","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"16","hour":"16"},{"0":"9","id":"9","1":"2","cid":"2","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"15","hour":"15"},{"0":"10","id":"10","1":"3","cid":"3","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"13","hour":"13"}]}

this my listview custom row java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

This is json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

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

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

If I don't parse:

Body:
JSONObject json = new JSONObject(all_data);
 JSONArray jsonArray = json.getJSONArray("appointments");

You should get array from the all_data, and use that one instead of json


问:
What does $(selector)[0] mean in jQuery?
The syntax that I don't understand is this:

```<code>$("#profilePhotoFileUpload")[0]
</code>```

I have been seeing this syntax pretty frequently and I've ignored it for a while because I never had to use it. But now, in order to understand the code from this post How do I upload an image using the Parse.com javascriptSDK?, I cannot ignore it any longer.

I know that [0] this syntax is used to refer to an array usually. But it seems a little weird that a reference to an id would generate an array of some sort.

答:
Well, don't confuse jQuery Object with DOM node/element.

this should be as simple as

```<code>$(this)[0] === this
</code>```

and

```<code>$("#target")[0] === document.getElementById("target");
</code>```

e.g.

```<code>// Setting the inner HTML with jQuery.
var target = document.getElementById("target");

// Comparing DOM elements.
alert($(target)[0] === target); // alerts "true"

// Comparing DOM element and jQuery element
alert($(target)[0] === $(target).eq(0)); // alerts "false"
</code>```

We must keep in mind that both $(target)[0] and $(target).get(0)
  return the same DOM element which has DOM properties like .innerHTML
  and methods like .appendChild(), but not jQuery methods like
  .html() or .after() whereas $(target).eq(0) returns a jQuery
  object which has useful methods like .html() and .after().

what's more

```<code>var logo1 = $("#logo");
var logo1Elem = logo1.get(0);

var logo2 = $("#logo");
var logo2Elem = $("#logo")[0];
</code>```

Although logo1 and logo2 are created in the same way (and wrap the same DOM element), they are not the same object.

```<code>// Comparing jQuery objects.
alert($("#logo") === $("#logo")); // alerts "false"

// Comparing DOM elements.
alert(logo1Elem === logo2Elem); // alerts "true"
</code>```

Ref: https://learn.jquery.com/using-jquery-core/jquery-object/

Body:
The syntax that I don't understand is this:

$("#profilePhotoFileUpload")[0]

I have been seeing this syntax pretty frequently and I've ignored it for a while because I never had to use it. But now, in order to understand the code from this post How do I upload an image using the Parse.com javascriptSDK?, I cannot ignore it any longer.

I know that [0] this syntax is used to refer to an array usually. But it seems a little weird that a reference to an id would generate an array of some sort.

Body:
Well, don't confuse jQuery Object with DOM node/element.

this should be as simple as

$(this)[0] === this

and

$("#target")[0] === document.getElementById("target");

e.g.

// Setting the inner HTML with jQuery.
var target = document.getElementById("target");

// Comparing DOM elements.
alert($(target)[0] === target); // alerts "true"

// Comparing DOM element and jQuery element
alert($(target)[0] === $(target).eq(0)); // alerts "false"

We must keep in mind that both $(target)[0] and $(target).get(0)
  return the same DOM element which has DOM properties like .innerHTML
  and methods like .appendChild(), but not jQuery methods like
  .html() or .after() whereas $(target).eq(0) returns a jQuery
  object which has useful methods like .html() and .after().

what's more

var logo1 = $("#logo");
var logo1Elem = logo1.get(0);

var logo2 = $("#logo");
var logo2Elem = $("#logo")[0];

Although logo1 and logo2 are created in the same way (and wrap the same DOM element), they are not the same object.

// Comparing jQuery objects.
alert($("#logo") === $("#logo")); // alerts "false"

// Comparing DOM elements.
alert(logo1Elem === logo2Elem); // alerts "true"

Ref: https://learn.jquery.com/using-jquery-core/jquery-object/


问:
Rolling back changes with reset and force push
i have seen similar topics here, but i didn't find the clear answer.

i have commited and pushed few changes on a remote branch, but that was a mistake and would like to reset this branch to the state it was couple of days ago. (using source tree btw)

```<code>- bad pushed commit
- bad pushed commit
- bad pushed commit
- place i want to return to
- older commits
</code>```

if i do a hard reset to the place i want to return to and then force push it. Will that do the trick, are there any issues with that ?

答:
you can try this

```<code>git reset HEAD~
</code>```

or reset to specific commit

```<code>git reset --hard <commit-hash>
git push -f origin master
</code>```

or more information for git

please follow this link :- https://git-scm.com/docs/git-reset

Body:
i have seen similar topics here, but i didn't find the clear answer.

i have commited and pushed few changes on a remote branch, but that was a mistake and would like to reset this branch to the state it was couple of days ago. (using source tree btw)

- bad pushed commit
- bad pushed commit
- bad pushed commit
- place i want to return to
- older commits

if i do a hard reset to the place i want to return to and then force push it. Will that do the trick, are there any issues with that ?

Body:
you can try this

git reset HEAD~

or reset to specific commit

git reset --hard <commit-hash>
git push -f origin master

or more information for git

please follow this link :- https://git-scm.com/docs/git-reset


问:
What is the best way to implement weight constraints in TensorFlow?
Suppose we have weights

```<code>x = tf.Variable(np.random.random((5,10)))
cost = ...
</code>```

And we use the GD optimizer:

```<code>upds = tf.train.GradientDescentOptimizer(lr).minimize(cost)
session.run(upds)
</code>```

How can we implement for example non-negativity on weights?

I tried clipping them:

```<code>upds = tf.train.GradientDescentOptimizer(lr).minimize(cost)
session.run(upds)
session.run(tf.assign(x, tf.clip_by_value(x, 0, np.infty)))
</code>```

But this slows down my training by a factor of 50.

Does anybody know a good way to implement such constraints on the weights in TensorFlow?

P.S.: in the equivalent Theano algorithm, I had

```<code>T.clip(x, 0, np.infty)
</code>```

and it ran smoothly.

答:
By running

```<code>sess.run(tf.assign(x, tf.clip_by_value(x, 0, np.infty)))
</code>```

you are consistently adding nodes to the graph and making it slower and slower.

Actually you may just define a clip_op when building the graph and run it each time after updating the weights:

```<code># build the graph
x = tf.Variable(np.random.random((5,10)))
loss = ...
train_op = tf.train.GradientDescentOptimizer(lr).minimize(loss)
clip_op = tf.assign(x, tf.clip(x, 0, np.infty))

# train
sess.run(train_op)
sess.run(clip_op)
</code>```

Body:
Suppose we have weights

x = tf.Variable(np.random.random((5,10)))
cost = ...

And we use the GD optimizer:

upds = tf.train.GradientDescentOptimizer(lr).minimize(cost)
session.run(upds)

How can we implement for example non-negativity on weights?

I tried clipping them:

upds = tf.train.GradientDescentOptimizer(lr).minimize(cost)
session.run(upds)
session.run(tf.assign(x, tf.clip_by_value(x, 0, np.infty)))

But this slows down my training by a factor of 50.

Does anybody know a good way to implement such constraints on the weights in TensorFlow?

P.S.: in the equivalent Theano algorithm, I had

T.clip(x, 0, np.infty)

and it ran smoothly.

Body:
By running

sess.run(tf.assign(x, tf.clip_by_value(x, 0, np.infty)))

you are consistently adding nodes to the graph and making it slower and slower.

Actually you may just define a clip_op when building the graph and run it each time after updating the weights:

# build the graph
x = tf.Variable(np.random.random((5,10)))
loss = ...
train_op = tf.train.GradientDescentOptimizer(lr).minimize(loss)
clip_op = tf.assign(x, tf.clip(x, 0, np.infty))

# train
sess.run(train_op)
sess.run(clip_op)


问:
R, dpylr handling variablenames that are identical to column names
When using dplyr and variablenames which are identical to column names, how do I distinguish between the two?

```<code>test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = test) # does not change anything
</code>```

I also tried something like

```<code>test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = interp(~x, x = as.name("test")))
</code>```

To force the use of the (global) variable "test" instead, unfortunately no success.

How do I handle such situations?

Edit:
When having non non-global vars, i.e. function arguments

```<code>foo <- function(test) {
  df <- data.frame(test = c(3,4))
  env <- environment()
  df %>% mutate(test = env[["test"]])
}
foo(1:2)
</code>```

Does the trick

答:
We can use .GlobalEnv to extract the objects

```<code>df %>%
    mutate(test = .GlobalEnv[["test"]])
#    test
#1    1
#2    2
</code>```

Body:
When using dplyr and variablenames which are identical to column names, how do I distinguish between the two?

test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = test) # does not change anything

I also tried something like

test <- c(1,2)
df <- data.frame(test = c(3,4))
df %>% mutate(test = interp(~x, x = as.name("test")))

To force the use of the (global) variable "test" instead, unfortunately no success.

How do I handle such situations?

Edit:
When having non non-global vars, i.e. function arguments

foo <- function(test) {
  df <- data.frame(test = c(3,4))
  env <- environment()
  df %>% mutate(test = env[["test"]])
}
foo(1:2)

Does the trick

Body:
We can use .GlobalEnv to extract the objects

df %>%
    mutate(test = .GlobalEnv[["test"]])
#    test
#1    1
#2    2


问:
Copying stuff from vim running in putty
I am running Vim 6.3 through putty and putty connection manager. I have the mouse option set (set mouse = a). I am able to paste things from the (windows) clipboard to vim by  but selecting text in vim  isn't copying anything to the clipboard. Does anyone know how do I do this?

Note: I can't update Vim to a newer version.

答: Hold down shift, and then highlight the text you want to copy using the left mouse button. When you release, the highlighted text should be in the Windows clipboard.</p>

Title: Copying stuff from vim running in putty


问:
angular 2 innerHTMLchange event binding?
Is there a way to do something like:

```<code><div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div>
</code>```

As my code sits, I have a variable content that gets updated from a service that gets a string from my express server. The content variable is set and the innerHTML is updated when the site loads. Now I have a javascript lib that needs to do calls on the added string to the innerHTML. The problem I currently have is that the contentInit() is called before the HTML is updated.

```<code>constructor(private service: StringService) {
    this.service.getString().subscribe((string) => {
        this.content = string;
        this.contentInit(); // called before innerHTML changes
    });
}

contentInit: void {
    var innerHTMLDiv = document.getElementById("innerHTML-div");
    //do stuff
}
</code>```

If the template can call the contentInit() when the innerHTML changes this should solve my problem as the innerHTML will be initiated and it can connect to the elements.

答:
Just invoke change detection explicitly instead of waiting for Angular to run the next cycle:</p>

```<code>constructor(private service: StringService, cdRef:ChangeDetectorRef) {
    this.service.getString().subscribe((string) => {
        this.content = string;
        cdRef.detectChanges(); // after that the DOM is updated
        this.contentInit(); // called before innerHTML changes
    });
}
</code>```

Body:
Is there a way to do something like:

As my code sits, I have a variable content that gets updated from a service that gets a string from my express server. The content variable is set and the innerHTML is updated when the site loads. Now I have a javascript lib that needs to do calls on the added string to the innerHTML. The problem I currently have is that the contentInit() is called before the HTML is updated.

constructor(private service: StringService) {
    this.service.getString().subscribe((string) => {
        this.content = string;
        this.contentInit(); // called before innerHTML changes
    });
}

contentInit: void {
    var innerHTMLDiv = document.getElementById("innerHTML-div");
    //do stuff
}

If the template can call the contentInit() when the innerHTML changes this should solve my problem as the innerHTML will be initiated and it can connect to the elements.

Body:
Just invoke change detection explicitly instead of waiting for Angular to run the next cycle:

constructor(private service: StringService, cdRef:ChangeDetectorRef) {
    this.service.getString().subscribe((string) => {
        this.content = string;
        cdRef.detectChanges(); // after that the DOM is updated
        this.contentInit(); // called before innerHTML changes
    });
}


问:
How to increment numeric part of a string by one?
I have a string formed up by numbers and sometimes by letters.

Example AF-1234 or 345ww.

I have to get the numeric part and increment it by one.

how can I do that? maybe with regex?

答:
You can use preg_replace_callback as:

```<code>function inc($matches) {
    return ++$matches[1];
}

$input = preg_replace_callback("|(\d+)|", "inc", $input);
</code>```

Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.

Ideone link

Alternatively this can be done using preg_replace() with the e modifier as:

```<code> $input = preg_replace("|(\d+)|e", "$1+1", $input);
</code>```

Ideone link

Body:
You can use preg_replace_callback as:

function inc($matches) {
    return ++$matches[1];
}

$input = preg_replace_callback("|(\d+)|", "inc", $input);

Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.

Ideone link

Alternatively this can be done using preg_replace() with the e modifier as:

 $input = preg_replace("|(\d+)|e", "$1+1", $input);

Ideone link


问:
How to specify response type in ASP.NET Core middleware
My controllers return unified RequestResult:

```<code>public Task<RequestResult> SomeAction()
{
  ...
  return new RequestResult(RequestResultType.NotFound);
}

public class RequestResult
{
  public RequestResultType Type { get;set; }
  ... //actual data
}

public enum RequestResultType
{
   Success = 1,
   NotFound = 2
}
</code>```

So basically RequestResult combines actual Action data and error type (if it happened). Now I need to specify Response Type at some point in case if Action returned Error. My best guess here is to use Middleware:

```<code>public class ResponseTypeMiddleware
{
  private readonly RequestDelegate next;

  public ResponseTypeMiddleware(RequestDelegate next)
  {
    this.next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    await next(context);

    var response = context.Response.Body; //how to access object?
  }
}
</code>```

but I can't figure out what to do with it. What I'd perfectly like to do is to check if response is of type RequestResult, then specify ResponseType equal BadRequest. But I don't see how I can do it here as what I have is just a stream. May be I can hijack into pipeline earlier, before result was serialized (Controller?).

P. S. The reason why I don't use Controller.BadRequest directly in Action is that my Action's logic is implemented via CQRS command/query handlers, so I don't have direct access to Controller.

答:
As you are going to process controller's action result (MVC), the best way is to use ActionFilter or ResultFilter here, instead of Middleware. Filters in ASP.NET Core are a part of MVC and so know about controllers, actions and so on. Middleware is a more common conception - it is an additional chain in application request-response pipeline.

```<code>public class SampleActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // do something before the action executes
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do something after the action executes

        // get or set controller action result here
        var result = context.Result as RequestResult;
    }
}
</code>```

Body:
My controllers return unified RequestResult:

public Task<RequestResult> SomeAction()
{
  ...
  return new RequestResult(RequestResultType.NotFound);
}

public class RequestResult
{
  public RequestResultType Type { get;set; }
  ... //actual data
}

public enum RequestResultType
{
   Success = 1,
   NotFound = 2
}

So basically RequestResult combines actual Action data and error type (if it happened). Now I need to specify Response Type at some point in case if Action returned Error. My best guess here is to use Middleware:

public class ResponseTypeMiddleware
{
  private readonly RequestDelegate next;

  public ResponseTypeMiddleware(RequestDelegate next)
  {
    this.next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    await next(context);

    var response = context.Response.Body; //how to access object?
  }
}

but I can't figure out what to do with it. What I'd perfectly like to do is to check if response is of type RequestResult, then specify ResponseType equal BadRequest. But I don't see how I can do it here as what I have is just a stream. May be I can hijack into pipeline earlier, before result was serialized (Controller?).

P. S. The reason why I don't use Controller.BadRequest directly in Action is that my Action's logic is implemented via CQRS command/query handlers, so I don't have direct access to Controller.

Body:
As you are going to process controller's action result (MVC), the best way is to use ActionFilter or ResultFilter here, instead of Middleware. Filters in ASP.NET Core are a part of MVC and so know about controllers, actions and so on. Middleware is a more common conception - it is an additional chain in application request-response pipeline.

public class SampleActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // do something before the action executes
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do something after the action executes

        // get or set controller action result here
        var result = context.Result as RequestResult;
    }
}


问:
jQuery trigger("click") not working
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

```<code><!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
</code>```

答:
Add the click event handler to the element. Then only it will work.

Check the below snippet.

Try placing mouse over the link and it will trigger the click event handler.

$(document).ready(function() {
  $("#linkElement").mouseover(function() {
    $("#linkElement").trigger("click");
  });
  $("#linkElement").click(function(){
    window.location.href=$("#linkElement").attr("href");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
  click

  <select name="cars" id="selectElemet">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>
</body>

</html></code>```

Title: jQuery trigger("click") not working

Body:
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>

    click

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

Body:
Add the click event handler to the element. Then only it will work.

Check the below snippet.

Try placing mouse over the link and it will trigger the click event handler.

$(document).ready(function() {
  $("#linkElement").mouseover(function() {
    $("#linkElement").trigger("click");
  });
  $("#linkElement").click(function(){
    window.location.href=$("#linkElement").attr("href");
  });
});

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
  <a id="linkElement" href="www.google.co.uk">click</a>

  <select name="cars" id="selectElemet">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>
</body>

</html>


问:
User Authentication with EntityFrameworkCore and MySQL DB not working
I am developing a .Net Core Web Application using Entity Framework and MySQL and when I try to register as a user, I get the following message.

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: Connection must be valid and open to commit transaction
MySql.Data.MySqlClient.MySqlTransaction.Commit()
</code>```

This is my DB Context

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

    }
}
</code>```

}

And this is my Startup code

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

    }
</code>```

--UPDATE----

I Found out that the Authentication mechanism is done by Ajax not EF, the problem seems to stem from this line of code.

```<code>    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
   PROBLEM LINE====>         var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "User created a new account with password.");
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }
</code>```

答:
I was having this exact same problem amonst a few others the other night. It's some kind of issue with async and the Oracle MySQL provider. If you override your DbContext's dispose method and put a breakpoint in there, you see the context gets disposed before some of the sign in steps are done. I found another SO question (can't find it right now on mobile), that had similar issues and recommended replacing Oracle MySQL package with this one:

https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

This fixed the problem and another problem I was having related to handling of varbinary data types longer than 255 when adding migrations.

Also remember the DbContext is loaded into the DI container in the "scoped" lifetime (by default), which means it is a single instance per http request, so make sure your code or any middleware you have in place isn't disposing the DbContext after getting it from the service container.

Body:
I am developing a .Net Core Web Application using Entity Framework and MySQL and when I try to register as a user, I get the following message.

An unhandled exception occurred while processing the request.
InvalidOperationException: Connection must be valid and open to commit transaction
MySql.Data.MySqlClient.MySqlTransaction.Commit()

This is my DB Context

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

    }
}

}

And this is my Startup code

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

    }

--UPDATE----

I Found out that the Authentication mechanism is done by Ajax not EF, the problem seems to stem from this line of code.

    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
   PROBLEM LINE====>         var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "User created a new account with password.");
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }


问:
DBMS_SCHEDULER.get_file data issue
I am trying to get the output from the stdout and stderr files using the DBMS_SCHEDULER.get_file package. But the data is getting displayed in binary form. How do I convert that to varchar2?

```<code>SET SERVEROUTPUT ON
DECLARE
  l_clob             CLOB;
  l_additional_info  VARCHAR2(100);
  l_external_log_id  VARCHAR2(100);
BEGIN
  SELECT additional_info, external_log_id
  INTO   l_additional_info, l_external_log_id
  FROM   (SELECT log_id,
             additional_info,
             REGEXP_SUBSTR(additional_info,'job[_0-9]*') AS external_log_id
          FROM   user_scheduler_job_run_details
          WHERE  job_name = 'SCRIPT_DISABLE_USER'
          ORDER BY log_id DESC)
  WHERE  ROWNUM = 1;

  DBMS_OUTPUT.put_line('ADDITIONAL_INFO: ' || l_additional_info);
  DBMS_OUTPUT.put_line('EXTERNAL_LOG_ID: ' || l_external_log_id);

  dbms_scheduler.create_credential
  (credential_name => 'WORKFLOW_CRED1',
  username => 'dsadasd',
  password => 'dasdsa');

  DBMS_LOB.createtemporary(l_clob, FALSE);

  DBMS_SCHEDULER.get_file(
  source_file     => l_external_log_id ||'_stdout',
  credential_name => 'WORKFLOW_CRED',
  file_contents   => l_clob,
  source_host     => NULL);

  DBMS_OUTPUT.put_line('stdout:');
  DBMS_OUTPUT.put_line(l_clob);
  dbms_scheduler.drop_credential('WORKFLOW_CRED1');
END;
/
</code>```

Output Generated:

```<code>anonymous block completed
ADDITIONAL_INFO: EXTERNAL_LOG_ID="job_44793_12759",
USERNAME="workflow"
EXTERNAL_LOG_ID: job_44793_12759
stdout:
㈰ㄵⴰ㐭ㄳ弱ㄺ㐶㨳〠ⴠ卣物灴慵湣桥搠睩瑨牧畭敮琠❲浩整畳✮ਲ〱㔭〴ⴱ㍟ㄱ㨴㘺㌳⁕獥爠❲浩整   畳✠獵捣敳獦畬汹楳慢汥搮ਲ〱㔭〴ⴱ㍟ㄱ㨴㘺㌳⁅硩瑩湧⁷楴栠牥瑵牮潤攠〮
</code>```

Any help is much appreciated. Thanks..

答:
file_contents in mulibyte characters. They should be read by more complicated method: get file_contents into blob and then convert to clob like

```<code>    function blob_to_clob (p_blob in blob) return clob as
  l_clob    clob;
  l_varchar varchar2(32767);
  l_start      pls_integer := 1;
  l_buffer  pls_integer := 32767;
begin
  dbms_lob.createtemporary(l_clob, true);
  for i in 1..ceil(dbms_lob.getlength(p_blob) / l_buffer)
  loop
    l_varchar := utl_raw.cast_to_varchar2(dbms_lob.substr(p_blob, l_buffer, l_start));
    dbms_lob.writeappend(l_clob, length(l_varchar), l_varchar);
    l_start := l_start + l_buffer;
  end loop;
  return l_clob;
end;
</code>```

Title: DBMS_SCHEDULER.get_file data issue

Body:
I am trying to get the output from the stdout and stderr files using the DBMS_SCHEDULER.get_file package. But the data is getting displayed in binary form. How do I convert that to varchar2?

SET SERVEROUTPUT ON
DECLARE
  l_clob             CLOB;
  l_additional_info  VARCHAR2(100);
  l_external_log_id  VARCHAR2(100);
BEGIN
  SELECT additional_info, external_log_id
  INTO   l_additional_info, l_external_log_id
  FROM   (SELECT log_id,
             additional_info,
             REGEXP_SUBSTR(additional_info,'job[_0-9]*') AS external_log_id
          FROM   user_scheduler_job_run_details
          WHERE  job_name = 'SCRIPT_DISABLE_USER'
          ORDER BY log_id DESC)
  WHERE  ROWNUM = 1;

  DBMS_OUTPUT.put_line('ADDITIONAL_INFO: ' || l_additional_info);
  DBMS_OUTPUT.put_line('EXTERNAL_LOG_ID: ' || l_external_log_id);

  dbms_scheduler.create_credential
  (credential_name => 'WORKFLOW_CRED1',
  username => 'dsadasd',
  password => 'dasdsa');

  DBMS_LOB.createtemporary(l_clob, FALSE);

  DBMS_SCHEDULER.get_file(
  source_file     => l_external_log_id ||'_stdout',
  credential_name => 'WORKFLOW_CRED',
  file_contents   => l_clob,
  source_host     => NULL);

  DBMS_OUTPUT.put_line('stdout:');
  DBMS_OUTPUT.put_line(l_clob);
  dbms_scheduler.drop_credential('WORKFLOW_CRED1');
END;
/

Output Generated:

anonymous block completed
ADDITIONAL_INFO: EXTERNAL_LOG_ID="job_44793_12759",
USERNAME="workflow"
EXTERNAL_LOG_ID: job_44793_12759
stdout:
㈰ㄵⴰ㐭ㄳ弱ㄺ㐶㨳〠ⴠ卣物灴慵湣桥搠睩瑨牧畭敮琠❲浩整畳✮ਲ〱㔭〴ⴱ㍟ㄱ㨴㘺㌳⁕獥爠❲浩整   畳✠獵捣敳獦畬汹楳慢汥搮ਲ〱㔭〴ⴱ㍟ㄱ㨴㘺㌳⁅硩瑩湧⁷楴栠牥瑵牮潤攠〮

Any help is much appreciated. Thanks..

Body:
file_contents in mulibyte characters. They should be read by more complicated method: get file_contents into blob and then convert to clob like

    function blob_to_clob (p_blob in blob) return clob as
  l_clob    clob;
  l_varchar varchar2(32767);
  l_start      pls_integer := 1;
  l_buffer  pls_integer := 32767;
begin
  dbms_lob.createtemporary(l_clob, true);
  for i in 1..ceil(dbms_lob.getlength(p_blob) / l_buffer)
  loop
    l_varchar := utl_raw.cast_to_varchar2(dbms_lob.substr(p_blob, l_buffer, l_start));
    dbms_lob.writeappend(l_clob, length(l_varchar), l_varchar);
    l_start := l_start + l_buffer;
  end loop;
  return l_clob;
end;


问:
DataGrid validation display error problem
I have a little problem with the silverlight data grid. I wrote a little sample app to show the problem. (You can download it here: http://rapidshare.com/files/433480041/DataGridValidationTest.zip).

Here you can Add a new Person (has a Name and an Age) to a Collection which is displayed in a DataGrid.
 I also implemented the validation based on the INotifyDataErrorInfo interface. If you click save, the data is validatet (Name must not be null, Age gt 0).

The validation works fine, but the validation errors are only displayed if I click into one row. After clicking the Save Button, the data is validatet, but not shown in the grid (see picture below):

If I click in the row, to change the data, the validation message is shown (picture below):

If I'm in that row, I have to resolve the problem, cause I'm not able to select another cell.

Does anyone know, how I can show (all) errors directly in the grid?
And can I get out of the cell with the error without resolving the problem?

Thx in advance,

TJ

答:
As far as I know, in Silverlight datagrid, only one row would be active at a time, so if you want to valudate all rows at the same time, it is not possible.

Another workaround is add your all content in the same cell. So all your data would be editable and it would be validated at the same time as well. What I mean is

If you have grid with 2 columns -

<DataGrid>
<Name>
<Age>
</DataGrid>

make it look like this
<Grid>
<Cell>
<Grid>
<Name>
<Age>
</Grid>
</Cell></DataGrid>


问:
how can I validate whether values entered in a new form is reflected correctly in edit form
I am trying to automate a website which is mainly dealing with Forms. I have entered values in new form and I need to validate whether it is reflected back correctly in edit form.
In New form I have tried like :

```<code> WebElement FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
 FN.click();
 FN.sendKeys("abc");
</code>```

In the edit form code:

```<code> if(FN.getAttribute("value").equals("abc"))
    System.out.println("First Name is matching with new form");
 else
    System.out.println("First Name is not matching with new form");
</code>```

and I am getting error like

```<code> Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document(Session info: chrome=57.0.2987.110)
</code>```

Thanks in advance .

答:
You need to reinitialize the FN Webelement once you are at edit form, as the previous FN Webelement will become stale as soon as you move away from new form. Hence, try following:

```<code>FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
if(FN.getAttribute("value").equals("abc"))
    System.out.println("First Name is matching with new form");
else
    System.out.println("First Name is not matching with new form");
</code>```

Let me know, if you have any further queries.

Body:
I am trying to automate a website which is mainly dealing with Forms. I have entered values in new form and I need to validate whether it is reflected back correctly in edit form.
In New form I have tried like :

 WebElement FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
 FN.click();
 FN.sendKeys("abc");

In the edit form code:

 if(FN.getAttribute("value").equals("abc"))
    System.out.println("First Name is matching with new form");
 else
    System.out.println("First Name is not matching with new form");

and I am getting error like

 Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document(Session info: chrome=57.0.2987.110)

Thanks in advance .

Body:
You need to reinitialize the FN Webelement once you are at edit form, as the previous FN Webelement will become stale as soon as you move away from new form. Hence, try following:

FN = driver.findElement(By.id("ctl00_ctl41_g_1fc852c8_32cb_4220_80ee_2af21b671f9e_ff21_ctl00_ctl00_TextField"));
if(FN.getAttribute("value").equals("abc"))
    System.out.println("First Name is matching with new form");
else
    System.out.println("First Name is not matching with new form");

Let me know, if you have any further queries.


问:
HTML5 canvas create outer glow effect of shape
I want to create an outer glow effect for arc shapes in my canvas tag.
This is what it's supposed to look like:

So far I have the circles in white. I tried using a dropShadow that has an Offset of '0', but this doesn't look right.

What do you suggest? Maybe shapes underneath that have a gradient from blue to black?
Thanks in advance!

Edit: Finally got it working. Used a for loop to draw circles with different radius and alpha.

答:
The loop is the solution, indeed, but without playing the radius and the alpha. Simple set the linewidth thick and the shadow with zero offsets and decent blur, then draw the arcs in a loop of... some... like with 10 it will shine.</p>

```<code>ctx.fillStyle='black';
ctx.fillRect(0,0,500,500);
ctx.lineWidth=25;
ctx.strokeStyle='white';
ctx.shadowColor='blue';
ctx.shadowOffsetX=0;
ctx.shadowOffsetY=0;
ctx.shadowBlur=25;
for(a=0;a<10;a++) {
    ctx.beginPath();
    ctx.arc(250,250,200,Math.PI/12,23*Math.PI/12);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(250,250,100,7*Math.PI/12,5*Math.PI/12);
    ctx.stroke();
}
</code>```

Body:
The loop is the solution, indeed, but without playing the radius and the alpha. Simple set the linewidth thick and the shadow with zero offsets and decent blur, then draw the arcs in a loop of... some... like with 10 it will shine.

ctx.fillStyle='black';
ctx.fillRect(0,0,500,500);
ctx.lineWidth=25;
ctx.strokeStyle='white';
ctx.shadowColor='blue';
ctx.shadowOffsetX=0;
ctx.shadowOffsetY=0;
ctx.shadowBlur=25;
for(a=0;a<10;a++) {
    ctx.beginPath();
    ctx.arc(250,250,200,Math.PI/12,23*Math.PI/12);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(250,250,100,7*Math.PI/12,5*Math.PI/12);
    ctx.stroke();
}


问:
Materialize autocomplete with dynamic data in jquery ajax
I'm using materialize ui in an ASP.Net MVC application and I'm using an autocomplete control with dynamic data.

Here is my code,

```<code><div class="row">
    <div class="col s12">
        <div class="row">
            <div class="input-field col s12">
                <i class="material-icons prefix">textsms</i>
                <input type="text" id="autocomplete-input" class="autocomplete">
                <label for="autocomplete-input">Autocomplete</label>
            </div>
        </div>
    </div>
</div>
</code>```

This is the jquery ajax call,

```<code>$(function () {
    $.ajax({
        type: 'GET', // your request type
        url: "/Home/GetData/",
        success: function (response) {
            var myArray = $.parseJSON(response);

            debugger;
            $('input.autocomplete').autocomplete({
                data: {
                    "Arizona (1)": null,
                    "Florida (2)": null,
                    "Georgia (3)": null,
                    "Hawaii(4)": null,
                    "Idaho (5)": null,
                    "Illinois (6)": null
                }
            });
        }
    });
});
</code>```

It can accept data only in this format and this is my response,

```<code>"[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]"
</code>```

How do I convert my response into the format that autocomplete understands?

答:
you can easily achieve the autocomplete functionality using the Devberidge plugin.

Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete

```<code>     <script type="text/javascript">

    $(document).ready(function() {

              $("#country").devbridgeAutocomplete({
                //lookup: countries,
                serviceUrl:"getCountry.php", //tell the script where to send requests
                  type:'POST',

                  //callback just to show it's working
                  onSelect: function (suggestion) {
                     // $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results',

              });

    });

  </script>
</code>```

Here the getCountry.php file returns the JSON data.
For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php

Body:
I'm using materialize ui in an ASP.Net MVC application and I'm using an autocomplete control with dynamic data.

Here is my code,

                textsms
                <input type="text" id="autocomplete-input" class="autocomplete">
                Autocomplete

This is the jquery ajax call,

$(function () {
    $.ajax({
        type: 'GET', // your request type
        url: "/Home/GetData/",
        success: function (response) {
            var myArray = $.parseJSON(response);

            debugger;
            $('input.autocomplete').autocomplete({
                data: {
                    "Arizona (1)": null,
                    "Florida (2)": null,
                    "Georgia (3)": null,
                    "Hawaii(4)": null,
                    "Idaho (5)": null,
                    "Illinois (6)": null
                }
            });
        }
    });
});

It can accept data only in this format and this is my response,

"[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]"

How do I convert my response into the format that autocomplete understands?

Body:
you can easily achieve the autocomplete functionality using the Devberidge plugin.

Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete

     <script type="text/javascript">

    $(document).ready(function() {

              $("#country").devbridgeAutocomplete({
                //lookup: countries,
                serviceUrl:"getCountry.php", //tell the script where to send requests
                  type:'POST',

                  //callback just to show it's working
                  onSelect: function (suggestion) {
                     // $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
                    },
                showNoSuggestionNotice: true,
                noSuggestionNotice: 'Sorry, no matching results',

              });

    });

  </script>

Here the getCountry.php file returns the JSON data.
For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php


问:
how to use Tango3DR_updateTexture?
I am trying to make 3DR texturing but it always use only vertex colors in texture.

On every frame I store frame as PNG:

```<code>    RGBImage frame(t3dr_image, 4);
    std::ostringstream ss;
    ss << dataset_.c_str();
    ss << "/";
    ss << poses_.size();
    ss << ".png";
    frame.Write(ss.str().c_str());
    poses_.push_back(t3dr_image_pose);
    timestamps_.push_back(t3dr_image.timestamp);
</code>```

In the method Save I am trying to process texturing:

1) I extract full mesh from context

```<code>    Tango3DR_Mesh* mesh = 0;
    Tango3DR_Status ret;
    ret = Tango3DR_extractFullMesh(t3dr_context_, &mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
</code>```

2) Create texturing context using extracted mesh

```<code>    Tango3DR_ConfigH textureConfig;
    textureConfig = Tango3DR_Config_create(TANGO_3DR_CONFIG_TEXTURING);
    ret = Tango3DR_Config_setDouble(textureConfig, "min_resolution", 0.01);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    Tango3DR_TexturingContext context;
    context = Tango3DR_createTexturingContext(textureConfig, dataset.c_str(), mesh);
    if (context == nullptr)
        std::exit(EXIT_SUCCESS);
    Tango3DR_Config_destroy(textureConfig);
</code>```

3) Call Tango3DR_updateTexture with data I stored before (this does not work)

```<code>    for (unsigned int i = 0; i < poses_.size(); i++) {
        std::ostringstream ss;
        ss << dataset_.c_str();
        ss << "/";
        ss << i;
        ss << ".png";
        RGBImage frame(ss.str());
        Tango3DR_ImageBuffer image;
        image.width = frame.GetWidth();
        image.height = frame.GetHeight();
        image.stride = frame.GetWidth() * 3;
        image.timestamp = timestamps_[i];
        //data are for sure in this format
        image.format = TANGO_3DR_HAL_PIXEL_FORMAT_RGB_888;
        image.data = frame.GetData();
        ret = Tango3DR_updateTexture(context, &image, &poses_[i]);
        if (ret != TANGO_3DR_SUCCESS)
            std::exit(EXIT_SUCCESS);
    }
</code>```

4) Texturize mesh

```<code>    ret = Tango3DR_Mesh_destroy(mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    mesh = 0;
    ret = Tango3DR_getTexturedMesh(context, &mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
</code>```

5) Save it as OBJ (in the result texture are only data from vertex colors, why?)

```<code>    ret = Tango3DR_Mesh_saveToObj(mesh, filename.c_str());
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    ret = Tango3DR_destroyTexturingContext(context);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    ret = Tango3DR_Mesh_destroy(mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
</code>```

All methods returned TANGO_3DR_SUCCESS.

Full code here: https://github.com/lvonasek/tango

答:
Thanks for reaching out and providing the detailed code breakdown.

The error is on our end - the library currently doesn't support RGB texture inputs. It assumes YUV for all input images. I've opened a ticket to track this bug and we'll fix it for the next release, by allowing RGB input and providing better return values for invalid image formats.

Edit: Found another bug on our end. The API states image_pose should be the pose of the image, but our implementation actually expects the pose of the device. I've opened a bug, and this will be fixed in next release (release-H).

You can try working around this for now by passing in the device pose without multiplying the device-to-camera extrinsic calibration, although of course that's just a temp bandaid.

Title: how to use Tango3DR_updateTexture?

Body:
I am trying to make 3DR texturing but it always use only vertex colors in texture.

On every frame I store frame as PNG:

    RGBImage frame(t3dr_image, 4);
    std::ostringstream ss;
    ss << dataset_.c_str();
    ss << "/";
    ss << poses_.size();
    ss << ".png";
    frame.Write(ss.str().c_str());
    poses_.push_back(t3dr_image_pose);
    timestamps_.push_back(t3dr_image.timestamp);

In the method Save I am trying to process texturing:

1) I extract full mesh from context

    Tango3DR_Mesh* mesh = 0;
    Tango3DR_Status ret;
    ret = Tango3DR_extractFullMesh(t3dr_context_, &mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);

2) Create texturing context using extracted mesh

    Tango3DR_ConfigH textureConfig;
    textureConfig = Tango3DR_Config_create(TANGO_3DR_CONFIG_TEXTURING);
    ret = Tango3DR_Config_setDouble(textureConfig, "min_resolution", 0.01);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    Tango3DR_TexturingContext context;
    context = Tango3DR_createTexturingContext(textureConfig, dataset.c_str(), mesh);
    if (context == nullptr)
        std::exit(EXIT_SUCCESS);
    Tango3DR_Config_destroy(textureConfig);

3) Call Tango3DR_updateTexture with data I stored before (this does not work)

    for (unsigned int i = 0; i < poses_.size(); i++) {
        std::ostringstream ss;
        ss << dataset_.c_str();
        ss << "/";
        ss << i;
        ss << ".png";
        RGBImage frame(ss.str());
        Tango3DR_ImageBuffer image;
        image.width = frame.GetWidth();
        image.height = frame.GetHeight();
        image.stride = frame.GetWidth() * 3;
        image.timestamp = timestamps_[i];
        //data are for sure in this format
        image.format = TANGO_3DR_HAL_PIXEL_FORMAT_RGB_888;
        image.data = frame.GetData();
        ret = Tango3DR_updateTexture(context, &image, &poses_[i]);
        if (ret != TANGO_3DR_SUCCESS)
            std::exit(EXIT_SUCCESS);
    }

4) Texturize mesh

    ret = Tango3DR_Mesh_destroy(mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    mesh = 0;
    ret = Tango3DR_getTexturedMesh(context, &mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);

5) Save it as OBJ (in the result texture are only data from vertex colors, why?)

    ret = Tango3DR_Mesh_saveToObj(mesh, filename.c_str());
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    ret = Tango3DR_destroyTexturingContext(context);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);
    ret = Tango3DR_Mesh_destroy(mesh);
    if (ret != TANGO_3DR_SUCCESS)
        std::exit(EXIT_SUCCESS);

All methods returned TANGO_3DR_SUCCESS.

Full code here: https://github.com/lvonasek/tango