问:
DatabaseException: Can't convert object of type java.lang.String to type
I've looked at a few other answers for similar problems but don't understand why mine isn't working.

I'm trying to get my app to read commands from Firebase and move a drone. The command in firebase comes from a separate software. The app is built on top of the Parrot Drone SDK Sample code.

It seems to be able to get the text from the command object and append it to a textview, but when a new child is added it just crashes. I'm getting this error when a new child is added.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                Process: com.parrot.sdksample, PID: 10592
                com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.parrot.sdksample.activity.CommandObject
                    at com.google.android.gms.internal.zg.zzb(Unknown Source)
                    at com.google.android.gms.internal.zg.zza(Unknown Source)
                    at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                    at com.parrot.sdksample.activity.MiniDroneActivity$13.onChildAdded(MiniDroneActivity.java:383)
                    at com.google.android.gms.internal.px.zza(Unknown Source)
                    at com.google.android.gms.internal.vj.zzHX(Unknown Source)
                    at com.google.android.gms.internal.vp.run(Unknown Source)
                    at android.os.Handler.handleCallback(Handler.java:739)
                    at android.os.Handler.dispatchMessage(Handler.java:95)
                    at android.os.Looper.loop(Looper.java:148)
                    at android.app.ActivityThread.main(ActivityThread.java:5417)
                    at java.lang.reflect.Method.invoke(Native Method)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

A sample of my data structure in firebase is below.

```<code>{
"drones" : {
    "commands" : {
    "-L-n9HwaQktOdI2VEVlH" : {
        "executed" : false,
        "text" : "TAKE_OFF",
        "timestamp" : 1.512686825309134E9
    },
    "-L-nAuK5Ifde7Cdnan8K" : {
        "executed" : false,
        "text" : "LAND",
        "timestamp" : 1.512687248764272E9
    }
    }
}
}
</code>```

The function in my activity to get data from firebase looks like this.

```<code>private void initFirebase(){
        mCommandTextView = (TextView) findViewById(R.id.commandTextView);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference commandsRef = database.getReference("drones/commands");

        ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
                CommandObject command = dataSnapshot.getValue(CommandObject.class);
                mCommandTextView.append(command.text + "\n");
// I've tried commenting out the if statements below this, but it doesn't seem to make a difference.
                if ("TAKE_OFF".equals(command.text)) {
                    mMiniDrone.takeOff();
                } else if ("LAND".equals(command.text)) {
                    mMiniDrone.land();
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName){

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName){

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        commandsRef.addChildEventListener(childEventListener);
    }
</code>```

My CommandObject class looks like this.

```<code>public class CommandObject {
    public String text;
    public float timestamp;
    public boolean executed;

    public CommandObject() {
    }

    public CommandObject(boolean executed, String text, float timestamp){
        this.executed = executed;
        this.text = text;
        this.timestamp = timestamp;
    }
}
</code>```

I've also tried using a value event listener instead, but the same problem occured.

答:
You are getting this error:

```<code>Can't convert object of type java.lang.String to type com.parrot.sdksample.activity.CommandObject
</code>```

Because you are trying to read the data of type String which is of type CommandObject and that why you are getting this error.

A more simple way to get those values would be to use the String class like this:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference commandsRef = rootRef.child("drones").child("commands");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            boolean executed = ds.child("executed").getValue(Boolean.class);
            String text = ds.child("text").getValue(String.class);
            double timestamp = ds.child("timestamp").getValue(Double.class);
            Log.d("TAG", executed + " / " + text + " / " + timestamp);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
commandsRef.addListenerForSingleValueEvent(eventListener);
</code>```

And this the approach using an object of CommandObject class:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference commandsRef = rootRef.child("drones").child("commands");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            CommandObject commandObject = ds.getValue(CommandObject.class);
            Log.d("TAG", commandObject.getExecuted() + " / " +
                commandObject.getText() + " / " +
                commandObject.getTimestamp());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
commandsRef.addListenerForSingleValueEvent(eventListener);
</code>```

In both cases your output will be:

```<code>false / TAKE_OFF / 1.512686825309134E9
false / LAND / 1.512687248764272E9
</code>```

Body:
I've looked at a few other answers for similar problems but don't understand why mine isn't working.

I'm trying to get my app to read commands from Firebase and move a drone. The command in firebase comes from a separate software. The app is built on top of the Parrot Drone SDK Sample code.

It seems to be able to get the text from the command object and append it to a textview, but when a new child is added it just crashes. I'm getting this error when a new child is added.

E/AndroidRuntime: FATAL EXCEPTION: main
                Process: com.parrot.sdksample, PID: 10592
                com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.parrot.sdksample.activity.CommandObject
                    at com.google.android.gms.internal.zg.zzb(Unknown Source)
                    at com.google.android.gms.internal.zg.zza(Unknown Source)
                    at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                    at com.parrot.sdksample.activity.MiniDroneActivity$13.onChildAdded(MiniDroneActivity.java:383)
                    at com.google.android.gms.internal.px.zza(Unknown Source)
                    at com.google.android.gms.internal.vj.zzHX(Unknown Source)
                    at com.google.android.gms.internal.vp.run(Unknown Source)
                    at android.os.Handler.handleCallback(Handler.java:739)
                    at android.os.Handler.dispatchMessage(Handler.java:95)
                    at android.os.Looper.loop(Looper.java:148)
                    at android.app.ActivityThread.main(ActivityThread.java:5417)
                    at java.lang.reflect.Method.invoke(Native Method)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A sample of my data structure in firebase is below.

{
"drones" : {
    "commands" : {
    "-L-n9HwaQktOdI2VEVlH" : {
        "executed" : false,
        "text" : "TAKE_OFF",
        "timestamp" : 1.512686825309134E9
    },
    "-L-nAuK5Ifde7Cdnan8K" : {
        "executed" : false,
        "text" : "LAND",
        "timestamp" : 1.512687248764272E9
    }
    }
}
}

The function in my activity to get data from firebase looks like this.

private void initFirebase(){
        mCommandTextView = (TextView) findViewById(R.id.commandTextView);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference commandsRef = database.getReference("drones/commands");

        ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
                CommandObject command = dataSnapshot.getValue(CommandObject.class);
                mCommandTextView.append(command.text + "\n");
// I've tried commenting out the if statements below this, but it doesn't seem to make a difference.
                if ("TAKE_OFF".equals(command.text)) {
                    mMiniDrone.takeOff();
                } else if ("LAND".equals(command.text)) {
                    mMiniDrone.land();
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName){

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName){

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        commandsRef.addChildEventListener(childEventListener);
    }

My CommandObject class looks like this.

public class CommandObject {
    public String text;
    public float timestamp;
    public boolean executed;

    public CommandObject() {
    }

    public CommandObject(boolean executed, String text, float timestamp){
        this.executed = executed;
        this.text = text;
        this.timestamp = timestamp;
    }
}

I've also tried using a value event listener instead, but the same problem occured.

Body:
You are getting this error:

Can't convert object of type java.lang.String to type com.parrot.sdksample.activity.CommandObject

Because you are trying to read the data of type String which is of type CommandObject and that why you are getting this error.

A more simple way to get those values would be to use the String class like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference commandsRef = rootRef.child("drones").child("commands");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            boolean executed = ds.child("executed").getValue(Boolean.class);
            String text = ds.child("text").getValue(String.class);
            double timestamp = ds.child("timestamp").getValue(Double.class);
            Log.d("TAG", executed + " / " + text + " / " + timestamp);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
commandsRef.addListenerForSingleValueEvent(eventListener);

And this the approach using an object of CommandObject class:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference commandsRef = rootRef.child("drones").child("commands");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            CommandObject commandObject = ds.getValue(CommandObject.class);
            Log.d("TAG", commandObject.getExecuted() + " / " +
                commandObject.getText() + " / " +
                commandObject.getTimestamp());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
commandsRef.addListenerForSingleValueEvent(eventListener);

In both cases your output will be:

false / TAKE_OFF / 1.512686825309134E9
false / LAND / 1.512687248764272E9


来源: stackexchange

问:
RecognizerIntent not working; "missing extra calling_package"
I'm having problems using the RecognizerIntent API on Android 2.2. When I call the API using this code:

```<code>Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
startActivityForResult(intent, REQUEST_CODE_VOICE_SEARCH);
</code>```

which looks like it should work, the search popup says "Unknown problem" on the device and in the logs it states:

```<code>01-17 14:25:30.433: ERROR/RecognitionActivity(9118): ACTION_RECOGNIZE_SPEECH intent called incorrectly. Maybe you called startActivity, but you should have called startActivityForResult (or otherwise included a pending intent).
01-17 14:25:30.433: INFO/RecognitionControllerImpl(9118): startRecognition(#Intent;action=android.speech.action.RECOGNIZE_SPEECH;launchFlags=0x800000;component=com.google.android.voicesearch/.IntentApiActivity;B.fullRecognitionResultsRequest=true;S.android.speech.extra.LANGUAGE_MODEL=free_form;end)
01-17 14:25:30.433: INFO/RecognitionControllerImpl(9118): State change: STARTING -> STARTING
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): required extra 'calling_package' missing in voice search intent
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): ERROR_CLIENT
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): ERROR_CLIENT
</code>```

It looks like the problem is the missing "calling_package" extra; on the RecognizerIntent page it states that this extra is:

The extra key used in an intent to the speech recognizer for voice
  search. Not generally to be used by
  developers. The system search dialog
  uses this, for example, to set a
  calling package for identification by
  a voice search API. If this extra is
  set by anyone but the system process,
  it should be overridden by the voice
  search implementation.

As far as I can tell, I don't need to override this extra, so why am I getting this error? How can I fix my code?

答:
Have you tried setting the extra yourself?

```<code>Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra("calling_package","com.yourpackagename.YourActivityClassName");
startActivityForResult(intent, REQUEST_CODE_VOICE_SEARCH);
</code>```

This is the approach used by this code and is the suggested solution to a similar issue.

ContentLicense: CC BY-SA 2.5

Body:
I'm having problems using the RecognizerIntent API on Android 2.2. When I call the API using this code:

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
startActivityForResult(intent, REQUEST_CODE_VOICE_SEARCH);

which looks like it should work, the search popup says "Unknown problem" on the device and in the logs it states:

01-17 14:25:30.433: ERROR/RecognitionActivity(9118): ACTION_RECOGNIZE_SPEECH intent called incorrectly. Maybe you called startActivity, but you should have called startActivityForResult (or otherwise included a pending intent).
01-17 14:25:30.433: INFO/RecognitionControllerImpl(9118): startRecognition(#Intent;action=android.speech.action.RECOGNIZE_SPEECH;launchFlags=0x800000;component=com.google.android.voicesearch/.IntentApiActivity;B.fullRecognitionResultsRequest=true;S.android.speech.extra.LANGUAGE_MODEL=free_form;end)
01-17 14:25:30.433: INFO/RecognitionControllerImpl(9118): State change: STARTING -> STARTING
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): required extra 'calling_package' missing in voice search intent
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): ERROR_CLIENT
01-17 14:25:30.443: ERROR/RecognitionControllerImpl(9118): ERROR_CLIENT

It looks like the problem is the missing "calling_package" extra; on the RecognizerIntent page it states that this extra is:

The extra key used in an intent to the speech recognizer for voice
  search. Not generally to be used by
  developers. The system search dialog
  uses this, for example, to set a
  calling package for identification by
  a voice search API. If this extra is
  set by anyone but the system process,
  it should be overridden by the voice
  search implementation.

As far as I can tell, I don't need to override this extra, so why am I getting this error? How can I fix my code?

Body:
Have you tried setting the extra yourself?

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra("calling_package","com.yourpackagename.YourActivityClassName");
startActivityForResult(intent, REQUEST_CODE_VOICE_SEARCH);

This is the approach used by this code and is the suggested solution to a similar issue.


问:
Ways to smoothly zoom in LibGDX?
I'm building a LibGDX game and need to zoom the camera in and out. But when I do camera.zoom = 1.2f;, it just 'jumps' to that value. Instead, I want to have a smooth zoom.

My question:
What's the best way to smoothly zoom?

I want to zoom like this graph below. y=0 is the start cam.zoom, y=100 is the desired cam.zoom and the x-axis shows the time.

Should I use cam.zoom = f(time);? (With some modification to f(x))

time is the total time passed since the beginning of the zoom.

Or is it better to use:

```<code>cam.zoom += (desiredZoom - cam.zoom) * delta * scalar;
</code>```

delta is the time between two frames and
 scalar is a float that will be adjusted in order to set the speed.

Or is there another, better way? What do you think?

Thanks a lot!

答:
You can use the MathUtils.lerp method.

Example:

```<code>MathUtils.lerp(currentZoom,targetZoom,progress);
</code>```

Increase the progress value to change faster or lower to slow down speed the value changes.

ContentLicense: CC BY-SA 3.0

Title: Ways to smoothly zoom in LibGDX?

Body:
I'm building a LibGDX game and need to zoom the camera in and out. But when I do camera.zoom = 1.2f;, it just 'jumps' to that value. Instead, I want to have a smooth zoom.

My question:
What's the best way to smoothly zoom?

I want to zoom like this graph below. y=0 is the start cam.zoom, y=100 is the desired cam.zoom and the x-axis shows the time.

Should I use cam.zoom = f(time);? (With some modification to f(x))

time is the total time passed since the beginning of the zoom.

Or is it better to use:

cam.zoom += (desiredZoom - cam.zoom) * delta * scalar;

delta is the time between two frames and
 scalar is a float that will be adjusted in order to set the speed.

Or is there another, better way? What do you think?

Thanks a lot!

Body:
You can use the MathUtils.lerp method.

Example:

MathUtils.lerp(currentZoom,targetZoom,progress);

Increase the progress value to change faster or lower to slow down speed the value changes.


问:
collapse cell in jupyter notebook
I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell?

I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?

答:
There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

```<code>%%html
<style id=hide>div.input{display:none;}</style>
<button type="button"
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>
</code>```

Or python:

```<code># Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))
</code>```

Title: collapse cell in jupyter notebook

Body:
There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button"
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

Or python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))


问:
JavaScript Function reload automatically
the problem here is i don't need input field required when i remove required the table still empty and another problem when i enter (not valid character)
also the table data will be deleted

i need the input field not required and when click add it adds a new row

var myInput = document.getElementById("myInput")
    myTable = document.getElementById("myTable")
    i = 1
    num = 1
    tabledata = myTable.innerHTML;

    function arr() {

                if(myInput.value!=""){

                if(/^[a-z]+$/i.test(myInput.value)){

                if (num % 2 == 0) {
                    myTable.innerHTML = myTable.innerHTML + '
' + i + '	' + myInput.value + "
";
                    myInput.value = "";
                    i++;
                } else {
                    myTable.innerHTML = myTable.innerHTML + '
' + i + '	' + myInput.value + "
";
                    myInput.value = "";
                    i++;
                }
                num++;
            }
         else {
              alert("Please Enter A Valid Charceter");

          }
         }else{
         alert("This Field Is Reqiured Please Enter Your Name")
         }};

function res() {
    myTable.innerHTML = "
 Id	 Name
";
    i = 1;
    num = 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <h1>Enter Your Name</h1>
        <form>
        <input type="text" id="myInput" required/>
        <button onclick="arr()">Add</button>
        </form>
        <table id="myTable">
        <tr>
        <th>ID</th>
        <th>Name</th>
        </tr>
        </table>
        <button onclick ="res()">Reset</button></code>```

答:
I didn't fully understand what you need, but I see here a little bit flaw:
When you click the "Add" button, the form is submitting, so you need to break this.

Try it:

```<code><style>
    #myTable tr {
        background: #FF8000
    }

    #myTable tr:nth-child(odd){
        background: #FFB366
    }
</style>

<h1>Enter Your Name</h1>

<form id="myForm">
    <input type="text" id="myInput" required />
    <input type="submit" />
</form>

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody id="myTable"></tbody>
</table>

<button id="myButton">Reset</button>

<script>
    (function(){
        "use strict";

        var
            form  = document.getElementById("myForm"),
            input = document.getElementById("myInput"),
            table = document.getElementById("myTable"),
            reset = document.getElementById("myButton");

        form.addEventListener("submit", add, true);
        function add(event){
            event.preventDefault();

            if( /^[a-z]+$/i.test(myInput.value) )
                table.innerHTML += '<tr><td>' + (table.children.length + 1) + '</td><td>' + input.value + '</td></tr>';

            return input.value = '';
        }

        function reset(){
            table.innerHTML = '';
        }
    })()
</script>
</code>```

Body:
the problem here is i don't need input field required when i remove required the table still empty and another problem when i enter (not valid character)
also the table data will be deleted

i need the input field not required and when click add it adds a new row

var myInput = document.getElementById("myInput")
    myTable = document.getElementById("myTable")
    i = 1
    num = 1
    tabledata = myTable.innerHTML;

    function arr() {

                if(myInput.value!=""){

                if(/^[a-z]+$/i.test(myInput.value)){

                if (num % 2 == 0) {
                    myTable.innerHTML = myTable.innerHTML + '
' + i + '	' + myInput.value + "
";
                    myInput.value = "";
                    i++;
                } else {
                    myTable.innerHTML = myTable.innerHTML + '
' + i + '	' + myInput.value + "
";
                    myInput.value = "";
                    i++;
                }
                num++;
            }
         else {
              alert("Please Enter A Valid Charceter");

          }
         }else{
         alert("This Field Is Reqiured Please Enter Your Name")
         }};

function res() {
    myTable.innerHTML = "
 Id	 Name
";
    i = 1;
    num = 1;
}

Enter Your Name

        <form>
        <input type="text" id="myInput" required/>
        <button onclick="arr()">Add</button>
        </form>

        ID
        Name

        <button onclick ="res()">Reset</button>

Body:
I didn't fully understand what you need, but I see here a little bit flaw:
When you click the "Add" button, the form is submitting, so you need to break this.

Try it:

<style>
    #myTable tr {
        background: #FF8000
    }

    #myTable tr:nth-child(odd){
        background: #FFB366
    }
</style>

<h1>Enter Your Name</h1>

<form id="myForm">
    <input type="text" id="myInput" required />
    <input type="submit" />
</form>

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody id="myTable"></tbody>
</table>

<button id="myButton">Reset</button>

<script>
    (function(){
        "use strict";

        var
            form  = document.getElementById("myForm"),
            input = document.getElementById("myInput"),
            table = document.getElementById("myTable"),
            reset = document.getElementById("myButton");

        form.addEventListener("submit", add, true);
        function add(event){
            event.preventDefault();

            if( /^[a-z]+$/i.test(myInput.value) )
                table.innerHTML += '<tr><td>' + (table.children.length + 1) + '</td><td>' + input.value + '</td></tr>';

            return input.value = '';
        }

        function reset(){
            table.innerHTML = '';
        }
    })()
</script>


问:
Change Date Format(DD/MM/YYYY) in SQL SELECT Statement
The Original SQL Statement is:

```<code>SELECT SA.[RequestStartDate] as 'Service Start Date',
       SA.[RequestEndDate] as 'Service End Date',
FROM
(......)SA
WHERE......
</code>```

The output date format  is YYYY/MM/DD, but I want the output date format is DD/MM/YYYY. How can I modify in this statement?

答:
Try:

```<code>SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date',
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date',
FROM
(......)SA
WHERE......
</code>```

Or:

```<code>SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date',
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date',
FROM
(......)SA
WHERE......
</code>```

Body:
The Original SQL Statement is:

SELECT SA.[RequestStartDate] as 'Service Start Date',
       SA.[RequestEndDate] as 'Service End Date',
FROM
(......)SA
WHERE......

The output date format  is YYYY/MM/DD, but I want the output date format is DD/MM/YYYY. How can I modify in this statement?

Body:
Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date',
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date',
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date',
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date',
FROM
(......)SA
WHERE......


问:
Use Custom Patterns in ReSharper Code Quality Analysis in TFS build
I use ReSharper 2017.2.2 on the development machine together with Visual Studio 2017.5.

I'm using TFS 2017 Update 3.

On the TFS server, Visual Studio 2017.4 and ReSharper CLT 2017.2.2 are installed.

I'm using TFS build.

My goal is to do code analysis when building a solution.

I use the Resharper Code Quality Analysis task. I can configure it using the sln.DotSettings file which is at the root of the solution.

Standard code checks ReSharper successfully work. I can also change the warning level as shown here https://marketplace.visualstudio.com/items?itemName=alanwales.resharper-code-analysis

For this I use ReSharper -> Options | Code Inspection -> Custom patterns.

This rule works well in Visual Studio. When I save this rule to sln.DotSettings, the following lines are added:

```<code> <s:Boolean x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/@KeyIndexDefined">True</s:Boolean>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/LanguageName/@EntryValue">JAVA_SCRIPT</s:String>
 <s:Boolean x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/MatchCatchClauseWithoutExceptionFilter/@EntryValue">False</s:Boolean>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/SearchPattern/@EntryValue">debugger</s:String>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/Severity/@EntryValue">ERROR</s:String></wpf:ResourceDictionary>
</code>```

I in the JS code specially added lines with debugger. But I do not get a warning on my custom patterns.

Does Resharper Code Quality Analysis support in TFS use Custom patterns?

UPDATE 1: I checked the launch of the code analysis via the console with the command: InspectCode.exe -o="C:\temp\Results.xml" --no-swea "C:\BuildAgent\Thompson\_work\23\s\***.sln"

In the Results.xml file, I found the required line:

```<code><Issue TypeId="StructuralSearch" Severity="ERROR" File="***.WebResources\WebResources\new_\js\forms\***.js" Offset="406-415" Line="13" Message="debugger" />
</code>```

UPDATE 2: I looked at the script code RunResharperCodeAnalysisTool.ps1. In this file there are the following lines:

```<code>...
$severityLevels = @{"Hint" = 0; "Suggestion" = 1; "Warning" = 2; "Error" = 3}
...
foreach($issue in $issuesElements) {
    $severity = @($issuesTypesElements | Where-Object {$_.Attributes["Id"].Value -eq $issue.Attributes["TypeId"].Value})[0].Attributes["Severity"].Value

    $severityLevel = $severityLevels[$severity]

    if($severityLevel -ge $severityLevels[$failBuildLevelSelector]) {
        $item = New-Object -TypeName PSObject -Property @{
            'Severity' = $severity
            'Message' = $issue.Attributes["Message"].Value
            'File' = $issue.Attributes["File"].Value
            'Line' = $issue.Attributes["Line"].Value
        }

        $filteredElements.Add($item)
    }
}
</code>```

The Results.xml file has the following lines:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generated by JetBrains Inspect Code 2017.2.2 -->
<Report ToolsVersion="109.0.20171006.123742">
  <Information>
    <Solution>..\..\BuildAgent\Thompson\_work\23\s\***\***.sln</Solution>
    <InspectionScope>
      <Element>Solution</Element>
    </InspectionScope>
  </Information>
  <IssueTypes>
    <IssueType Id="StructuralSearch" Category="Structural Search Highlightings" CategoryId="StructuralSearch" Description="Structural Search Pattern" Severity="INVALID_SEVERITY" />
    <IssueType Id="WebConfigErrors" Category="WebConfig Errors" CategoryId="WebConfigErrors" Description="" Severity="ERROR" />
  </IssueTypes>
  <Issues>
    <Project Name="***">
      <Issue TypeId="WebConfigErrors" File="***.WebResources\Web.config" Offset="531-650" Line="17" Message="Invalid module qualification: Failed to resolve assembly Microsoft.CodeDom.Providers.DotNetCompilerPlatform" />
      <Issue TypeId="WebConfigErrors" File="***.WebResources\Web.config" Offset="916-1035" Line="20" Message="Invalid module qualification: Failed to resolve assembly Microsoft.CodeDom.Providers.DotNetCompilerPlatform" />
      <Issue TypeId="StructuralSearch" Severity="ERROR" File="***.WebResources\WebResources\new_\js\forms\***.js" Offset="406-415" Line="13" Message="debugger" />
    </Project>
  </Issues>
</Report>
</code>```

My Custom Patterns has Severity="INVALID_SEVERITY" which is not on the $severityLevels list.

答:
Since it works well with the command line, seems the issue is not related to TFS side, may more related with the 3-party task.

If this will not work with the Resharper Code Quality Analysis task, you could directly call the InspectCode.exe  command during the build task by use a command line task or customize extension. Then publish the result file to TFS.

Besides, as a workaround, you could also  be able to  return warnings and errors from your powershell script using logging commands.  With using task.logissue type=error you could fail the build task and then fail the build.

Body:
I use ReSharper 2017.2.2 on the development machine together with Visual Studio 2017.5.

I'm using TFS 2017 Update 3.

On the TFS server, Visual Studio 2017.4 and ReSharper CLT 2017.2.2 are installed.

I'm using TFS build.

My goal is to do code analysis when building a solution.

I use the Resharper Code Quality Analysis task. I can configure it using the sln.DotSettings file which is at the root of the solution.

Standard code checks ReSharper successfully work. I can also change the warning level as shown here https://marketplace.visualstudio.com/items?itemName=alanwales.resharper-code-analysis

For this I use ReSharper -> Options | Code Inspection -> Custom patterns.

This rule works well in Visual Studio. When I save this rule to sln.DotSettings, the following lines are added:

 <s:Boolean x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/@KeyIndexDefined">True</s:Boolean>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/LanguageName/@EntryValue">JAVA_SCRIPT</s:String>
 <s:Boolean x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/MatchCatchClauseWithoutExceptionFilter/@EntryValue">False</s:Boolean>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/SearchPattern/@EntryValue">debugger</s:String>
 <s:String x:Key="/Default/PatternsAndTemplates/StructuralSearch/Pattern/=4E6B3830DEEA6148909C23CD21C96E28/Severity/@EntryValue">ERROR</s:String></wpf:ResourceDictionary>

I in the JS code specially added lines with debugger. But I do not get a warning on my custom patterns.

Does Resharper Code Quality Analysis support in TFS use Custom patterns?

UPDATE 1: I checked the launch of the code analysis via the console with the command: InspectCode.exe -o="C:\temp\Results.xml" --no-swea "C:\BuildAgent\Thompson\_work\23\s\***.sln"

In the Results.xml file, I found the required line:

<Issue TypeId="StructuralSearch" Severity="ERROR" File="***.WebResources\WebResources\new_\js\forms\***.js" Offset="406-415" Line="13" Message="debugger" />

UPDATE 2: I looked at the script code RunResharperCodeAnalysisTool.ps1. In this file there are the following lines:

...
$severityLevels = @{"Hint" = 0; "Suggestion" = 1; "Warning" = 2; "Error" = 3}
...
foreach($issue in $issuesElements) {
    $severity = @($issuesTypesElements | Where-Object {$_.Attributes["Id"].Value -eq $issue.Attributes["TypeId"].Value})[0].Attributes["Severity"].Value

    $severityLevel = $severityLevels[$severity]

    if($severityLevel -ge $severityLevels[$failBuildLevelSelector]) {
        $item = New-Object -TypeName PSObject -Property @{
            'Severity' = $severity
            'Message' = $issue.Attributes["Message"].Value
            'File' = $issue.Attributes["File"].Value
            'Line' = $issue.Attributes["Line"].Value
        }

        $filteredElements.Add($item)
    }
}

The Results.xml file has the following lines:

<?xml version="1.0" encoding="utf-8"?>

<Report ToolsVersion="109.0.20171006.123742">
  <Information>
    <Solution>..\..\BuildAgent\Thompson\_work\23\s\***\***.sln</Solution>
    <InspectionScope>
      <Element>Solution</Element>
    </InspectionScope>
  </Information>
  <IssueTypes>
    <IssueType Id="StructuralSearch" Category="Structural Search Highlightings" CategoryId="StructuralSearch" Description="Structural Search Pattern" Severity="INVALID_SEVERITY" />
    <IssueType Id="WebConfigErrors" Category="WebConfig Errors" CategoryId="WebConfigErrors" Description="" Severity="ERROR" />
  </IssueTypes>
  <Issues>
    <Project Name="***">
      <Issue TypeId="WebConfigErrors" File="***.WebResources\Web.config" Offset="531-650" Line="17" Message="Invalid module qualification: Failed to resolve assembly Microsoft.CodeDom.Providers.DotNetCompilerPlatform" />
      <Issue TypeId="WebConfigErrors" File="***.WebResources\Web.config" Offset="916-1035" Line="20" Message="Invalid module qualification: Failed to resolve assembly Microsoft.CodeDom.Providers.DotNetCompilerPlatform" />
      <Issue TypeId="StructuralSearch" Severity="ERROR" File="***.WebResources\WebResources\new_\js\forms\***.js" Offset="406-415" Line="13" Message="debugger" />
    </Project>
  </Issues>
</Report>

My Custom Patterns has Severity="INVALID_SEVERITY" which is not on the $severityLevels list.


问:
C# Add 1 day in specific TimeZone to DateTimeOffset
I have an instance of DateTimeOffset and I need to add 1 day to it in specific TimeZone (W. Europe Standard Time) taking into account daylight saving rules (so it might result in Offset change). How can I do it without 3rd party libraries?

Verifiable example:

```<code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject
{
    [TestClass]
    public class TimeZoneTests
    {
        [TestMethod]
        public void DateTimeOffsetAddDays_DaylightSaving_OffsetChange()
        {
            var timeZoneId = "W. Europe Standard Time";
            var utcTimestamp = new DateTimeOffset(2017, 10, 28, 22, 0, 0, TimeZoneInfo.Utc.BaseUtcOffset);
            var weuropeStandardTimeTimestamp = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcTimestamp, timeZoneId);
            Assert.AreEqual(new DateTime(2017, 10, 29), weuropeStandardTimeTimestamp.DateTime);
            Assert.AreEqual(TimeSpan.FromHours(2), weuropeStandardTimeTimestamp.Offset);

            var weuropeStandardTimeTimestampNextDay = AddDaysInTimeZone(weuropeStandardTimeTimestamp, 1, timeZoneId);

            Assert.AreEqual(new DateTime(2017, 10, 30), weuropeStandardTimeTimestampNextDay);
            Assert.AreEqual(TimeSpan.FromHours(1), weuropeStandardTimeTimestamp.Offset);
        }

        private DateTimeOffset AddDaysInTimeZone(DateTimeOffset timestamp, int days, string timeZoneId)
        {
            // this line has to be fixed:
            return timestamp.AddDays(days);
        }
    }
}
</code>```

AddDaysInTimeZone method should be replaced with correct implementation.

PS If it results in invalid/ambigous/skipped date, then it is fine to throw exception.

答:
TimeZoneInfo makes this reasonably simple - just add a day to the DateTime part of the value, check whether the result is skipped or ambiguous, and if not, ask the zone for the UTC offset. Here's a complete example showing all the different possibilities:

```<code>using System;
using System.Globalization;

using static System.FormattableString;

class Program
{
    static void Main()
    {
        // Stay in winter
        Test("2017-01-22T15:00:00+01:00");
        // Skipped time during transition
        Test("2017-03-25T02:30:00+01:00");
        // Offset change to summer
        Test("2017-03-25T15:00:00+01:00");
        // Stay in summer
        Test("2017-06-22T15:00:00+02:00");
        // Ambiguous time during transition
        Test("2017-10-28T02:30:00+02:00");
        // Offset change back to winter
        Test("2017-10-28T15:00:00+02:00");
        // Stay in winter
        Test("2017-12-22T15:00:00+01:00");
    }

    static void Test(string startText)
    {
        var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
        var start = DateTimeOffset.ParseExact(
            startText, "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);
        try
        {
            var end = AddOneDay(start, zone);
            Console.WriteLine(Invariant($"{startText} => {end:yyyy-MM-dd'T'HH:mm:ssK}"));
        }
        catch (Exception e)
        {
            Console.WriteLine($"{startText} => {e.Message}");
        }
    }

    static DateTimeOffset AddOneDay(DateTimeOffset start, TimeZoneInfo zone)
    {
        var newLocal = start.DateTime.AddDays(1);
        // TODO: Use a better exception type :)
        if (zone.IsAmbiguousTime(newLocal))
        {
            throw new Exception("Ambiguous");
        }
        if (zone.IsInvalidTime(newLocal))
        {
            throw new Exception("Skipped");
        }
        return new DateTimeOffset(newLocal, zone.GetUtcOffset(newLocal));
    }

}
</code>```

Body:
I have an instance of DateTimeOffset and I need to add 1 day to it in specific TimeZone (W. Europe Standard Time) taking into account daylight saving rules (so it might result in Offset change). How can I do it without 3rd party libraries?

Verifiable example:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject
{
    [TestClass]
    public class TimeZoneTests
    {
        [TestMethod]
        public void DateTimeOffsetAddDays_DaylightSaving_OffsetChange()
        {
            var timeZoneId = "W. Europe Standard Time";
            var utcTimestamp = new DateTimeOffset(2017, 10, 28, 22, 0, 0, TimeZoneInfo.Utc.BaseUtcOffset);
            var weuropeStandardTimeTimestamp = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcTimestamp, timeZoneId);
            Assert.AreEqual(new DateTime(2017, 10, 29), weuropeStandardTimeTimestamp.DateTime);
            Assert.AreEqual(TimeSpan.FromHours(2), weuropeStandardTimeTimestamp.Offset);

            var weuropeStandardTimeTimestampNextDay = AddDaysInTimeZone(weuropeStandardTimeTimestamp, 1, timeZoneId);

            Assert.AreEqual(new DateTime(2017, 10, 30), weuropeStandardTimeTimestampNextDay);
            Assert.AreEqual(TimeSpan.FromHours(1), weuropeStandardTimeTimestamp.Offset);
        }

        private DateTimeOffset AddDaysInTimeZone(DateTimeOffset timestamp, int days, string timeZoneId)
        {
            // this line has to be fixed:
            return timestamp.AddDays(days);
        }
    }
}

AddDaysInTimeZone method should be replaced with correct implementation.

PS If it results in invalid/ambigous/skipped date, then it is fine to throw exception.

Body:
TimeZoneInfo makes this reasonably simple - just add a day to the DateTime part of the value, check whether the result is skipped or ambiguous, and if not, ask the zone for the UTC offset. Here's a complete example showing all the different possibilities:

using System;
using System.Globalization;

using static System.FormattableString;

class Program
{
    static void Main()
    {
        // Stay in winter
        Test("2017-01-22T15:00:00+01:00");
        // Skipped time during transition
        Test("2017-03-25T02:30:00+01:00");
        // Offset change to summer
        Test("2017-03-25T15:00:00+01:00");
        // Stay in summer
        Test("2017-06-22T15:00:00+02:00");
        // Ambiguous time during transition
        Test("2017-10-28T02:30:00+02:00");
        // Offset change back to winter
        Test("2017-10-28T15:00:00+02:00");
        // Stay in winter
        Test("2017-12-22T15:00:00+01:00");
    }

    static void Test(string startText)
    {
        var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
        var start = DateTimeOffset.ParseExact(
            startText, "yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);
        try
        {
            var end = AddOneDay(start, zone);
            Console.WriteLine(Invariant($"{startText} => {end:yyyy-MM-dd'T'HH:mm:ssK}"));
        }
        catch (Exception e)
        {
            Console.WriteLine($"{startText} => {e.Message}");
        }
    }

    static DateTimeOffset AddOneDay(DateTimeOffset start, TimeZoneInfo zone)
    {
        var newLocal = start.DateTime.AddDays(1);
        // TODO: Use a better exception type :)
        if (zone.IsAmbiguousTime(newLocal))
        {
            throw new Exception("Ambiguous");
        }
        if (zone.IsInvalidTime(newLocal))
        {
            throw new Exception("Skipped");
        }
        return new DateTimeOffset(newLocal, zone.GetUtcOffset(newLocal));
    }

}


问:
Python import coding style
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

```<code>import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)
</code>```

I move all my imports into the function where they're actually used., like this:

```<code>def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)
</code>```

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

答:
Another useful thing to note is that the from module import * syntax inside of a function has been removed in Python 3.0.

There is a brief mention of it under "Removed Syntax" here:

http://docs.python.org/3.0/whatsnew/3.0.html

OwnerDisplayName: TokenMacGuy

Title: Python import coding style

Body:
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)

I move all my imports into the function where they're actually used., like this:

def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

OwnerDisplayName: Russell Bryant


问:
How do I use asyncio.sslproto.SSLProtocol?
I am trying to talk to an ElectrumX server using JSON-RPC over TLS, but through Tor (SOCKS proxy on localhost).

When running the following code, drain() in  asyncio.streams is calling _drain_helper in SSLProtocol, which I don't know how to implement.

If I just make it a no-op, it seems to not work.

I know that the JSON-RPC server is working because I have tested with

```<code>echo -ne '{"id":0,"args":["3.0.2","1.1"],"method":"server.version"}\n' | socat stdio openssl-connect:songbird.bauerj.eu:50002,verify=0
</code>```

My attempt at using TLS through SOCKS in Python with asyncio:

```<code>from asyncio.sslproto import SSLProtocol
import aiosocks
import asyncio

loop = None

class MySSLProtocol(SSLProtocol):
    def __init__(otherself):
        super().__init__(loop, None,      False  , None)
        #                      app_proto  context  waiter

async def l(fut):
    try:
        socks4addr = aiosocks.Socks4Addr("127.0.0.1", 9050)
        transport, protocol = await aiosocks.create_connection(MySSLProtocol, proxy=socks4addr, proxy_auth=None, dst=("songbird.bauerj.eu", 50002))
        reader = asyncio.StreamReader()
        reader.set_transport(transport)
        writer = asyncio.StreamWriter(transport, protocol, reader, loop)
        writer.write(b'{"id":0,"method":"server.version","args":["3.0.2", "1.1"]}\n')
        await writer.drain()
        print(await reader.readuntil(b"\n"))
        fut.set_result("finished")
    except BaseException as e:
        fut.set_exception(e)

def f():
    global loop
    loop = asyncio.get_event_loop()
    fut = asyncio.Future()
    asyncio.ensure_future(l(fut))
    loop.run_until_complete(fut)
    print(fut.result())
    loop.close()

f()
</code>```

I am using aiosocks from master. Commit 932374c

答:
asyncio.sslproto and SSLProtocol are part of asyncio private API.

You should never use the class directly or derive from it.

For working with SSL please pass normal protocol (derived from asyncio.Protocol) and ssl.SSLContext as ssl param into loop.create_connection() / loop.create_server().

Body:
I am trying to talk to an ElectrumX server using JSON-RPC over TLS, but through Tor (SOCKS proxy on localhost).

When running the following code, drain() in  asyncio.streams is calling _drain_helper in SSLProtocol, which I don't know how to implement.

If I just make it a no-op, it seems to not work.

I know that the JSON-RPC server is working because I have tested with

echo -ne '{"id":0,"args":["3.0.2","1.1"],"method":"server.version"}\n' | socat stdio openssl-connect:songbird.bauerj.eu:50002,verify=0

My attempt at using TLS through SOCKS in Python with asyncio:

from asyncio.sslproto import SSLProtocol
import aiosocks
import asyncio

loop = None

class MySSLProtocol(SSLProtocol):
    def __init__(otherself):
        super().__init__(loop, None,      False  , None)
        #                      app_proto  context  waiter

async def l(fut):
    try:
        socks4addr = aiosocks.Socks4Addr("127.0.0.1", 9050)
        transport, protocol = await aiosocks.create_connection(MySSLProtocol, proxy=socks4addr, proxy_auth=None, dst=("songbird.bauerj.eu", 50002))
        reader = asyncio.StreamReader()
        reader.set_transport(transport)
        writer = asyncio.StreamWriter(transport, protocol, reader, loop)
        writer.write(b'{"id":0,"method":"server.version","args":["3.0.2", "1.1"]}\n')
        await writer.drain()
        print(await reader.readuntil(b"\n"))
        fut.set_result("finished")
    except BaseException as e:
        fut.set_exception(e)

def f():
    global loop
    loop = asyncio.get_event_loop()
    fut = asyncio.Future()
    asyncio.ensure_future(l(fut))
    loop.run_until_complete(fut)
    print(fut.result())
    loop.close()

f()

I am using aiosocks from master. Commit 932374c


问:
Oracle uses exception handler from first block in later blocks
I'm running into a behavior where I'm trying to use case-specific exception handlers for several Oracle PL/SQL blocks in a Flyway script and Oracle, apparently contradicting its documented scoping for exception handlers, sends all exceptions to the exception handler for the first block.  For example, in this code:

```<code>begin

  begin
    execute immediate '
create table "test" (
  "id" number not null,
  "name" varchar2(100) not null,
  constraint "test_pk" primary key ("id")
)
';
  exception
  when others then
    if sqlcode != -955 then raise; end if;
  end;

  begin
    execute immediate 'fail to create index "test_name_idx" on "test" ("name")';
  exception
  when others then
    if sqlcode != -6512 then raise; end if;
  end;

end;
</code>```

the ORA-06512 exception is not caught, and the exception raised is tagged as from line 13.

Wrapping the blocks in more blocks doesn't help.

What is going on here?  How do I stop this from happening?

答:
This seems to be a bug, which has (so far) been reproduced in 11.2.0.4, 12.1.0.2 and 12.2.0.1. It doesn't seem to require DDL, or any real action in the first sub-block (though just doing null; as a placeholder doesn't trigger it, possibly because the compiler removes it), but it does seem to need the if inside both exception handlers:

```<code>begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 8
ORA-06512: at line 13
</code>```

As with your example the exception is thrown by line 13 so should be reported as (re-)raised at line 18; but it's instead it's reported as raised from line 8, which doesn't make sense.  (The at line 13 message is only shown in 12.2; in 11.2 and 12.1 it only reports the first ORA-06512, which is rather more confusing. At least in 12 2 you have some clue where the problem really is.)

From the debugs you can see it doesn't actually use the first exception handler, and it does go into the second one. It 'only' seems to be reporting against the wrong line number, rather than executing the wrong code.

It appears that doing real work inside the if, immediately before the raise somehow fixes things - in either exception handling section; this adds a message in the first, which can't be reached:

```<code>begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        dbms_output.put_line('This avoids the bug somehow');
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 19
ORA-06512: at line 14
</code>```

and this in the second:

```<code>begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        dbms_output.put_line('This avoids the bug somehow');
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 19
ORA-06512: at line 13
</code>```

In both cases the reported line number is now correct. Somehow.

It doesn't have to be a dbms_output call, anything seems to work, such as a dummy procedure call or query, even an extra sub-block (e.g. begin execute immediate 'select * from dual'; end;, even though the query isn't executed because there's no into...). Again just using null; doesn't work though.

This is a bit ugly but gives you a way to stop it from happening at least, sort of.

It's clearly weird and unexpected and inconsistent behaviour, and has been around for a while, so it should probably be raised as a service request through My Oracle Support. I can't see any existing reports but I didn't look very hard so there might be one lurking somewhere.

Body:
I'm running into a behavior where I'm trying to use case-specific exception handlers for several Oracle PL/SQL blocks in a Flyway script and Oracle, apparently contradicting its documented scoping for exception handlers, sends all exceptions to the exception handler for the first block.  For example, in this code:

begin

  begin
    execute immediate '
create table "test" (
  "id" number not null,
  "name" varchar2(100) not null,
  constraint "test_pk" primary key ("id")
)
';
  exception
  when others then
    if sqlcode != -955 then raise; end if;
  end;

  begin
    execute immediate 'fail to create index "test_name_idx" on "test" ("name")';
  exception
  when others then
    if sqlcode != -6512 then raise; end if;
  end;

end;

the ORA-06512 exception is not caught, and the exception raised is tagged as from line 13.

Wrapping the blocks in more blocks doesn't help.

What is going on here?  How do I stop this from happening?

Body:
This seems to be a bug, which has (so far) been reproduced in 11.2.0.4, 12.1.0.2 and 12.2.0.1. It doesn't seem to require DDL, or any real action in the first sub-block (though just doing null; as a placeholder doesn't trigger it, possibly because the compiler removes it), but it does seem to need the if inside both exception handlers:

begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 8
ORA-06512: at line 13

As with your example the exception is thrown by line 13 so should be reported as (re-)raised at line 18; but it's instead it's reported as raised from line 8, which doesn't make sense.  (The at line 13 message is only shown in 12.2; in 11.2 and 12.1 it only reports the first ORA-06512, which is rather more confusing. At least in 12 2 you have some clue where the problem really is.)

From the debugs you can see it doesn't actually use the first exception handler, and it does go into the second one. It 'only' seems to be reporting against the wrong line number, rather than executing the wrong code.

It appears that doing real work inside the if, immediately before the raise somehow fixes things - in either exception handling section; this adds a message in the first, which can't be reached:

begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        dbms_output.put_line('This avoids the bug somehow');
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 19
ORA-06512: at line 14

and this in the second:

begin
  begin
    dbms_output.put_line('Dummy message');
  exception
    when others then
      dbms_output.put_line('In first exception handler');
      if 1=1 then
        raise;
      end if;
  end;

  begin
    execute immediate 'invalid';
  exception
    when others then
      dbms_output.put_line('In second exception handler');
      if 1=1 then
        dbms_output.put_line('This avoids the bug somehow');
        raise;
      end if;
  end;
end;
/

Dummy message
In second exception handler

ORA-00900: invalid SQL statement
ORA-06512: at line 19
ORA-06512: at line 13

In both cases the reported line number is now correct. Somehow.

It doesn't have to be a dbms_output call, anything seems to work, such as a dummy procedure call or query, even an extra sub-block (e.g. begin execute immediate 'select * from dual'; end;, even though the query isn't executed because there's no into...). Again just using null; doesn't work though.

This is a bit ugly but gives you a way to stop it from happening at least, sort of.

It's clearly weird and unexpected and inconsistent behaviour, and has been around for a while, so it should probably be raised as a service request through My Oracle Support. I can't see any existing reports but I didn't look very hard so there might be one lurking somewhere.


问:
Plot float up & down beyond y-axis in StockChart while dragging navigator
Here is my js code:

```<code>Highcharts.stockChart('utilizations', {
                chart: {
                        zoomType: 'x'
                },
                title: {
                    text: 'KPI'
                },
                subtitle: {
                    text: 'CCE & PRB Utilization (%)'
                },
                rangeSelector: {
                    buttons: [{
                        type: 'day',
                        count: 1,
                        text: '1d'
                    }, {
                        type: 'day',
                        count: 3,
                        text: '3d'
                    }, {
                        type: 'day',
                        count: 7,
                        text: '1w'
                    }, {
                        type: 'day',
                        count: 14,
                        text: '2w'
                    }, {
                        type: 'all',
                        text: 'All'
                    }],
                    selected: 1
                },
                yAxis: {
                    labels: {
                        formatter: function () {return this.value + '%';}
                    },
                    max: 100,
                    min: 0,
                    tickInterval: 20,
                    plotLines: [{
                        value: 0,
                        width: 2,
                        color: 'silver'
                    },{
                        value: 70,
                        width: 1,
                        color: 'red'
                    }]
                },
                tooltip: {
                    crosshairs: true,
                    shared: true
                },
                plotOptions: {
                    series: {
                        compare: 'value',
                        showInNavigator: true
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle'
                },
                xAxis: {
                    type: 'datetime'
                },
                series: [{
                    name: 'CCE Util',
                    type: 'spline',
                    yAxis: 0,
                    data: (function(){
                        var data = [];
                        for (var i = 0; i < result.length; i++) {
                            var time = result[i]["time"];
                            var kpi = result[i]["cce"];
                            data.push([time, kpi]);
                        }
                        return data;
                    })(),
                    tooltip: {
                        valueSuffix: '%',
                        valueDecimals: 2,
                        split: true
                    }
                },{
                    name: 'PRB Util',
                    type: 'spline',
                    yAxis: 0,
                    data: (function(){
                        var data = [];
                        for (var i = 0; i < result.length; i++) {
                            var time = result[i]["time"];
                            var kpi = result[i]["prb"];
                            data.push([time, kpi]);
                        }
                        return data;
                    })(),
                    tooltip: {
                        valueSuffix: '%',
                        valueDecimals: 2,
                        split: true
                    }
</code>```

And my plot:

While dragging the navigator bar, sometimes the plot goes to the right position and sometimes it looks like the capture above. According to my experience, the plot position is related to the left end (let's note this as A) position of the navigator selector. When A is on the lowest part of the whole plot in navigator, the shown plot positioned well; and when A goes like the capture above, the plot shown sunk.

Please refer to a short demo with 100 data here: https://jsfiddle.net/ghqyvo0x/

How can I make my plot stable?

答:
Your problem is caused by series.compare: property, which you set in plotOptions configuration object. If you delete this line of code, everything should work as you need. We could read in Highstock API:

Compare the values of the series against the first non-null, non- zero value in the visible range.

```<code>plotOptions: {
  series: {
    //compare: 'percent',
    showInNavigator: true
  }
}
</code>```

JSFiddle example

API Reference

Body:
Here is my js code:

Highcharts.stockChart('utilizations', {
                chart: {
                        zoomType: 'x'
                },
                title: {
                    text: 'KPI'
                },
                subtitle: {
                    text: 'CCE & PRB Utilization (%)'
                },
                rangeSelector: {
                    buttons: [{
                        type: 'day',
                        count: 1,
                        text: '1d'
                    }, {
                        type: 'day',
                        count: 3,
                        text: '3d'
                    }, {
                        type: 'day',
                        count: 7,
                        text: '1w'
                    }, {
                        type: 'day',
                        count: 14,
                        text: '2w'
                    }, {
                        type: 'all',
                        text: 'All'
                    }],
                    selected: 1
                },
                yAxis: {
                    labels: {
                        formatter: function () {return this.value + '%';}
                    },
                    max: 100,
                    min: 0,
                    tickInterval: 20,
                    plotLines: [{
                        value: 0,
                        width: 2,
                        color: 'silver'
                    },{
                        value: 70,
                        width: 1,
                        color: 'red'
                    }]
                },
                tooltip: {
                    crosshairs: true,
                    shared: true
                },
                plotOptions: {
                    series: {
                        compare: 'value',
                        showInNavigator: true
                    }
                },
                legend: {
                    layout: 'vertical',
                    align: 'right',
                    verticalAlign: 'middle'
                },
                xAxis: {
                    type: 'datetime'
                },
                series: [{
                    name: 'CCE Util',
                    type: 'spline',
                    yAxis: 0,
                    data: (function(){
                        var data = [];
                        for (var i = 0; i < result.length; i++) {
                            var time = result[i]["time"];
                            var kpi = result[i]["cce"];
                            data.push([time, kpi]);
                        }
                        return data;
                    })(),
                    tooltip: {
                        valueSuffix: '%',
                        valueDecimals: 2,
                        split: true
                    }
                },{
                    name: 'PRB Util',
                    type: 'spline',
                    yAxis: 0,
                    data: (function(){
                        var data = [];
                        for (var i = 0; i < result.length; i++) {
                            var time = result[i]["time"];
                            var kpi = result[i]["prb"];
                            data.push([time, kpi]);
                        }
                        return data;
                    })(),
                    tooltip: {
                        valueSuffix: '%',
                        valueDecimals: 2,
                        split: true
                    }

And my plot:

While dragging the navigator bar, sometimes the plot goes to the right position and sometimes it looks like the capture above. According to my experience, the plot position is related to the left end (let's note this as A) position of the navigator selector. When A is on the lowest part of the whole plot in navigator, the shown plot positioned well; and when A goes like the capture above, the plot shown sunk.

Please refer to a short demo with 100 data here: https://jsfiddle.net/ghqyvo0x/

How can I make my plot stable?

Body:
Your problem is caused by series.compare: property, which you set in plotOptions configuration object. If you delete this line of code, everything should work as you need. We could read in Highstock API:

Compare the values of the series against the first non-null, non- zero value in the visible range.

plotOptions: {
  series: {
    //compare: 'percent',
    showInNavigator: true
  }
}

JSFiddle example

API Reference


问:
How to resize an image by DM scripting?

How to resize an image by DM scripting?

When we process an image, we could resize the image by “process – scale -dimensions -width and height, then change the pixels’ number of width or height “ in DM software.

We also have the option “Constrain proportion” when we resize the image.

How to achieve this by scripting?

答:
Good question.

There are a couple of commands you need. ImageResize() changes the physical size of an image (i.e. the pixel dimensions) while keeping the meta data (tags) and at the same time changing calibration such that the overall field of view remains the same in calibrated units. However, the pixel values are reset to 0 and need to be re-computed in a second step.

The command warp() is used for any mapping with bilinear interpolation of intensity values, so you can use that one for the scaling (plus interpolation).

If you instead want to use "nearest neighbour" interpolation (i.e. copying pixel values), you can most easily achieve this by simple data-copying using the slice2() command for sub-sampling or just the [ ] notation of pixel indexing.

As the thing you are asking for is rather a "basic need" in scripting, the answer to it has actually been included in the F1 help documentation's "examples" section in later GMS versions, so I'm just copy-pasting the script here:

Example 3: Resizing with intensity interpolation

```<code>image in, out1, out2
if ( !GetFrontImage( in ) )
 Throw( "No image loaded." )

number sx, sy
GetSize( in, sx, sy )
number f = 1.8        // scaling factor

// Variant 1, bi-linear interpolation
out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " bilinear" )
ShowImage( out1 )

// Variant 2, nearest-neighbor interpolation / sampling
out2 := ImageClone( in )
ImageResize( out2, 2, sx * f, sy * f )
out2 = in[ icol / f, irow / f ]
SetName( out2, GetName( in ) + " nn" )
ShowImage( out2 )

// Note: ImageResize() sets all values to zero and
// adjusts spatial calibration to keep same FOV as before
</code>```

Now, if you want to constrain the aspect ratio, that would be what you need to do in scripting yourself by making sure you use the same sampling factor in X and Y. If you want to mimic 'User enters finals size' you would do something like this:

```<code>image in
if ( !GetFrontImage( in ) )
 Throw( "No image loaded." )

number sx = ImageGetDimensionSize( in, 0 )
number sy = ImageGetDimensionSize( in, 1 )

string msg = "Please enter wanted X size."
msg += "\n(Currently: " + sx + " pixels)"
number sx_new
if ( !GetNumber( msg, sx, sx_new) )
    exit( 0 )

number f = sx_new/sx
number sy_new = trunc(sx * f)
Result( "\n New Image size: " + sx_new + " x " + sy_new )
image out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " scaled" )
ShowImage( out1 )
</code>```

Title: How to resize an image by DM scripting?

Body:
Good question.

There are a couple of commands you need. ImageResize() changes the physical size of an image (i.e. the pixel dimensions) while keeping the meta data (tags) and at the same time changing calibration such that the overall field of view remains the same in calibrated units. However, the pixel values are reset to 0 and need to be re-computed in a second step.

The command warp() is used for any mapping with bilinear interpolation of intensity values, so you can use that one for the scaling (plus interpolation).

If you instead want to use "nearest neighbour" interpolation (i.e. copying pixel values), you can most easily achieve this by simple data-copying using the slice2() command for sub-sampling or just the [ ] notation of pixel indexing.

As the thing you are asking for is rather a "basic need" in scripting, the answer to it has actually been included in the F1 help documentation's "examples" section in later GMS versions, so I'm just copy-pasting the script here:

Example 3: Resizing with intensity interpolation

image in, out1, out2
if ( !GetFrontImage( in ) )
 Throw( "No image loaded." )

number sx, sy
GetSize( in, sx, sy )
number f = 1.8        // scaling factor

// Variant 1, bi-linear interpolation
out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " bilinear" )
ShowImage( out1 )

// Variant 2, nearest-neighbor interpolation / sampling
out2 := ImageClone( in )
ImageResize( out2, 2, sx * f, sy * f )
out2 = in[ icol / f, irow / f ]
SetName( out2, GetName( in ) + " nn" )
ShowImage( out2 )

// Note: ImageResize() sets all values to zero and
// adjusts spatial calibration to keep same FOV as before

Now, if you want to constrain the aspect ratio, that would be what you need to do in scripting yourself by making sure you use the same sampling factor in X and Y. If you want to mimic 'User enters finals size' you would do something like this:

image in
if ( !GetFrontImage( in ) )
 Throw( "No image loaded." )

number sx = ImageGetDimensionSize( in, 0 )
number sy = ImageGetDimensionSize( in, 1 )

string msg = "Please enter wanted X size."
msg += "\n(Currently: " + sx + " pixels)"
number sx_new
if ( !GetNumber( msg, sx, sx_new) )
    exit( 0 )

number f = sx_new/sx
number sy_new = trunc(sx * f)
Result( "\n New Image size: " + sx_new + " x " + sy_new )
image out1 := ImageClone( in )
ImageResize( out1, 2, sx * f, sy * f )
out1 = Warp( in, icol / f, irow / f )
SetName( out1, GetName( in ) + " scaled" )
ShowImage( out1 )


问:
create a timelog line under line in javascript
simple button when you click on it it will show the current date but when you click on it agin it will show the curennt date in another line ( date after date) as a timelog set in a table. meaning that the time will show inside a box table under box.

the function that gets the date  :

```<code>Button.addEventListener("click", function Click () {
  document.getElementById("pergraph").innerHTML = Date(); }
</code>```

i cant jest put a "/n"...

thanks.

答:
Append to innerHTML using += rather than assigning with =:

Button.addEventListener("click", function Click() {
  document.getElementById("pergraph").innerHTML += Date() + "
";
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="Button" type="button">
Add date
</button>

<p id="pergraph">

</p></code>```

If you would rather have separate, style-able elements, wrap the date in a span  and style with CSS:

Button.addEventListener("click", function Click() {
  document.getElementById("pergraph").innerHTML += "" + Date() + "";
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#pergraph span {
  display: block;
  background: #f2f2f2;
  margin-bottom: 4px;
  padding: 4px;
}</code>```

<button id="Button" type="button">
Add date
</button>

```

Body:
simple button when you click on it it will show the current date but when you click on it agin it will show the curennt date in another line ( date after date) as a timelog set in a table. meaning that the time will show inside a box table under box.

the function that gets the date  :

Button.addEventListener("click", function Click () {
  document.getElementById("pergraph").innerHTML = Date(); }

i cant jest put a "/n"...

thanks.

Body:
Append to innerHTML using += rather than assigning with =:

Button.addEventListener("click", function Click() {
  document.getElementById("pergraph").innerHTML += Date() + "<br>";
})

<button id="Button" type="button">
Add date
</button>

<p id="pergraph">

</p>

If you would rather have separate, style-able elements, wrap the date in a span  and style with CSS:

Button.addEventListener("click", function Click() {
  document.getElementById("pergraph").innerHTML += "<span>" + Date() + "</span>";
})

#pergraph span {
  display: block;
  background: #f2f2f2;
  margin-bottom: 4px;
  padding: 4px;
}

<button id="Button" type="button">
Add date
</button>

<p id="pergraph">

</p>


问:
Check if custom font can display character
I have a custom font which is displaying the box character. The font I am using does not support all languages apparently. I want to check if the String I am about to display can be displayed by my custom font. If it cannot then I want to use the standard Android font (which I know can display the characters). I can't find a method to check if my Typeface can display a particular String though. I am sure I have seen a method around that does this somewhere. Anyone know?</p>

答:
For those of you who would still like your app to be compatible with APIs less than 23 and still use the hasGlyph function in your code, you can use the @TargetApi(23) in the following way:

```<code>@TargetApi(23)
public boolean isPrintable( String c ) {
    Paint paint=new Paint();
    boolean hasGlyph=true;
    hasGlyph=paint.hasGlyph(c);
    return hasGlyph;
}
</code>```

And then in your code:

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if(isPrintable(yourString)) {
        //Do Something
    }
}
</code>```

The only problem is that in APIs lower than 23, your app may show blank symbols. But at least in API23+ your app will be perfect.

Body:
For those of you who would still like your app to be compatible with APIs less than 23 and still use the hasGlyph function in your code, you can use the @TargetApi(23) in the following way:

@TargetApi(23)
public boolean isPrintable( String c ) {
    Paint paint=new Paint();
    boolean hasGlyph=true;
    hasGlyph=paint.hasGlyph(c);
    return hasGlyph;
}

And then in your code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if(isPrintable(yourString)) {
        //Do Something
    }
}

The only problem is that in APIs lower than 23, your app may show blank symbols. But at least in API23+ your app will be perfect.


问:
Jhipster for production error
I have a big problem more then 3 days. I generated project with jhipster and after that i want to set new project in production.
I try with Heroku just create new jhipster project, after that i go to:
-heroku login
-jhipster heroku
and automatic go to building application
i get some errors (copy down) and after that i get this message:

Your app should now be live. To view it run
        heroku open
And you can view the logs with this command
        heroku logs --tail
After application modification, redeploy it with
        jhipster heroku
Congratulations, JHipster execution is complete!

But when i type heroku open in my browser i have an error:
Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details.

heroku open - application error

This is error when start jhipster heroku:

Look error

Also, i try to put just .war in my Tomcat 7.0 server, but i have trouble when put ./mvnw -Pprod package (have some error like up), and i get .war but my server upload him and dont give me response, i think its problem like up.

I dont have solution for this, thanks a lot.

答:
Your application logs are pretty clear:

```<code>Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'
</code>```

Your application cannot access database probably because you did not provision one, so the heroku sub generator could not value a jdbc url in application*.yml.

So you have 2 alternatives:

register a credit card (even for using free account)

configure a free add-on (e.g. JawsDB MySQL or Heroku Postgresql) in Heroku dashboard.

Title: Jhipster for production error

Body:
Your application logs are pretty clear:

Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'

Your application cannot access database probably because you did not provision one, so the heroku sub generator could not value a jdbc url in application*.yml.

So you have 2 alternatives:

register a credit card (even for using free account)

configure a free add-on (e.g. JawsDB MySQL or Heroku Postgresql) in Heroku dashboard.


问:
Spring webflow Value of second parameter is not passed to subflow

Hi, I am using spring webflow2.4.4 with spring4.1.3.
 I am trying to pass values between two flows as below.
sending value from flow first xml

```<code><action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value1" value="form.value1" />
        <set name="flowScope.value2" value="form.value2" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value1" value="value1" />
        <input name="value2" value="value2" />
        ...
    </subflow-state>
</code>```

reeving data in flow second view xml

```<code><input name="value1" type="string" />
    <input name="value2" type="string" />
</code>```

now in view xml I am able to receive value for "value1" what I passed from first flow but getting value for 'value2' is null.

I tried switching the position in first flow as below

```<code><action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value2" value="value2" />
        <input name="value1" value="value1" />
        ...
    </subflow-state>
</code>```

Now I am able to see value of 'value2' but value for 'value1' receiving is null.

What is wrong here? see below debug logs for both example

1st trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value1' -> 'ABCDF', 'value2' -> [null]]

2nd trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value2' -> 'ABCDF', 'value1' -> [null]]

I want to pass both thew values to second flow but it second parameter is getting skipped somehow.

答:
Thanks rptmat57, below code worked for me. </p>

```<code><action-state id="submit">
    <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
    <transition on="success" to="view" >
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
    </transition>
</action-state>
</code>```

Body:
Hi, I am using spring webflow2.4.4 with spring4.1.3.
 I am trying to pass values between two flows as below.
sending value from flow first xml

<action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value1" value="form.value1" />
        <set name="flowScope.value2" value="form.value2" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value1" value="value1" />
        <input name="value2" value="value2" />
        ...
    </subflow-state>

reeving data in flow second view xml

<input name="value1" type="string" />
    <input name="value2" type="string" />

now in view xml I am able to receive value for "value1" what I passed from first flow but getting value for 'value2' is null.

I tried switching the position in first flow as below

<action-state id="submit">
        <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
        <transition on="success" to="view" />
    </action-state>

    <subflow-state id="view" subflow="flow/path/view">
        <input name="value2" value="value2" />
        <input name="value1" value="value1" />
        ...
    </subflow-state>

Now I am able to see value of 'value2' but value for 'value1' receiving is null.

What is wrong here? see below debug logs for both example

1st trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value1' -> 'ABCDF', 'value2' -> [null]]

2nd trial

DEBUG SubflowState - Calling subflow 'flow/path/view' with input map['value2' -> 'ABCDF', 'value1' -> [null]]

I want to pass both thew values to second flow but it second parameter is getting skipped somehow.

Body:
Thanks rptmat57, below code worked for me.

<action-state id="submit">
    <evaluate expression="someMethod(form)" result="flowScope.saveStatus" />
    <transition on="success" to="view" >
        <set name="flowScope.value2" value="form.value2" />
        <set name="flowScope.value1" value="form.value1" />
    </transition>
</action-state>


问:
Stop a stopwatch
I have the following code in a JPanel class which is added to a another class (JFrame). What I'm trying to implement is some sort of a stopwatch program.

```<code>startBtn.addActionListener(new startListener());

class startListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        Timer time = new Timer();
        time.scheduleAtFixedRate(new Stopwatch(), 1000, 1000);
    }
}
</code>```

This is another class which basically the task.

```<code>public class Stopwatch extends TimerTask {

    private final double start = System.currentTimeMillis();

    public void run() {
        double curr = System.currentTimeMillis();
        System.out.println((curr - start) / 1000);
    }
}
</code>```

The timer works fine and this is definitely far from complete but I'm not sure how to code the stop button which should stop the timer. Any advice on this? BTW I'm using java.util.timer

EDIT: I want to be able to start it again after stopping it (without the timer being reset)

答:
```<code>long startTime = System.currentTimeMillis();
    Timer timer = new Timer(100,new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            long elapsedTime = System.currentTimeMillis()-startTime;
            long mil = elapsedTime%1000;
            long sec = elapsedTime/1000%60;
            long min = elapsedTime/60000%60;
            long hr = elapsedTime/3600000;
            label.setText(String.format("%02d:%02d:%02d.%03d", hr,min,sec,mil));
        }
    });
    timer.start();
</code>```

Title: Stop a stopwatch

Body:
I have the following code in a JPanel class which is added to a another class (JFrame). What I'm trying to implement is some sort of a stopwatch program.

startBtn.addActionListener(new startListener());

class startListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        Timer time = new Timer();
        time.scheduleAtFixedRate(new Stopwatch(), 1000, 1000);
    }
}

This is another class which basically the task.

public class Stopwatch extends TimerTask {

    private final double start = System.currentTimeMillis();

    public void run() {
        double curr = System.currentTimeMillis();
        System.out.println((curr - start) / 1000);
    }
}

The timer works fine and this is definitely far from complete but I'm not sure how to code the stop button which should stop the timer. Any advice on this? BTW I'm using java.util.timer

EDIT: I want to be able to start it again after stopping it (without the timer being reset)


问:
Download files with ServiceStack Rest-API
I'm quite new to REST-services in general and I'm playing around with ServiceStack (which is awesome!). I have some services running and now I want to be able to download files (zip) via the service.

My idea is to set a route (/download) to receive files and download them with the client to store them locally.

My current approach looks like this:

```<code>[Route("/download")]
public class DownloadRequest : IReturn<HttpResult>
{

}

public class FileDownloadService : Service
{
    public object Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        string mimeType = "application/zip";
        FileInfo fi = new FileInfo(fileFullPath);

        byte[] reportBytes = File.ReadAllBytes(fi.FullName);
        HttpResult result = new HttpResult(reportBytes, mimeType);

        result.Headers.Add("Content-Disposition", "attachment;filename=Download.zip;");

        return result;
    }
}
</code>```

I'd like to change this implementation to send data as stream. I stumbled upon IStreamWriterAsync, but couldn't really find documentation on usage for this. I'd also like to be able to handle client-side download with the ServiceStack C#-Client.

What would be a good strategy do implement my plan?

Edit: Something like that?

```<code>[Route("/download")]
public class DownloadRequest : IReturn<Stream>
{

}

public class FileDownloadService : Service, IHasOptions
{
    public IDictionary<string, string> Options { get; private set; }

    public Stream Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        FileInfo fi = new FileInfo(fileFullPath);

        Options = new Dictionary<string, string>
        {
            {"Content-Type","application/zip" },
            {"Content-Disposition", "attachment;filename=Download.zip;" }
        };

        return fi.OpenRead();
    }
}
</code>```

答:
Have a look at this article. Basically, just return a Stream. You can use fi.OpenRead and return that stream.

To combine headers and stream, an option is a custom return type instead, something like this

```<code>public class DownloadFileResult : IStreamWriterAsync, IHasOptions
{
    private readonly Stream _stream;
    public IDictionary<string, string> Options { get; }

    public DownloadFileResult(Stream responseStream, string mime, string filename)
    {
        _stream = responseStream;

        Options = new Dictionary<string, string>()
        {
            {"Content-Disposition", $"attachment; filename=\"{filename}\";"},
            {"Content-Type", mime}
        };
    }

    public async Task WriteToAsync(Stream responseStream, CancellationToken token)
    {
        if (_stream == null) {
            return;
        }

        await _stream.CopyToAsync(responseStream);
        responseStream.Flush();
    }
}
</code>```

Body:
I'm quite new to REST-services in general and I'm playing around with ServiceStack (which is awesome!). I have some services running and now I want to be able to download files (zip) via the service.

My idea is to set a route (/download) to receive files and download them with the client to store them locally.

My current approach looks like this:

[Route("/download")]
public class DownloadRequest : IReturn<HttpResult>
{

}

public class FileDownloadService : Service
{
    public object Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        string mimeType = "application/zip";
        FileInfo fi = new FileInfo(fileFullPath);

        byte[] reportBytes = File.ReadAllBytes(fi.FullName);
        HttpResult result = new HttpResult(reportBytes, mimeType);

        result.Headers.Add("Content-Disposition", "attachment;filename=Download.zip;");

        return result;
    }
}

I'd like to change this implementation to send data as stream. I stumbled upon IStreamWriterAsync, but couldn't really find documentation on usage for this. I'd also like to be able to handle client-side download with the ServiceStack C#-Client.

What would be a good strategy do implement my plan?

Edit: Something like that?

[Route("/download")]
public class DownloadRequest : IReturn<Stream>
{

}

public class FileDownloadService : Service, IHasOptions
{
    public IDictionary<string, string> Options { get; private set; }

    public Stream Any(DownloadRequest request)
    {
        string fileFullPath = @"C:\Users\marcel\Downloads\test.zip";
        FileInfo fi = new FileInfo(fileFullPath);

        Options = new Dictionary<string, string>
        {
            {"Content-Type","application/zip" },
            {"Content-Disposition", "attachment;filename=Download.zip;" }
        };

        return fi.OpenRead();
    }
}

Body:
Have a look at this article. Basically, just return a Stream. You can use fi.OpenRead and return that stream.

To combine headers and stream, an option is a custom return type instead, something like this

public class DownloadFileResult : IStreamWriterAsync, IHasOptions
{
    private readonly Stream _stream;
    public IDictionary<string, string> Options { get; }

    public DownloadFileResult(Stream responseStream, string mime, string filename)
    {
        _stream = responseStream;

        Options = new Dictionary<string, string>()
        {
            {"Content-Disposition", $"attachment; filename=\"{filename}\";"},
            {"Content-Type", mime}
        };
    }

    public async Task WriteToAsync(Stream responseStream, CancellationToken token)
    {
        if (_stream == null) {
            return;
        }

        await _stream.CopyToAsync(responseStream);
        responseStream.Flush();
    }
}


问:
Passing data from the child modal to the parent

When I created a SeleccionServicioComponentMD modal window (child), I used this way:https://valor-software.com/ngx-bootstrap/#/modals#service-component

Inside the  child there is button. When it is clicked:

1) the parent should close this child.

2) the parent should display another modal.

My attempt: The child (modal) emits an event to its parent but:

3) the parent didn't include an <app-seleccion-servicio-component> tag inside its HTML because its child was dynamically created. So, where does the parent listen for this emitted event from its children?

The expected result is:

4) click on the button inside the child component.

5) the parent closes this child (modal window).

6) the parent shows another modal window.

7) I am stuck on this point. I don't know how to do so that the parent listens the event emitted by its parent with no <app-seleccion-servicio-component> tag.

答:
Can't say much without looking at your code but you can create an EventEmitter in your child component and subscribe to it from parent.

Example: https://plnkr.co/edit/b6qHpolJmUFy7dYvYpkJ?p=preview

```<code>  /* CHILD COMPONENT */
  public event: EventEmitter<any> = new EventEmitter();

  triggerEvent() {
    this.event.emit({data: 12345});
  }
</code>```

```<code>  /* PARENT COMPONENT */
 this.bsModalRef.content.event.subscribe(data => {
    console.log('Child component\'s event was triggered', data);
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Can't say much without looking at your code but you can create an EventEmitter in your child component and subscribe to it from parent.

Example: https://plnkr.co/edit/b6qHpolJmUFy7dYvYpkJ?p=preview

  /* CHILD COMPONENT */
  public event: EventEmitter<any> = new EventEmitter();

  triggerEvent() {
    this.event.emit({data: 12345});
  }

  /* PARENT COMPONENT */
 this.bsModalRef.content.event.subscribe(data => {
    console.log('Child component\'s event was triggered', data);
 });