问:
Fill fields in webview programmatically
I was trying to insert values into fields in a webpage loaded inside a webview .

The exact thing i was doing was this -

```<code>String date = "5/8/1994";
webview.loadUrl("javascript:var uselessvar_a =document.getElementById('dpStudentdob_dateInput').value='" + date + "';");
</code>```

Problem

So this is suppose to insert the value into the field into the given
id. and it gives me the exact result , it insert into the field. but
when the submit button is pressed the error is shown as this data is
not correct. but when i insert the values by typing the same value is
accepted.

The problem is with inserting value into the DOB field in the
webpage.

The registration number field works fine and the clicking button also
works fine in my code.

the webpage is was loading is this.

I want to enter the date into the date DOB field in the webpage.

My full java class is-

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

WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    webview = (WebView) findViewById(R.id.webView);

    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setDisplayZoomControls(false);

    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.getSettings().setJavaScriptEnabled(true);
    webview.setWebChromeClient(new WebChromeClient());

    webview.getSettings().setDomStorageEnabled(true);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String password = "1201329022";
            String date = "5/8/1994";
            webview.loadUrl("javascript:var uselessvar =document.getElementById('txtRegNo').value='" + password + "';");
            webview.loadUrl("javascript:var uselessvar_a =document.getElementById('dpStudentdob_dateInput').value='" + date + "';");
            webview.loadUrl("javascript:var uselessvar_b =document.getElementById('btnView').click();");
        }
    });

    webview.loadUrl("http://bputexam.in/StudentSection/ResultPublished/StudentResult.aspx");
}

}
</code>```

Do any one have any suggestion for this.

答:
To insert text inside an input text field in webview you have to use javascript like below:

```<code>webView.loadUrl("javascript:(function(){l=document.getElementById('form1:txtDrname').value='" + editTextInput.getText().toString() + "';})()");
</code>```

Then you can click a button inside webview to perform search:

```<code>webView.loadUrl("javascript:(function(){l=document.getElementById('form1:btnSubmit');e=document.createEvent('HTMLEvents');e.initEvent('click',true,true);l.dispatchEvent(e);})()");
</code>```

Title: Fill fields in webview programmatically

Body:
I was trying to insert values into fields in a webpage loaded inside a webview .

The exact thing i was doing was this -

String date = "5/8/1994";
webview.loadUrl("javascript:var uselessvar_a =document.getElementById('dpStudentdob_dateInput').value='" + date + "';");

Problem

So this is suppose to insert the value into the field into the given
id. and it gives me the exact result , it insert into the field. but
when the submit button is pressed the error is shown as this data is
not correct. but when i insert the values by typing the same value is
accepted.

The problem is with inserting value into the DOB field in the
webpage.

The registration number field works fine and the clicking button also
works fine in my code.

the webpage is was loading is this.

I want to enter the date into the date DOB field in the webpage.

My full java class is-

public class MainActivity extends AppCompatActivity {

WebView webview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    webview = (WebView) findViewById(R.id.webView);

    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setDisplayZoomControls(false);

    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.getSettings().setJavaScriptEnabled(true);
    webview.setWebChromeClient(new WebChromeClient());

    webview.getSettings().setDomStorageEnabled(true);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            String password = "1201329022";
            String date = "5/8/1994";
            webview.loadUrl("javascript:var uselessvar =document.getElementById('txtRegNo').value='" + password + "';");
            webview.loadUrl("javascript:var uselessvar_a =document.getElementById('dpStudentdob_dateInput').value='" + date + "';");
            webview.loadUrl("javascript:var uselessvar_b =document.getElementById('btnView').click();");
        }
    });

    webview.loadUrl("http://bputexam.in/StudentSection/ResultPublished/StudentResult.aspx");
}

}

Do any one have any suggestion for this.

Body:
To insert text inside an input text field in webview you have to use javascript like below:

webView.loadUrl("javascript:(function(){l=document.getElementById('form1:txtDrname').value='" + editTextInput.getText().toString() + "';})()");

Then you can click a button inside webview to perform search:

webView.loadUrl("javascript:(function(){l=document.getElementById('form1:btnSubmit');e=document.createEvent('HTMLEvents');e.initEvent('click',true,true);l.dispatchEvent(e);})()");


来源: stackexchange

问:
Dhitools plot_item results in python failure
I am using dhitools developed by robjameswall for reading and plotting DHI's Mike files (i.e DFSU). My code is as follows:

```<code>modelpath = 'xxx.dfsu'
area = dhitools.dfsu.Dfsu(modelpath)
fig,ax,tf = area.plot_item(item_name= 'Total SSC', tstep=1)
plt.show()
</code>```

The code fails at the plot_item line. There is no error message, it just shows that the kernal have died (i am using jupyter) and python is not working properly. Any ideas what is happening? I am following the instructions provided by the author here: https://github.com/robjameswall/dhitools/blob/master/notebooks/dfsu_analysis.ipynb

If any one has experience using this module, please let me know.

Cheers

答:
An update on my question. I realized that it works perfectly fine when working with HD files (items include surface elevation, water depth, current speed, etc.). Example of the plot produced below:

However, the problem arises when i am processing MT files (item == Total Suspended Solids (SSC) in mg/L units). Python fails to run. I believe this should be an issue with the dfsu.py script which uses matplotlib triplot and tricontourf.

ContentLicense: CC BY-SA 4.0

Body:
I am using dhitools developed by robjameswall for reading and plotting DHI's Mike files (i.e DFSU). My code is as follows:

modelpath = 'xxx.dfsu'
area = dhitools.dfsu.Dfsu(modelpath)
fig,ax,tf = area.plot_item(item_name= 'Total SSC', tstep=1)
plt.show()

The code fails at the plot_item line. There is no error message, it just shows that the kernal have died (i am using jupyter) and python is not working properly. Any ideas what is happening? I am following the instructions provided by the author here: https://github.com/robjameswall/dhitools/blob/master/notebooks/dfsu_analysis.ipynb

If any one has experience using this module, please let me know.

Cheers


问:
ExoPlayer2 how to loop a part / segment of a video
I have a video of 10 seconds. I want to loop a segment from 2 seconds to 6 seconds. Starting the player at the right time is easy:

```<code>player?.seekTo(2000)
</code>```

I don't think there is a functionality available in the ExoPlayer2 library to define an end position. So I tried to add a delay co-routine. With the method seekToPositionAndStartCounter. This works in a separate project. But used in the actual project, onPlayerStateChanged gets triggered a lot of times all of a sudden.

```<code>var elapsedTime = 0L // just for testing

private fun showVideoWhenDoneLoading() {
    videoView?.player?.addListener(object : Player.EventListener {
        override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
            super.onPlayerStateChanged(playWhenReady, playbackState)
            if (playbackState == Player.STATE_READY) {
                if (playWhenReady) {
                    seekToPositionAndStartCounter()
                } else {
                    cancelCounter()
                }
            }
        }
    })
}

private fun seekToPositionAndStartCounter() {
    elapsedTime = System.currentTimeMillis()

    cancelCounter()
    job = GlobalScope.launch(Dispatchers.IO) {
        Timber.d("starting Thread name = ${Thread.currentThread().name}")
        player?.seekTo(startPosition)

        if (duration != 0L) {
            runBlocking {
                delay(duration)
            }
            GlobalScope.launch(Dispatchers.Main) {
                Timber.d("duration = $duration elapsedTime = ${System.currentTimeMillis()-elapsedTime} Thread name = ${Thread.currentThread().name}")
                seekToPositionAndStartCounter()
            }
        }
    }
}

private fun cancelCounter() {
    job?.cancel()
    job = null
}
</code>```

答:
If you don't try this then think about this.

getCurrentPosition of player and if player reach end position which you want then run player.seekto(2) it loops the video in specific segment of video.

Body:
I have a video of 10 seconds. I want to loop a segment from 2 seconds to 6 seconds. Starting the player at the right time is easy:

player?.seekTo(2000)

I don't think there is a functionality available in the ExoPlayer2 library to define an end position. So I tried to add a delay co-routine. With the method seekToPositionAndStartCounter. This works in a separate project. But used in the actual project, onPlayerStateChanged gets triggered a lot of times all of a sudden.

var elapsedTime = 0L // just for testing

private fun showVideoWhenDoneLoading() {
    videoView?.player?.addListener(object : Player.EventListener {
        override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
            super.onPlayerStateChanged(playWhenReady, playbackState)
            if (playbackState == Player.STATE_READY) {
                if (playWhenReady) {
                    seekToPositionAndStartCounter()
                } else {
                    cancelCounter()
                }
            }
        }
    })
}

private fun seekToPositionAndStartCounter() {
    elapsedTime = System.currentTimeMillis()

    cancelCounter()
    job = GlobalScope.launch(Dispatchers.IO) {
        Timber.d("starting Thread name = ${Thread.currentThread().name}")
        player?.seekTo(startPosition)

        if (duration != 0L) {
            runBlocking {
                delay(duration)
            }
            GlobalScope.launch(Dispatchers.Main) {
                Timber.d("duration = $duration elapsedTime = ${System.currentTimeMillis()-elapsedTime} Thread name = ${Thread.currentThread().name}")
                seekToPositionAndStartCounter()
            }
        }
    }
}

private fun cancelCounter() {
    job?.cancel()
    job = null
}


问:
Merging two complex objects in PHP
I have two data objects converted from JSON. both are quite deeply complex and I'd like to merge them in a similar fashion to how jQuery would merge two objects using extend.

example

JSON 1:

```<code>{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "misc": "0",
                ...
            },
            ...
        },
        ...
    },
    ...
}
</code>```

JSON 2:

```<code>{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}
</code>```

Merged into

```<code>{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}
</code>```

What's the best way to approach this with PHP objects.

答:
As hinted by @infinum's link-only answer, array_replace_recursive() is the correct, native tool for this task.

I am not sure why the OP accepted @meouw's answer as array_merge_recursive() is an inappropriate call and rolling-your-own custom recursive script is unnecessary labor when php already has a single, native call.

With the green tick and so many upvotes on an partially incorrect with a suboptimal bandaid answer, this page is very likely to misinform researchers and represents an unattractive candidate to close future duplicate questions.

The script merely needs to decode the json strings into arrays, call the recursive function, then re-encode the resultant array.

Here is a full demonstration of how to prepare the json strings and employ array_replace_recursive().

Code: (Demo)

```<code>$json1 = '{"blah":{"params":{"foo":{"default":"bar","misc":"0"}}}}';
$json2 = '{"blah":{"params":{"foo":{"value":"val","misc":"1"}}}}';
echo json_encode(
    array_replace_recursive(
        json_decode($json1, true),
        json_decode($json2, true)
    ),
    JSON_PRETTY_PRINT
);
</code>```

Output:

```<code>{
    "blah": {
        "params": {
            "foo": {
                "default": "bar",
                "misc": "1",
                "value": "val"
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Merging two complex objects in PHP

Body:
I have two data objects converted from JSON. both are quite deeply complex and I'd like to merge them in a similar fashion to how jQuery would merge two objects using extend.

example

JSON 1:

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "misc": "0",
                ...
            },
            ...
        },
        ...
    },
    ...
}

JSON 2:

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}

Merged into

{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}

What's the best way to approach this with PHP objects.

Body:
As hinted by @infinum's link-only answer, array_replace_recursive() is the correct, native tool for this task.

I am not sure why the OP accepted @meouw's answer as array_merge_recursive() is an inappropriate call and rolling-your-own custom recursive script is unnecessary labor when php already has a single, native call.

With the green tick and so many upvotes on an partially incorrect with a suboptimal bandaid answer, this page is very likely to misinform researchers and represents an unattractive candidate to close future duplicate questions.

The script merely needs to decode the json strings into arrays, call the recursive function, then re-encode the resultant array.

Here is a full demonstration of how to prepare the json strings and employ array_replace_recursive().

Code: (Demo)

$json1 = '{"blah":{"params":{"foo":{"default":"bar","misc":"0"}}}}';
$json2 = '{"blah":{"params":{"foo":{"value":"val","misc":"1"}}}}';
echo json_encode(
    array_replace_recursive(
        json_decode($json1, true),
        json_decode($json2, true)
    ),
    JSON_PRETTY_PRINT
);

Output:

{
    "blah": {
        "params": {
            "foo": {
                "default": "bar",
                "misc": "1",
                "value": "val"
            }
        }
    }
}


问:
Eclipse Installer > Eclipse IDE For Java Developers > Eclipse > Eclipse Marketplace > Kotlin > java.util.ArrayList?
Used equinox.launcher_1.5.600.v20191014-2022 to install Eclipse IDE for Java Developers 2019-12 then invoked Eclipse and used Eclipse Marketplace to install Kotlin Plugin for Eclipse 0.8.19. I created a Kotlin project. Using Package Explorer I expanded the contents of JRE System Library.

I expected to see java.util.ArrayList be listed in order to use on
kotlin-stdlib / kotlin.collections / ArrayList . Is there some other step missing?

答:
That listing is showing the 'modules' in the JRE. Modules were introduced in Java 9.

The 'java.util' package is in the 'java.base' module as show in this screen shot:


问:
Call to undefined method stdClass::count() in laravel
I trying to paginate my JSON response but got error like this

Call to undefined method stdClass::count()

My JSON response from the Laravel API by using guzzle ......

here is my controller code

public function index()
{
    $response =  $this->client->get('getUserIndex')->getBody();
    $content = json_decode($response->getContents());
    $total = $content->count();
    $paginationRecord = CollectionPaginate::paginate($content, $total, '15');
    return view('configuration.comuserprofiles.ComUserProfilesList', ['paginationRecord' => $paginationRecord->data]);
}
```

答:
```<code>$content = json_decode($response->getContents());
$total = $content->count();
</code>```

I am not entirely sure why you think the result of json_decode would have a count method? The JSON decoding always results in a generic object (stdClass) since there's no way for the PHP interpreter to know it represents an available class.

The ->count method is available on Countable implementations (such as ArrayCollection). If you expect a Countable class, then you can either have a factory to build your object from JSON or try to cast the stdClass to ArrayCollection.

Otherwise, if your JSON data is a valid array, you can try to use

```<code>$decoded = json_decode($data, true)
</code>```

meaning it will decode it to an array rather than an object, which enables you to do

```<code>count($decoded)
</code>```

Body:
$content = json_decode($response->getContents());
$total = $content->count();

I am not entirely sure why you think the result of json_decode would have a count method? The JSON decoding always results in a generic object (stdClass) since there's no way for the PHP interpreter to know it represents an available class.

The ->count method is available on Countable implementations (such as ArrayCollection). If you expect a Countable class, then you can either have a factory to build your object from JSON or try to cast the stdClass to ArrayCollection.

Otherwise, if your JSON data is a valid array, you can try to use

$decoded = json_decode($data, true)

meaning it will decode it to an array rather than an object, which enables you to do

count($decoded)


问:
How to use custom DateRangePicker widget with Django Filter's DateFromToRangeFilter
So I have this filter using Django Filter:

```<code>class AssignmentFilter(FilterSet):
    assignment_date = filters.DateFromToRangeFilter()
</code>```

This built in class of Django Filter generates a form with these two inputs:

```<code><input type="text" name="assignment_date_after" id="id_assignment_date_0">
<input type="text" name="assignment_date_before" id="id_assignment_date_1">
</code>```

So there you pick the two dates and based on that it will get you the filtered QuerySet. All working well.

However I would like to use this usefull DateRangePicker:
https://www.daterangepicker.com/

This gets activated like this:

```<code><input type="text" name="dates" class="form-control">

<script>
$('input[name="dates"]').daterangepicker();
</script>
</code>```

However as you can see, this is only one field where the range between the dates will be set. But Django Filter works with an start input field and end input field.

How can I modify this so that I can use the nice widget that belongs to input[name="dates"].

Maybe a solution is to process it with JavaScript after a GET request. The function will then take the start date and inject it into the id_assignment_date_0 field. And take the end date and inject it to the id_assignment_date_1 field. Both the field id_assignment_date_0 and id_assignment_date_1 will be visually hidden then in the form. It seems quite hacky though.

Does anyone have a clever solution for this?

答:
According to this example, you can accomplish what you want like this:

```<code><input type="text" id="datePicker" name="dates" class="form-control">
<input type="hidden" name="assignment_date_after" id="id_assignment_date_0">
<input type="hidden" name="assignment_date_before" id="id_assignment_date_1">

<script>
$(function() {
  $('input[name="dates"]').daterangepicker({
    opens: 'left'
  }, function(start, end, label) {
    $('#id_assignment_date_0').val(start)
    $('#id_assignment_date_1').val(end)
  });
  $('#datePicker').removeAttr('name');
});
</script>
</code>```

Although, the format might differ from what you need. You can also change the format with something like below:

```<code>$('#id_assignment_date_0').val(start.format('YYYY-MM-DD'))
</code>```

Body:
So I have this filter using Django Filter:

class AssignmentFilter(FilterSet):
    assignment_date = filters.DateFromToRangeFilter()

This built in class of Django Filter generates a form with these two inputs:

<input type="text" name="assignment_date_after" id="id_assignment_date_0">
<input type="text" name="assignment_date_before" id="id_assignment_date_1">

So there you pick the two dates and based on that it will get you the filtered QuerySet. All working well.

However I would like to use this usefull DateRangePicker:
https://www.daterangepicker.com/

This gets activated like this:

<input type="text" name="dates" class="form-control">

However as you can see, this is only one field where the range between the dates will be set. But Django Filter works with an start input field and end input field.

How can I modify this so that I can use the nice widget that belongs to input[name="dates"].

Maybe a solution is to process it with JavaScript after a GET request. The function will then take the start date and inject it into the id_assignment_date_0 field. And take the end date and inject it to the id_assignment_date_1 field. Both the field id_assignment_date_0 and id_assignment_date_1 will be visually hidden then in the form. It seems quite hacky though.

Does anyone have a clever solution for this?

Body:
According to this example, you can accomplish what you want like this:

<input type="text" id="datePicker" name="dates" class="form-control">
<input type="hidden" name="assignment_date_after" id="id_assignment_date_0">
<input type="hidden" name="assignment_date_before" id="id_assignment_date_1">

<script>
$(function() {
  $('input[name="dates"]').daterangepicker({
    opens: 'left'
  }, function(start, end, label) {
    $('#id_assignment_date_0').val(start)
    $('#id_assignment_date_1').val(end)
  });
  $('#datePicker').removeAttr('name');
});
</script>

Although, the format might differ from what you need. You can also change the format with something like below:

$('#id_assignment_date_0').val(start.format('YYYY-MM-DD'))


问:
Replace multiple characters in a string with different characters
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

```<code>[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...
</code>```

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

```<code>Key1=Value1
Key2=Value2
Key3=Value3
...
</code>```

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

```<code>string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");
</code>```

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

答:
You can avoid one Replace with help of Regex.

```<code>Regex pattern = new Regex(@"[\[,\]]");
string outval = pattern.Replace(string.Join("\n", listOfLines), "")
                       .Replace(", ", "=");
</code>```

Body:
I am converting a list to string and I am wondering if there is a more simplified way to replace multiple characters w/ different characters. I'm coding in C# and this is what my list looks like:

[0]: [Key1, Value1]
[1]: [Key2, Value2]
[2]: [Key3, Value3]
...

So basically, I wanted to replace ", " w/ "=" and both "[]" with "" to achieve this format:

Key1=Value1
Key2=Value2
Key3=Value3
...

I already did get this format using the following code below and I am kinda worried I am overusing the Replace command.

string out = string.Join("\n", listOfLines).Replace(", ", "=").Replace("[", "").Replace("]","");

I have found a similar question but it does specify that the characters are all replaced by "\n" only.

Any help would be greatly appreciated. Thanks!

Body:
You can avoid one Replace with help of Regex.

Regex pattern = new Regex(@"[\[,\]]");
string outval = pattern.Replace(string.Join("\n", listOfLines), "")
                       .Replace(", ", "=");


问:
FTP Upload in Release Pipeline fails with FTPError: 500 Syntax error, command unrecognized
I have created a Release Pipeline in Azure Devops that first archives two files and then tries to upload those zip files to an FTP server.

The archiving works fine, however the upload task always fails. I receive the following console output:

```<code>2020-02-13T10:28:03.9716469Z ##[section]Starting: FTP Upload: $(Build.ArtifactStagingDirectory)
2020-02-13T10:28:03.9792841Z ==============================================================================
2020-02-13T10:28:03.9792892Z Task         : FTP upload
2020-02-13T10:28:03.9792921Z Description  : Upload files using FTP
2020-02-13T10:28:03.9792964Z Version      : 2.157.0
2020-02-13T10:28:03.9792992Z Author       : Microsoft Corporation
2020-02-13T10:28:03.9793020Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/ftp-upload
2020-02-13T10:28:03.9793049Z ==============================================================================
2020-02-13T10:28:04.9536900Z connecting to: mydomain.com:21
2020-02-13T10:28:05.1325089Z ##[error]FTPError: 500 Syntax error, command unrecognized.
2020-02-13T10:28:05.1333616Z ##[error]Ftp Upload failed
2020-02-13T10:28:31.5036758Z ##[error]The operation was canceled.
2020-02-13T10:28:31.5040435Z ##[section]Finishing: FTP Upload: $(Build.ArtifactStagingDirectory)
</code>```

Here is my YAML:

```<code>steps:
- task: FtpUpload@2
  displayName: 'FTP Upload: $(Build.ArtifactStagingDirectory)'
  inputs:
    credentialsOption: inputs
    serverUrl: 'ftp://mydomain.com'
    username: usr
    password: pwd
    rootDirectory: '$(Build.ArtifactStagingDirectory)'
    remoteDirectory: '/files/upload-Test/'
    trustSSL: true
</code>```

I also tried to connect to a different SFTP server, but I received similar results: FTPError: 550 SSL/TLS required on the control channel

Do you have any suggestions what I could try in order to make this work?

EDIT: Now with Debug output:

```<code>expanding braces
pattern: 'D:/a/r1/a/$(Build.ArtifactStagingDirectory)/**'
applying include pattern against original list
1 matches
1 final results
Found total matches: 1
adding file:   D:\a\r1\a\$(Build.ArtifactStagingDirectory)\FILENAME.zip
connecting to: domain.com:21
Connected to MY-IP
< 220 Speak friend, and enter
Login security: No encryption
> USER usr
< 331 FTP login okay, send password.
> PASS ###
< 230 User logged in, proceed.
> TYPE I
< 200 Using BINARY mode to transfer data.
> STRU F
< 500 Syntax error, command unrecognized.
FTPError: 500 Syntax error, command unrecognized.
Processed: ##vso[task.issue type=error;]FTPError: 500 Syntax error, command unrecognized.
task result: Failed
Ftp Upload failed
Processed: ##vso[task.issue type=error;]Ftp Upload failed
Processed: ##vso[task.complete result=Failed;]Ftp Upload failed
</code>```

答:
For this issue , there is a recently event of availability degradation of Azure DevOps, which could be the reason of this error.

The shortage of ATs is causing high CPU on the ATs, resulting in slow and failed commands across Boards, Repos, Pipelines, and Test Plans.

If you want to know more detailed information, please refer to this report.The issue is now fully mitigated.

Body:
I have created a Release Pipeline in Azure Devops that first archives two files and then tries to upload those zip files to an FTP server.

The archiving works fine, however the upload task always fails. I receive the following console output:

2020-02-13T10:28:03.9716469Z ##[section]Starting: FTP Upload: $(Build.ArtifactStagingDirectory)
2020-02-13T10:28:03.9792841Z ==============================================================================
2020-02-13T10:28:03.9792892Z Task         : FTP upload
2020-02-13T10:28:03.9792921Z Description  : Upload files using FTP
2020-02-13T10:28:03.9792964Z Version      : 2.157.0
2020-02-13T10:28:03.9792992Z Author       : Microsoft Corporation
2020-02-13T10:28:03.9793020Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/ftp-upload
2020-02-13T10:28:03.9793049Z ==============================================================================
2020-02-13T10:28:04.9536900Z connecting to: mydomain.com:21
2020-02-13T10:28:05.1325089Z ##[error]FTPError: 500 Syntax error, command unrecognized.
2020-02-13T10:28:05.1333616Z ##[error]Ftp Upload failed
2020-02-13T10:28:31.5036758Z ##[error]The operation was canceled.
2020-02-13T10:28:31.5040435Z ##[section]Finishing: FTP Upload: $(Build.ArtifactStagingDirectory)

Here is my YAML:

steps:
- task: FtpUpload@2
  displayName: 'FTP Upload: $(Build.ArtifactStagingDirectory)'
  inputs:
    credentialsOption: inputs
    serverUrl: 'ftp://mydomain.com'
    username: usr
    password: pwd
    rootDirectory: '$(Build.ArtifactStagingDirectory)'
    remoteDirectory: '/files/upload-Test/'
    trustSSL: true

I also tried to connect to a different SFTP server, but I received similar results: FTPError: 550 SSL/TLS required on the control channel

Do you have any suggestions what I could try in order to make this work?

EDIT: Now with Debug output:

expanding braces
pattern: 'D:/a/r1/a/$(Build.ArtifactStagingDirectory)/**'
applying include pattern against original list
1 matches
1 final results
Found total matches: 1
adding file:   D:\a\r1\a\$(Build.ArtifactStagingDirectory)\FILENAME.zip
connecting to: domain.com:21
Connected to MY-IP
< 220 Speak friend, and enter
Login security: No encryption
> USER usr
< 331 FTP login okay, send password.
> PASS ###
< 230 User logged in, proceed.
> TYPE I
< 200 Using BINARY mode to transfer data.
> STRU F
< 500 Syntax error, command unrecognized.
FTPError: 500 Syntax error, command unrecognized.
Processed: ##vso[task.issue type=error;]FTPError: 500 Syntax error, command unrecognized.
task result: Failed
Ftp Upload failed
Processed: ##vso[task.issue type=error;]Ftp Upload failed
Processed: ##vso[task.complete result=Failed;]Ftp Upload failed


问:
Keyboard is hidden on orientation change
My keyboard is hidden when the orientation of the android phone changes to landscape. What should I do in order to show my keyboard?</p>

答:
Try this:

```<code> InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.showSoftInputFromWindow(enterChat.getWindowToken(), 0);

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
</code>```

This will make your keyboard always visible. In this the enterchat is editText I have used. You don't need that thing i think.

Body:
Try this:

 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.showSoftInputFromWindow(enterChat.getWindowToken(), 0);

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

This will make your keyboard always visible. In this the enterchat is editText I have used. You don't need that thing i think.


问:
Laraver DB Query
I am new in Laravel, and I don't know what is happening here. I made a simple join query with two tables, but I get the triple result. I tried with distinct(), orderBy()(getting an error)... Can someone tell me what is happening here

Laravel Query:

```<code>    public function getArtForCom($id) {
    $articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id', 'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
        ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
        ->where('kupac', $id)
        ->get();
    return response()->json($articles);
}
</code>```

and result is:

```<code>[
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "130.000",
    "price": "3.590"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "485.000",
    "price": ".790"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "7204.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "3.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "17.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": ".000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "69.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "2.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "48.000",
    "price": ".490"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "30.000",
    "price": ".488"
  }
]
</code>```

答:
You need to groupBy common key here, kup_art.sifra</p>

```<code>  public function getArtForCom($id) {
$articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id',
   'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as
   group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
    ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
    ->where('kupac', $id)
    ->groupBy('kup_art.sifra')
    ->get();
return response()->json($articles);
 }
</code>```

Title: Laraver DB Query

Body:
I am new in Laravel, and I don't know what is happening here. I made a simple join query with two tables, but I get the triple result. I tried with distinct(), orderBy()(getting an error)... Can someone tell me what is happening here

Laravel Query:

    public function getArtForCom($id) {
    $articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id', 'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
        ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
        ->where('kupac', $id)
        ->get();
    return response()->json($articles);
}

and result is:

[
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "130.000",
    "price": "3.590"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "485.000",
    "price": ".790"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI",
    "count": "266.000",
    "price": "3.050"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "7204.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "3.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "17.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": ".000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "69.000",
    "price": ".490"
  },
  {
    "id": 1,
    "article_id": "000140",
    "article_name": "KECAP BF",
    "group_id": "04",
    "group_name": "KECEPI  ",
    "count": "2.000",
    "price": "3.215"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "48.000",
    "price": ".490"
  },
  {
    "id": 2,
    "article_id": "000407",
    "article_name": "SWISS ROLS",
    "group_id": "13",
    "group_name": "INDUSTRIJSKI ROLAT",
    "count": "30.000",
    "price": ".488"
  }
]

Body:
You need to groupBy common key here, kup_art.sifra

  public function getArtForCom($id) {
$articles = Article::select('kup_art.rbr as id', 'kup_art.sifra as article_id',
   'kup_art.naziv as article_name', 'kup_art.grupa as group_id', 'kup_art.grupa_naziv as
   group_name', 'ro_stanje.koli as count',  'ro_stanje.v_cije as price')
    ->join('ro_stanje', 'kup_art.sifra', 'ro_stanje.sifra')
    ->where('kupac', $id)
    ->groupBy('kup_art.sifra')
    ->get();
return response()->json($articles);
 }


问:
How can we use SDA or SCL lines for I2C Addresses?
TMP102 chip( http://www.ti.com/lit/ds/symlink/tmp102.pdf ) can have multiple I2c slave addresses. It has an address pin called ADD0(Section 5) which can be used to select multiple addresses(Section 7.3.4). The logic level at that pin can be used to select a particular TMP102 slave device. According to table 4, 4 addresses are possible. I do understand that connecting the pin to high or low voltage will produce two different addresses. But the table mentions that we can use SDA and SCL pins for two different addresses. I am not sure how this works. Can anyone explain how can this be used and how can we use multiple TMP102 devices based on SDA and SCL pins.

答:
The logic level at that pin can be used to select a particular TMP102 slave device

That is not the purpose of ADD0 - it is a configuration pin, not a select pin. It is not used to select the device; I2C addresses are part of the data stream on SDA, there is no "select" pin as there is on SPI for example.

Rather, ADD0 is used to define the address of each device to one of four defined in Table 4. Those addresses being one of 0x48, 0x49, 0x4A or 0x4B depending on connection of ADD0 to GND, V+, SDA or SDL respectively.  Like so:

How the device determines the address is not revealed in the datasheet and you don't really need to know, but given:

Public domain image by Marcin Floryan from https://en.wikipedia.org/wiki/I%C2%B2C

at the start condition at the falling edge of SDA the following occurs:

```<code>ADDR ADD0 SDA SCL
0x48   0   v   1
0x49   1   v   1
0x4A   v   v   1
0x4B   1   v   1
</code>```

Then on the next falling edge SCL

```<code>ADDR ADD0 SDA SCL
0x48   0   0   v
0x49   1   0   v
0x4A   0   0   v
0x4B   v   0   v
</code>```

So it is possible with suitable sequential logic to latch the address by the end of the S phase and before B1 which is sufficient because the address match does not occur until B7, and all devices on the bus must listen for the address.

Body:
The logic level at that pin can be used to select a particular TMP102 slave device

That is not the purpose of ADD0 - it is a configuration pin, not a select pin. It is not used to select the device; I2C addresses are part of the data stream on SDA, there is no "select" pin as there is on SPI for example.

Rather, ADD0 is used to define the address of each device to one of four defined in Table 4. Those addresses being one of 0x48, 0x49, 0x4A or 0x4B depending on connection of ADD0 to GND, V+, SDA or SDL respectively.  Like so:

How the device determines the address is not revealed in the datasheet and you don't really need to know, but given:

Public domain image by Marcin Floryan from https://en.wikipedia.org/wiki/I%C2%B2C

at the start condition at the falling edge of SDA the following occurs:

ADDR ADD0 SDA SCL
0x48   0   v   1
0x49   1   v   1
0x4A   v   v   1
0x4B   1   v   1

Then on the next falling edge SCL

ADDR ADD0 SDA SCL
0x48   0   0   v
0x49   1   0   v
0x4A   0   0   v
0x4B   v   0   v

So it is possible with suitable sequential logic to latch the address by the end of the S phase and before B1 which is sufficient because the address match does not occur until B7, and all devices on the bus must listen for the address.


问:
python exchangelib how to get email within specific date range?
I tried to use exchangelib to extract group mailbox for analysis, and i want to extract within a date range.
 tried to use Filter function but seems only work for calender, may I have your advise is there any sample for email ?
thanks all.

答:
```<code>pytz_tz = pytz.timezone('Europe/Copenhagen') #setting the timezone

py_dt = pytz_tz.localize(datetime(year,month,day)) #building the custom date filter with a timezone object

ews_bfr = EWSDateTime.from_datetime(py_dt) #converting the custom date timezone object to a EWS (Exchange Web Service) date object

for item in account.inbox.all().order_by('-datetime_received')[:10000]: #look into the inbox the first 10K emails order desc by date received
    if item.datetime_received < ews_bfr: #if the mail if older than the custom date in the EWS format then apply rule
        item.delete() #delete all filtered emails
        print("Mail deleted Successfully")
</code>```


问:
How to store the result set of a stored procedure into a table, where the result set from SP is in json path?
I have a stored procedure, where i need to pass the variables with it.

The result set i get is in json path from the above sp.

Now, i want to open the json and stored the result into a table.

i want the syntax for the above?????

In sql server.

答:
You will need to create a table to match the resultant data from the SPROC.

Then you can insert the results of your SPROC into that table.

```<code>INSERT INTO Your_Table EXECUTE Your_Stored_Proceedure;
</code>```

Body:
You will need to create a table to match the resultant data from the SPROC.

Then you can insert the results of your SPROC into that table.

INSERT INTO Your_Table EXECUTE Your_Stored_Proceedure;


问:
Why does it get same value?? and how to attach currency sign after result?
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
                <br>
                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >
            </label><br><br>

</div>
</div>

<p>value: <span id="demo"></span></p></code>```

答:
Your condition
Problem giving. Try as below

```<code><b>Choose Convert : </b><br><br>
            <select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all"
                style="width: 200px; height:30px;">
                <option id="Euro1" value="Euro1">Euro (EUR)</option>
                <option id="Us1" value="Us1">US Dollar (USD)</option>
                <option id="Uk1" value="Uk1">UK Pound Sterling (GBP)</option>
                <option id="Ja1" value="Ja1">Japanese Yen (JPY)</option>
                <option id="Ca1" value="Ca1">Canadian Dollor (CAD)</option>
            </select>
            <br>

            <label>
                <br>
                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >
            </label><br><br>

        </div>
    </div>
</code>```

js

```<code>    function changeCurrency() {

    var currencySelect = document.getElementById("CurrencyID").value;

    var inputVal = parseFloat(document.getElementById("inputMoney").value);
    var currencyVal = parseFloat(document.getElementById("inputMoney"));

    if (document.getElementById("Euro")) {

        if (currencySelect == "Us1") {

            currencyVal = (inputVal * 1.08);

        } else if (currencySelect == "Uk1") {

            currencyVal = (inputVal * 0.83);

        } else if (currencySelect == "Ja1") {

            currencyVal = (inputVal * 118.88);

        } else if (currencySelect == "Ca1") {

            currencyVal = (inputVal * 1.43);
        }

}
</code>```

Body:
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>

                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >

value:

Body:
Your condition
Problem giving. Try as below

<b>Choose Convert : </b><br><br>
            <select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all"
                style="width: 200px; height:30px;">
                <option id="Euro1" value="Euro1">Euro (EUR)</option>
                <option id="Us1" value="Us1">US Dollar (USD)</option>
                <option id="Uk1" value="Uk1">UK Pound Sterling (GBP)</option>
                <option id="Ja1" value="Ja1">Japanese Yen (JPY)</option>
                <option id="Ca1" value="Ca1">Canadian Dollor (CAD)</option>
            </select>
            <br>

            <label>
                <br>
                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >
            </label><br><br>

        </div>
    </div>

js

    function changeCurrency() {

    var currencySelect = document.getElementById("CurrencyID").value;

    var inputVal = parseFloat(document.getElementById("inputMoney").value);
    var currencyVal = parseFloat(document.getElementById("inputMoney"));

    if (document.getElementById("Euro")) {

        if (currencySelect == "Us1") {

            currencyVal = (inputVal * 1.08);

        } else if (currencySelect == "Uk1") {

            currencyVal = (inputVal * 0.83);

        } else if (currencySelect == "Ja1") {

            currencyVal = (inputVal * 118.88);

        } else if (currencySelect == "Ca1") {

            currencyVal = (inputVal * 1.43);
        }

}


问:
Spring Data JPA to return List of Dates with a specified range (Start Date && End Date)
Currently, I am trying to return a list of Objects with a Date that falls into a range that is given by parameters... However, when I run my rest api call, nothing is returned. I am not sure if I am doing this Spring JPA request correctly and decided to get some feedback whether or not something I did is incorrect.

Here's some brief pseudocode:

Object Model

```<code>public class mResult{
/* other variables */
LocalDate runDate;
}
</code>```

Repo

```<code>public interface mResultRepository extends CrudRepository<mResult,String> {
    List<mResult> findAllByRunDateBetween(LocalDate startDate,LocalDate endDate);
}
</code>```

Service

```<code>mResultRepository mRepository;

public List<mResult> getAllBetweenDates(LocalDate startDate, LocalDate endDate){
     return mRepository.findAllByRunDateBetween(startDate,endDate);
 }

</code>```

My repo contains JSON objects for example:

```<code>{"runDate": "2019-02-05"}
{"runDate": "2019-02-06"}
{"runDate": "2019-02-10}
</code>```

If my range is 2019-02-01 to 2019-02-09, then it should only return those in this range. However, when I run my API request, nothing is returned. Is my Spring JPA request correct? TIA

答:
I had the same issue some time back I try/find to get the solution from the database level, but I didn't find any appropriate way to solve at DB level, So I would prefer it solve it from Java side as a sample code given below.

```<code>List<LocalDate> runningDates = Stream.iterate(startDate, date -> date.plusDays(1))
            .limit(ChronoUnit.DAYS.between(startDate, endDate.plusDays(1)))
            .collect(Collectors.toList());
</code>```

I believe that it helps you.

Body:
Currently, I am trying to return a list of Objects with a Date that falls into a range that is given by parameters... However, when I run my rest api call, nothing is returned. I am not sure if I am doing this Spring JPA request correctly and decided to get some feedback whether or not something I did is incorrect.

Here's some brief pseudocode:

Object Model

public class mResult{
/* other variables */
LocalDate runDate;
}

Repo

public interface mResultRepository extends CrudRepository<mResult,String> {
    List<mResult> findAllByRunDateBetween(LocalDate startDate,LocalDate endDate);
}

Service

mResultRepository mRepository;

public List<mResult> getAllBetweenDates(LocalDate startDate, LocalDate endDate){
     return mRepository.findAllByRunDateBetween(startDate,endDate);
 }

My repo contains JSON objects for example:

{"runDate": "2019-02-05"}
{"runDate": "2019-02-06"}
{"runDate": "2019-02-10}

If my range is 2019-02-01 to 2019-02-09, then it should only return those in this range. However, when I run my API request, nothing is returned. Is my Spring JPA request correct? TIA

Body:
I had the same issue some time back I try/find to get the solution from the database level, but I didn't find any appropriate way to solve at DB level, So I would prefer it solve it from Java side as a sample code given below.

List<LocalDate> runningDates = Stream.iterate(startDate, date -> date.plusDays(1))
            .limit(ChronoUnit.DAYS.between(startDate, endDate.plusDays(1)))
            .collect(Collectors.toList());

I believe that it helps you.


问:
java.lang.NullPointerException on spring boot
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.</p>

```<code>package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}
</code>```

答:
You must not mix usage of new with Autowired.

Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.

Soulution No.1

use AUTOWIRE

```<code>@Autowired
public MorningService ms;

@Autowired
public NightService ns;

@Autowired
GenerateMessage gm;

@RequestMapping(path = "/test")
public String starter(){
//        GenerateMessage gm=new GenerateMessage();
    ns.mesage(); // this call working fine

    gm.mes();
    return "Mail scheduled.";
}
</code>```

Solution No.2

use this keyword

```<code>@RequestMapping(path = "/test")
public String starter(){
//        GenerateMessage gm=new GenerateMessage();
    ns.mesage(); // this call working fine

    this.mes();
    return "Mail scheduled.";
}
</code>```

Body:
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.

package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Body:
You must not mix usage of new with Autowired.

Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.

Soulution No.1

use AUTOWIRE

@Autowired
public MorningService ms;

@Autowired
public NightService ns;

@Autowired
GenerateMessage gm;

@RequestMapping(path = "/test")
public String starter(){
//        GenerateMessage gm=new GenerateMessage();
    ns.mesage(); // this call working fine

    gm.mes();
    return "Mail scheduled.";
}

Solution No.2

use this keyword

@RequestMapping(path = "/test")
public String starter(){
//        GenerateMessage gm=new GenerateMessage();
    ns.mesage(); // this call working fine

    this.mes();
    return "Mail scheduled.";
}


问:
row number increases by specific conditions in more fast way R
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

```<code>
df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}
</code>```

Body:
The data frame I have looked like this.

"rank" variable has to be increased once the differences between the [i]th row of "start" and the [i-1]th row of "end" are over 14.(also, when encountered the different "ID")

I tried the code below and it worked very well.

But the thing is.. it is way too slow because I have like over 700000 rows.

 So, is there any way to make it perform much faster?

df$rank <- 1

for(i in 2:nrow(l50.df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"])&
                                   (df[i-1,"diff"]<=14),
                         df[i,"rank"] <- df[i-1,"rank"],
                         df[i,"rank"] <- df[i-1,"rank"] + 1)
}

Body:
You can use cumsum to get an increasing rank when the conditions df[i,"ID"]==df[i-1,"ID"]) & (df[i-1,"diff"]<=14) are meet.

df$rank <- cumsum(c(1,(df$ID != c(df$ID[-1], NA) | df$diff>14)[-nrow(df)]))
df
#   ID diff rank
#1   a    4    1
#2   a    6    1
#3   a    8    1
#4   a  870    1
#5   a   34    2
#6   a   NA    3
#7   b    4    4
#8   b    6    4
#9   b    8    4
#10  b  870    4
#11  b   34    5
#12  b   NA    6

Using your code:

df$rank <- 1
for(i in 2:nrow(df)){
  df[i,"rank"] <- ifelse((df[i,"ID"]==df[i-1,"ID"]) & (df[i-1,"diff"]<=14),
    df[i,"rank"] <- df[i-1,"rank"], df[i,"rank"] <- df[i-1,"rank"] + 1)
}
df
#   ID diff rank
#1   a    4    1
#2   a    6    1
#3   a    8    1
#4   a  870    1
#5   a   34    2
#6   a   NA    3
#7   b    4    4
#8   b    6    4
#9   b    8    4
#10  b  870    4
#11  b   34    5
#12  b   NA    6

Data:

df  <- data.frame(ID=rep(c("a","b"), each=6), diff=c(4,6,8,870,34,NA)
                  , stringsAsFactors = FALSE)
df
#   ID diff
#1   a    4
#2   a    6
#3   a    8
#4   a  870
#5   a   34
#6   a   NA
#7   b    4
#8   b    6
#9   b    8
#10  b  870
#11  b   34
#12  b   NA


问:
How to separate regex values?
the user makes a selection and I want to test if the selection is valid. So e.g.

```<code> preg_match("/(test1/test2|test3)/", $value)
</code>```

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

```<code>test1/test2,
test3
</code>```

答:
Why not make use of an in_array function: </p>

```<code>$array = array('test1/test2' 'test3');

if (in_array($value, $array))
{
    //do something
}
</code>```

Title: How to separate regex values?

Body:
the user makes a selection and I want to test if the selection is valid. So e.g.

 preg_match("/(test1/test2|test3)/", $value)

The problem is that one value is test1/test2, but each test is treated as a single value.  Any idea how to change that to have test1/test2 as a single value?

Eg:

test1/test2,
test3

Body:
Why not make use of an in_array function:

$array = array('test1/test2' 'test3');

if (in_array($value, $array))
{
    //do something
}


问:
Cannot complie xquery : err:XPST0003 the ':=' notation is no longer accepted in map expression
I'm trying eXist-db replication with ActiveMQ. When I configure for the consumer instance, it needs to execute a XQuery like this to register JMS receiver:

```<code>xquery version "3.0";
import module namespace replication="http://exist-db.org/xquery/replication" at "java:org.exist.jms.xquery.ReplicationModule";
let $jmsConfiguration := map {
    "java.naming.factory.initial"
            := "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" := "tcp://localhost:61616",
    "connection-factory" := "ConnectionFactory",
    "destination" := "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" := "SubscriptionId",
    "connection.client-id" := "ClientId"
}

return
    replication:register($jmsConfiguration)
</code>```

When I run this query, it returns an error like the title. I'm new to XQuery, so can you help me to check it ?

答:
The notation map{ x := y, p := q } was used in an early draft of XSLT 3.0 and the notation was changed to map{ x : y, p : q } when it was adopted by XQuery. The error message suggests you are using an implementation that once supported the syntax from the draft spec, and later dropped it.

If this is actually Saxon "under the hood", then the full error message is "The ':=' notation is no longer accepted in map expressions: use ':' instead", which tells you precisely what you need to do.

Body:
I'm trying eXist-db replication with ActiveMQ. When I configure for the consumer instance, it needs to execute a XQuery like this to register JMS receiver:

xquery version "3.0";
import module namespace replication="http://exist-db.org/xquery/replication" at "java:org.exist.jms.xquery.ReplicationModule";
let $jmsConfiguration := map {
    "java.naming.factory.initial"
            := "org.apache.activemq.jndi.ActiveMQInitialContextFactory",
    "java.naming.provider.url" := "tcp://localhost:61616",
    "connection-factory" := "ConnectionFactory",
    "destination" := "dynamicTopics/eXistdb-replication-example",
    "subscriber.name" := "SubscriptionId",
    "connection.client-id" := "ClientId"
}

return
    replication:register($jmsConfiguration)

When I run this query, it returns an error like the title. I'm new to XQuery, so can you help me to check it ?


问:
I am trying to insert account but it is throwing errors
```<code>public Class Account
{
    public void createAccount(string Name, string label__c)
    {
       Account insertAccount = new Account();
       insertAccount.Name = 'ranjith';
       insertAccount.label__c= '123';
       insert insertAccount ;
    }
}
</code>```

答:
To me your problem looks like it is coming mostly from wrong syntax in your code. Here is your code with fixed syntax :

```<code>public Class Account
{
    public void createAccount(string Name, string label__c)
    {
       Account insertAccount = new Account();
       insertAccount.Name = "ranjith";
       insertAccount.label__c= "123";

       // Commented this line as this looks like a comment and should be replaced by
       // actual insert logic.

       // insert insertAccount ;
    }
}
</code>```

In C#, strings are defined with double quotes " and characters with single quotes '.

Also your code doesn't use the parameters you provide to the CreateAccount method so here is your code with the method actually using your parameters :

```<code>public Class Account
{
    public void createAccount(string Name, string label__c)
    {
       Account insertAccount = new Account();
       insertAccount.Name = Name;
       insertAccount.label__c= label__c;

       // insert insertAccount ;
    }
}
</code>```

And the last thing that you should do is read a bit about naming/coding conventions, how to write variables/methods name. It will help you a lot by making your code more readable by others. So here is your code with these conventions :

```<code>public Class Account
{
    // Method name should start with a capital letter. Parameters with a lowercase letter.
    // Also try to avoid underscore in variable names
    public void CreateAccount(string name, string labelC)
    {
       // You can use implicit naming when the type of the variable is obvious like here.
       var insertAccount = new Account();

       // Here I will assume that Name and LabelC are properties, they should start with a uppercase letter.
       insertAccount.Name = name;
       insertAccount.LabelC= labelC;

       // insert insertAccount ;
    }
}
</code>```

Again, these conventions are not mandatory, you are free to code as you want but it will improve your code a lot and you will have a lot less troubles maintaining it.

Body:
To me your problem looks like it is coming mostly from wrong syntax in your code. Here is your code with fixed syntax :

public Class Account
{
    public void createAccount(string Name, string label__c)
    {
       Account insertAccount = new Account();
       insertAccount.Name = "ranjith";
       insertAccount.label__c= "123";

       // Commented this line as this looks like a comment and should be replaced by
       // actual insert logic.

       // insert insertAccount ;
    }
}

In C#, strings are defined with double quotes " and characters with single quotes '.

Also your code doesn't use the parameters you provide to the CreateAccount method so here is your code with the method actually using your parameters :

public Class Account
{
    public void createAccount(string Name, string label__c)
    {
       Account insertAccount = new Account();
       insertAccount.Name = Name;
       insertAccount.label__c= label__c;

       // insert insertAccount ;
    }
}

And the last thing that you should do is read a bit about naming/coding conventions, how to write variables/methods name. It will help you a lot by making your code more readable by others. So here is your code with these conventions :

public Class Account
{
    // Method name should start with a capital letter. Parameters with a lowercase letter.
    // Also try to avoid underscore in variable names
    public void CreateAccount(string name, string labelC)
    {
       // You can use implicit naming when the type of the variable is obvious like here.
       var insertAccount = new Account();

       // Here I will assume that Name and LabelC are properties, they should start with a uppercase letter.
       insertAccount.Name = name;
       insertAccount.LabelC= labelC;

       // insert insertAccount ;
    }
}

Again, these conventions are not mandatory, you are free to code as you want but it will improve your code a lot and you will have a lot less troubles maintaining it.


问:
How to detect a 401 with axios and stop the console error
I am trying to use axios to call an API and return data.

I have the following code which works fine

```<code>axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response => {
    console.log(response.data)
  });
</code>```

This works fine, the API returns a 200 and data so in the console I get the data returned.

However this does not work

```<code>axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response => {
    console.log(response.data)
  });
</code>```

On the above call i get a 401 returned from the API, I want to be able to detect that and do something (where i am currently doing a console.log). However in the console I get the following errors:

```<code>GET http://api/courses 401 (Unauthorized)
(anonymous) @ spread.js:25
e.exports @ spread.js:25
e.exports @ spread.js:25
Promise.then (async)
r.request @ spread.js:25
r.(anonymous function) @ spread.js:25
(anonymous) @ index.js:20
(anonymous) @ (index):49

(index):58 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at axios.get.catch.then.response ((index):58)
at <anonymous>
</code>```

Is there a way to capture a 401? It seems like common practice by API's that require auth, but I cannot seem to work it out.
Thanks

答:
Added debugger to check the object, so this is how the error object looks like.

Refer screenshot. Right side(under scope)

Body:
I am trying to use axios to call an API and return data.

I have the following code which works fine

axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response => {
    console.log(response.data)
  });

This works fine, the API returns a 200 and data so in the console I get the data returned.

However this does not work

axios.get('http://api/courses')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.status);
    } else {
      console.log('Error', error.message);
    }
  })
  .then(response => {
    console.log(response.data)
  });

On the above call i get a 401 returned from the API, I want to be able to detect that and do something (where i am currently doing a console.log). However in the console I get the following errors:

GET http://api/courses 401 (Unauthorized)
(anonymous) @ spread.js:25
e.exports @ spread.js:25
e.exports @ spread.js:25
Promise.then (async)
r.request @ spread.js:25
r.(anonymous function) @ spread.js:25
(anonymous) @ index.js:20
(anonymous) @ (index):49

(index):58 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at axios.get.catch.then.response ((index):58)
at <anonymous>

Is there a way to capture a 401? It seems like common practice by API's that require auth, but I cannot seem to work it out.
Thanks


问:
Getting wrong data from database even if I am fetching something different in laravel api
Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.

Here is my model code

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';

}
</code>```

Here is my Controller Code

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\user;

class GetController extends Controller
{
    public function databybusinessid($business _id){
    $users = new user();
    $users = user::find($business _id);
    return response()->json($users);
}
}
</code>```

Thank you so much

答:
find() Retrieve a model by its primary key..

So you have to use your code as:

```<code>$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
</code>```

Or you can change your primary code in model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';
    protected $primaryKey = 'business_id';

}
</code>```

Body:
Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.

Here is my model code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';

}

Here is my Controller Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\user;

class GetController extends Controller
{
    public function databybusinessid($business _id){
    $users = new user();
    $users = user::find($business _id);
    return response()->json($users);
}
}

Thank you so much

Body:
find() Retrieve a model by its primary key..

So you have to use your code as:

$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...

Or you can change your primary code in model

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    protected $table = 'business';
    protected $primaryKey = 'business_id';

}


问:
RemoteObject in BlazeDS environment: Serializing objects from JAXB/XJC-generated classes
I'm developing a webapp with Java backend and Flash (pure ActionScript) frontend using BlazeDS.

I'm using the RemoteObject stuff to send objects, using custom serialization, where I need to implement Externalizable (Java) and IExternalizable (AS) interfaces. This works fine so far.

But now I need to send objects from Java to Flash, whose classes are generated with JAXB/XJC. Of course these generated Java classes don't implement the Externalizable interface, so it seems that I can't use my approach here.

One possibility seems to be writing a XJC plugin which makes the classes implement Externalizable. But this looks like a tough job...

Does anyone have a good idea how to solve this problem?

答:
I finally developed a JAXB/XJC plugin. (If someone's interested, just contact me.)
Works fine now.</p>


答:
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.

protected $primaryKey = 'business_id';
```

<pre class="lang-php prettyprint-override"><code>public function databybusinessid($business _id){
    $users = new user();
    $users = user::where('business_id',$business _id)->first();
    return response()->json($users);
}
</code>```

Title: Getting wrong data from database even if I am fetching something different in laravel api

Body:
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.

protected $primaryKey = 'business_id';

public function databybusinessid($business _id){
    $users = new user();
    $users = user::where('business_id',$business _id)->first();
    return response()->json($users);
}


问:
Can I use Vuejs Material Dashboard template on Nuxtjs App?
As a beginner I am trying to use a  free template of  Vuejs version of the Original Material Dashboard template on existing Nuxtjs project. Can I do that?</p>

答: It's a messy way to do thing. Just create a new Nuxt project, then copy paste the things you need to keep from your vuejs folder (components for example, do not copy paste everything of course)</p>


问:
Resolution problem in C# .NET Winform application
I have developed my winform application without caring about the resolution. Now am stuck up on PCs with a lower resolution. What to do now? Is there any way of conversion? I mean can the application get the resolution of the PC on which it is running, and set itself accordingly? Is there not any code or variable of Resolution in Windows which can be used ?</p>

答:
There are a lot of solutions for the problem given but most are based around the fact that you can build them into you're application from the start.

Simply manually changing the layout of you're application might be the 'fastest' way to go.

Getting 10 users to use a higher resolution might cost 10 * 100 dollar changing the application might costs 40 hours depending on application size.


问:
JSON- Array in MongoDB with Spring Data
I have the following JSON-Object in a Mongo database:

```<code>{ "elem1": { "elem2": ["elem3": {"elem4", "elem5"}, "elem6"] }}
</code>```

I want to check, if elem4 equals to 22. I'm writing this query with Spring Data. Now I wrote the following query, but it doesn't work for me:

```<code>Query query = new Query(Criteria.where("elem1.elem2").elemMatch(Criteria.where("elem3.elem4").is("22")));
</code>```

Does anyone know why my query doesn't work?

Thanks in advance.

答:
Your json is not valid. Please change it if you want it like this.</p>

```<code>{
    "elem1": {
        "elem2": "22"
    },
    "elem3": {
        "elem4": "22",
        "elem5": "33"
    }

}
</code>```

Title: JSON- Array in MongoDB with Spring Data

Body:
I have the following JSON-Object in a Mongo database:

{ "elem1": { "elem2": ["elem3": {"elem4", "elem5"}, "elem6"] }}

I want to check, if elem4 equals to 22. I'm writing this query with Spring Data. Now I wrote the following query, but it doesn't work for me:

Query query = new Query(Criteria.where("elem1.elem2").elemMatch(Criteria.where("elem3.elem4").is("22")));

Does anyone know why my query doesn't work?

Thanks in advance.

Body:
Your json is not valid. Please change it if you want it like this.

{
    "elem1": {
        "elem2": "22"
    },
    "elem3": {
        "elem4": "22",
        "elem5": "33"
    }

}


问:
C# Rest API File upload
I am trying too upload a file with C# by an API.

The StreamUtils dont work, I am getting error: "Cannot convert lambda expression to type 'string' because it is not a delegate type".

Any idea on how to upload the file?
It is around 100MB.

```<code> public void UploadModel(string ProjectId, string filename, Stream fileStream)
        {

            string access_token_string = Read_Json_Values("access_token");
            string webstring = String.Format("https://api.test.com/v2/projects/{0}/revisions", ProjectId);

            var client = new RestClient(webstring);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + access_token_string);
            request.AddHeader("Content-Type", "application/ifc");
            request.AddHeader("xxx-Params", "{\"callbackUri\": \"https://example.com\", \"filename\": \"mk337.ifc\", \"comment\": \"From Postman\", \"model\": \"21312312312312\"}");
            request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

            IRestResponse response = client.Execute(request);
            Console.WriteLine("Model is uploaded!");
        }
</code>```

```<code>internal static class StreamUtils
        {
            private const int STREAM_BUFFER_SIZE = 128 * 1024; // 128KB

            public static void CopyStream(Stream source, Stream target)
            { CopyStream(source, target, new byte[STREAM_BUFFER_SIZE]); }

            public static void CopyStream(Stream source, Stream target, byte[] buffer)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (target == null) throw new ArgumentNullException("target");

                if (buffer == null) buffer = new byte[STREAM_BUFFER_SIZE];
                int bufferLength = buffer.Length;
                int bytesRead = 0;
                while ((bytesRead = source.Read(buffer, 0, bufferLength)) > 0)
                    target.Write(buffer, 0, bytesRead);
            }
</code>```

答:
So you have two issues in your code
...

1. Lambda expression issue

The following line causes the lambda expression issue

```<code>request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

// This is the function you want to call
void CopyStream(Stream source, Stream target)
</code>```

So the issue is, that

```<code>s => StreamUtils.CopyStream(fileStream, s)
</code>```

is a Lambda expression, where you define s and give s as second Parameter to

```<code>CopyStream(Stream source, Stream target)
</code>```

but s is not of type Stream. That's why you get the exception.

2. request.AddFile needs Parameters

Assuming you use the RestSharp NuGet package for your REST request (I assume that because the classes look like the once from RestSharp) you should have a look on the different overloads of RestRequest.AddFile():

```<code>AddFile(string name, string path, string contentType = null);
AddFile(string name, byte[] bytes, string fileName, string contentType = null);
AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);
</code>```

All functions need several parameters. I guess you want to use the second definition which is

```<code>AddFile(string name, byte[] bytes, string fileName, string contentType = null);
</code>```

So if we compare it with the line in your code

```<code>request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);
</code>```

We see that you give following Parameters:

"file" as the name

Function call (Lambda expression) for the bytes

Filename variable for the filename

The first and third parameters look good but second parameter is an issue.

My suggestions:

Define a secound stream parameter in your  UploadModel and pass it to the CopyStream function:

```<code>public void UploadModel(string ProjectId, string filename, Stream sourceStream, Stream targetStream)
{
    // .... your code still here, just want to show the changing lines
    request.AddFile("file", StreamUtils.CopyStream(sourceStream, targetStream), filename);
}
</code>```

And if you still want to call StreamUtils.CopyStream() to get the second parameter for request.AddFile, you have to change the function definition as it currently returns void. So instead of:

```<code>public static void CopyStream(Stream source, Stream target)
public static void CopyStream(Stream source, Stream target, byte[] buffer)
</code>```

you have to change it to

```<code>public static byte[] CopyStream(Stream source, Stream target)
public static byte[] CopyStream(Stream source, Stream target, byte[] buffer)
</code>```

which leads us to the changes in the function body itself, as we now have to return a byte[] accordingly to the functions definition (this is just an example and still needs to get the real implementation which I am currently not able to do, just hope that it gives you an impression how to do it):

```<code>public static byte[] CopyStream(Stream source, Stream target, byte[] buffer)
{
    // -> Define a byte array
    byte[] bytesToReturn;

    // -> Fill the array with data
    // ...

    // -> return the array
    return bytesToReturn;
}
</code>```

With these changes it should work.

Title: C# Rest API File upload

Body:
I am trying too upload a file with C# by an API.

The StreamUtils dont work, I am getting error: "Cannot convert lambda expression to type 'string' because it is not a delegate type".

Any idea on how to upload the file?
It is around 100MB.

 public void UploadModel(string ProjectId, string filename, Stream fileStream)
        {

            string access_token_string = Read_Json_Values("access_token");
            string webstring = String.Format("https://api.test.com/v2/projects/{0}/revisions", ProjectId);

            var client = new RestClient(webstring);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + access_token_string);
            request.AddHeader("Content-Type", "application/ifc");
            request.AddHeader("xxx-Params", "{\"callbackUri\": \"https://example.com\", \"filename\": \"mk337.ifc\", \"comment\": \"From Postman\", \"model\": \"21312312312312\"}");
            request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

            IRestResponse response = client.Execute(request);
            Console.WriteLine("Model is uploaded!");
        }

internal static class StreamUtils
        {
            private const int STREAM_BUFFER_SIZE = 128 * 1024; // 128KB

            public static void CopyStream(Stream source, Stream target)
            { CopyStream(source, target, new byte[STREAM_BUFFER_SIZE]); }

            public static void CopyStream(Stream source, Stream target, byte[] buffer)
            {
                if (source == null) throw new ArgumentNullException("source");
                if (target == null) throw new ArgumentNullException("target");

                if (buffer == null) buffer = new byte[STREAM_BUFFER_SIZE];
                int bufferLength = buffer.Length;
                int bytesRead = 0;
                while ((bytesRead = source.Read(buffer, 0, bufferLength)) > 0)
                    target.Write(buffer, 0, bytesRead);
            }

Body:
So you have two issues in your code
...

1. Lambda expression issue

The following line causes the lambda expression issue

request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

// This is the function you want to call
void CopyStream(Stream source, Stream target)

So the issue is, that

s => StreamUtils.CopyStream(fileStream, s)

is a Lambda expression, where you define s and give s as second Parameter to

CopyStream(Stream source, Stream target)

but s is not of type Stream. That's why you get the exception.

2. request.AddFile needs Parameters

Assuming you use the RestSharp NuGet package for your REST request (I assume that because the classes look like the once from RestSharp) you should have a look on the different overloads of RestRequest.AddFile():

AddFile(string name, string path, string contentType = null);
AddFile(string name, byte[] bytes, string fileName, string contentType = null);
AddFile(string name, Action<Stream> writer, string fileName, long contentLength, string contentType = null);

All functions need several parameters. I guess you want to use the second definition which is

AddFile(string name, byte[] bytes, string fileName, string contentType = null);

So if we compare it with the line in your code

request.AddFile("file", s => StreamUtils.CopyStream(fileStream, s), filename);

We see that you give following Parameters:

"file" as the name

Function call (Lambda expression) for the bytes

Filename variable for the filename

The first and third parameters look good but second parameter is an issue.

My suggestions:

Define a secound stream parameter in your  UploadModel and pass it to the CopyStream function:

public void UploadModel(string ProjectId, string filename, Stream sourceStream, Stream targetStream)
{
    // .... your code still here, just want to show the changing lines
    request.AddFile("file", StreamUtils.CopyStream(sourceStream, targetStream), filename);
}

And if you still want to call StreamUtils.CopyStream() to get the second parameter for request.AddFile, you have to change the function definition as it currently returns void. So instead of:

public static void CopyStream(Stream source, Stream target)
public static void CopyStream(Stream source, Stream target, byte[] buffer)

you have to change it to

public static byte[] CopyStream(Stream source, Stream target)
public static byte[] CopyStream(Stream source, Stream target, byte[] buffer)

which leads us to the changes in the function body itself, as we now have to return a byte[] accordingly to the functions definition (this is just an example and still needs to get the real implementation which I am currently not able to do, just hope that it gives you an impression how to do it):

public static byte[] CopyStream(Stream source, Stream target, byte[] buffer)
{
    // -> Define a byte array
    byte[] bytesToReturn;

    // -> Fill the array with data
    // ...

    // -> return the array
    return bytesToReturn;
}

With these changes it should work.


问:
What, and why, does GNU gettext send over the public internet?
I was trying out gettext and ran msginit --locale=en --input=messages.po and this is what I see:

```<code>[... blah ...]
Is the following your email address?
  localUserName@localHostName
Please confirm by pressing Return, or enter your email address.

Retrieving http://translationproject.org/team/index.html... done.
A translation team for your language (en) does not exist yet.
If you want to create a new translation team for en or en_PG, please visit
  http://www.iro.umontreal.ca/contrib/po/HTML/teams.html
  http://www.iro.umontreal.ca/contrib/po/HTML/leaders.html
  http://www.iro.umontreal.ca/contrib/po/HTML/index.html

Created en_PG.po.
</code>```

What was or would have been disclosed? What is the purpose of this disclosure?

```<code>$ msginit --version
msginit (GNU gettext-tools) 0.19.8.1
</code>```

答:
You don't need wireshark for tracing here. A text editor will do:

The tool msginit invokes a shell script <prefix>/share/gettext/projects/TP/team-address that tries to download (via <prefix>/lib/gettext/urlget) the table with translation teams from http://translationproject.org/team/index.html, and it falls back to a local copy installed under <prefix>/share/gettext/projects/TP/teams.html.  The purpose of this is to fill the PO header Language-Team with an up-to-date email address.

I agree that the user should at least be prompted before an internet connection is opened.

I have opened an upstream issues for that:

https://savannah.gnu.org/bugs/index.php?57847

In versions before 0.20, the program (it is the above-mentioned script team-address) always reports that a "translation team for your language (xy) does not exist yet", no matter what locale you specify. This is fixed in gettext version 0.20.1.

Thanks for pointing this out!

As a workaround, you may edit the shell script team-address to not invoke urlget but use the local copy directly.

Body:
I was trying out gettext and ran msginit --locale=en --input=messages.po and this is what I see:

[... blah ...]
Is the following your email address?
  localUserName@localHostName
Please confirm by pressing Return, or enter your email address.

Retrieving http://translationproject.org/team/index.html... done.
A translation team for your language (en) does not exist yet.
If you want to create a new translation team for en or en_PG, please visit
  http://www.iro.umontreal.ca/contrib/po/HTML/teams.html
  http://www.iro.umontreal.ca/contrib/po/HTML/leaders.html
  http://www.iro.umontreal.ca/contrib/po/HTML/index.html

Created en_PG.po.

What was or would have been disclosed? What is the purpose of this disclosure?

$ msginit --version
msginit (GNU gettext-tools) 0.19.8.1


问:
error at javascript that connect to sql, asp.net c#
I have javascript timer countdown with the code:

```<code><script language="JavaScript">
TargetDate = "<% = TargetDate %>";
/*this is a property in code behind*/BackColor = "palegreen";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "the auction end"
</script>
<script language="JavaScript" src="countdown.js"></script>
</script>
</code>```

the code behind:

```<code>public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}
</code>```

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)

答:
Your method supposed to return string. It doesn't.

public string TargetDate

There is no return.

Use ExecuteScalar, instead of ExecuteReader.

Return the string value.

Body:
I have javascript timer countdown with the code:

</script>

the code behind:

public string TargetDate ()
{

    DataTable dataTable = new DataTable();
    using (SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True"))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from endTime";
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        dataTable.Load(reader); }
}

i get the error:
't.TargetDate()': not all code paths return value.

when i tried to write return i got another error... what means that i dont know what to do :)