问:
Submit HTML forms that contain dynamic IDs
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

```<code> <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">
    <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...
            <div class="row" style="margin-bottom: 5%;">
                <div class="col-xl-2 col-lg-3 col-md-3">
                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
                </div>
            </div>
     </form>
</code>```

Form with ID="surveyImage18"

```<code><form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">
      <div class="row">
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

            </div>
        </div>

    <div class="row" style="margin-bottom: 5%;">
        <div class="col-xl-2 col-lg-3 col-md-3">
             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
        </div>
    </div>
</form>
</code>```

AJAX call

```<code><script type="text/javascript">
 $("#surveyImage13").validate({
                    rules: {
                         'responses[]': {
                            required:true
                        }
                    },
                     // change name of error class that is assigned to input fields
    errorClass: 'error_validate',

    errorPlacement: function (label, element) {

        // default
        if (element.is(':radio')) {
            label.insertAfter(element.parent('.form-check-inline'));
        }
        else {
            label.insertAfter(element);
        }
    }

     });
</script>

<script type="text/javascript">

     $("#surveyImage13").submit(function(e) {
        e.preventDefault();

        var route=$('#surveyImage13').attr('action');
        var pivot_id = $("#questionnaire_pivot_id").val();

        // Get values of checked checkboxes
        var responses = $('.form-check-inline input').filter(':checked').map(function() {
          return this.value;
        }).get();

     var isFormValid = $("#surveyImage13").valid();

    if(isFormValid){

        $.ajax({
          type: "POST",
          url: route,
          data: {'responses': responses, 'pivot_id': pivot_id},
          success: function(response){

            $("#surveyImageForm").css("display", "none");
            $("#surveyImageAjax").css("display", "block");

            $('#SurveyTableAjaxColumn1').append(response[1]);
            $('#SurveyTableAjaxColumn2').append(response[0]);
          },
          error: function(){
            console.log('Error');
          }
        })
        }
     });

</script>
</code>```

答:
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id</p>

```<code>   $(".btn").click(function(e) {
    e.preventDefault();

    var formId = '#'+ $(this).parents('form').attr('id');

    var route=$(formId).attr('action');
    var pivot_id = $("#questionnaire_pivot_id").val();

    // Get values of checked checkboxes
    var responses = $('.form-check-inline input').filter(':checked').map(function() {
      return this.value;
    }).get();

    var isFormValid = $(formId).valid();

    if(isFormValid){

    $.ajax({
      type: "POST",
      url: route,
      data: {'responses': responses, 'pivot_id': pivot_id},
      success: function(response){

        $("#surveyImageForm").css("display", "none");
        $("#surveyImageAjax").css("display", "block");

        $('#SurveyTableAjaxColumn1').append(response[1]);
        $('#SurveyTableAjaxColumn2').append(response[0]);
      },
      error: function(){
        console.log('Error');
      }
    })
  }
});
</code>```

Body:
I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with id="surveyImage13"

 <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...

                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

     </form>

Form with ID="surveyImage18"

<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate">

            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>

</form>

AJAX call

Body:
1.Instead of submit event use button click event
2.Get form id and store it
3.use this variable where you need id

   $(".btn").click(function(e) {
    e.preventDefault();

    var formId = '#'+ $(this).parents('form').attr('id');

    var route=$(formId).attr('action');
    var pivot_id = $("#questionnaire_pivot_id").val();

    // Get values of checked checkboxes
    var responses = $('.form-check-inline input').filter(':checked').map(function() {
      return this.value;
    }).get();

    var isFormValid = $(formId).valid();

    if(isFormValid){

    $.ajax({
      type: "POST",
      url: route,
      data: {'responses': responses, 'pivot_id': pivot_id},
      success: function(response){

        $("#surveyImageForm").css("display", "none");
        $("#surveyImageAjax").css("display", "block");

        $('#SurveyTableAjaxColumn1').append(response[1]);
        $('#SurveyTableAjaxColumn2').append(response[0]);
      },
      error: function(){
        console.log('Error');
      }
    })
  }
});


来源: stackexchange

问:
Test to verify primitive local variables are thread safe
I had written below code to increase version count

```<code>if ("Solution".equalsIgnoreCase(modelName)) {
    mainsolution.setSolutionVersion(oldsolution.getSolutionVersion() + 1);}
</code>```

i doubt above piece of code mayn't give proper result in multithreaded environment so to test this below test code i had written

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {

            service.execute(new NotThreadsafe());
        }

        ExecutorService service1 = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {

            service1.execute(new Threadsafe());
        }

    }

}

class NotThreadsafe implements Runnable{
    int x = 1;
    public int incrementX() {
        x++;
        return x;
    }

    @Override
    public void run() {
        System.out.println("not safe:"+incrementX());
    }
}

class Threadsafe implements Runnable{
    public int getTwoTimesTwo() {
        int x = 1;
        x++;
        return x;
    }

    @Override
    public void run() {
        System.out.println("safe:"+getTwoTimesTwo());
    }
}
</code>```

but i got 2 as output for both Threadsafe and NotThreadsafe.

Is something wrong i have written to test above post.

答:
You simply cannot write a test to demonstrate the thread safety of a primitive local variable.

The only way a local variable can be shared with another thread is if you reference it in an anonymous class.

However, by doing this the local variable is required either to be final or effectively final, so it cannot be updated either in the "original" thread, or the anonymous class.

Therefore, all threads will see the up-to-date value of that variable. There is never a thread safety issue. The compiler guarantees it.

ContentLicense: CC BY-SA 4.0

Body:
I had written below code to increase version count

if ("Solution".equalsIgnoreCase(modelName)) {
    mainsolution.setSolutionVersion(oldsolution.getSolutionVersion() + 1);}

i doubt above piece of code mayn't give proper result in multithreaded environment so to test this below test code i had written

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {

    public static void main(String[] args) {

        ExecutorService service = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {

            service.execute(new NotThreadsafe());
        }

        ExecutorService service1 = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {

            service1.execute(new Threadsafe());
        }

    }

}

class NotThreadsafe implements Runnable{
    int x = 1;
    public int incrementX() {
        x++;
        return x;
    }

    @Override
    public void run() {
        System.out.println("not safe:"+incrementX());
    }
}

class Threadsafe implements Runnable{
    public int getTwoTimesTwo() {
        int x = 1;
        x++;
        return x;
    }

    @Override
    public void run() {
        System.out.println("safe:"+getTwoTimesTwo());
    }
}

but i got 2 as output for both Threadsafe and NotThreadsafe.

Is something wrong i have written to test above post.


问:
Extracting text/number from tspan class tag HTML with R
I am trying to extract Current Production number from this website http://okg.se/sv/Produktionsinformation/ (in the blue area below).

Here is the HTML code part I need to use:

```<code><tspan dy="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">518</tspan>
</code>```

The example of the code I used:

```<code>url <- "http://okg.se/sv/Produktionsinformation//"
download.file(url, destfile = "scrapedpage.html", quiet=TRUE)
content <- read_html("scrapedpage.html")
content %>% html_nodes(".content__info__item__value")
</code>```

But the result I get shows that there is not nodes available:

```<code>{xml_nodeset (0)}
</code>```

Do you have any ides on how to solve this issue?

Thanks in advance!

答:
The html you see with your browser has been processed by javascript, so isn't the same as the html you see with rvest.

The raw data you are looking for is actually stored in attributes of a div with the id "gauge", so you get it like this:

library(rvest)
#> Loading required package: xml2

"http://okg.se/sv/Produktionsinformation//" %>%
read_html()                                 %>%
html_node("#gauge")                         %>%
html_attrs()                                %>%
`[`(c("data-current", "data-max"))
#> data-current     data-max
#>        "553"       "1450"
```

Note that you don't need to save the html to your local drive to process it. You can read it directly from the internet by giving the url to read_html

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I am trying to extract Current Production number from this website http://okg.se/sv/Produktionsinformation/ (in the blue area below).

Here is the HTML code part I need to use:

<tspan dy="0" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">518</tspan>

The example of the code I used:

url <- "http://okg.se/sv/Produktionsinformation//"
download.file(url, destfile = "scrapedpage.html", quiet=TRUE)
content <- read_html("scrapedpage.html")
content %>% html_nodes(".content__info__item__value")

But the result I get shows that there is not nodes available:

{xml_nodeset (0)}

Do you have any ides on how to solve this issue?

Thanks in advance!

Body:
The html you see with your browser has been processed by javascript, so isn't the same as the html you see with rvest.

The raw data you are looking for is actually stored in attributes of a div with the id "gauge", so you get it like this:

library(rvest)
#> Loading required package: xml2

"http://okg.se/sv/Produktionsinformation//" %>%
read_html()                                 %>%
html_node("#gauge")                         %>%
html_attrs()                                %>%
`[`(c("data-current", "data-max"))
#> data-current     data-max
#>        "553"       "1450"

Note that you don't need to save the html to your local drive to process it. You can read it directly from the internet by giving the url to read_html

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
C# WinForms using FlashLight built-in into mobile device running Windows 10 Professional x64
I've created a WinForms (C#) application and I have to add support for the built-in flash. The device is Tablet PC running x64 architecture Windows 10 Professional (common Windows 10). Is there any way to do that? My application captures video from a built-in camera - I'm using OpenCV Sharp to do that, but I can't find any possibility to use a built-in flashlight. I need just manually turn on and off the light. I've found a lot of examples but it is possible only through UWP which I can't add to WinForms in any way.
Does anyone know the way to use the built-in flashlight in WinForms Application?</p>

答:
Windows API can be used in any non-UWP-C#-project by adding UwpDesktog NuGet Package
and adding these references:

```<code>c:\Program Files (x86)\Windows Kits\10\References\Windows.Foundation.FoundationContract\1.0.0.0\Windows.Foundation.FoundationContract.winmd
c:\Program Files (x86)\Windows Kits\10\References\Windows.Foundation.UniversalApiContract\1.0.0.0\Windows.Foundation.UniversalApiContract.winmd
c:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.WinMD
c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
</code>```

Then you can turn on flashlight using MediaCaptur from UWP.

Body:
Windows API can be used in any non-UWP-C#-project by adding UwpDesktog NuGet Package
and adding these references:

c:\Program Files (x86)\Windows Kits\10\References\Windows.Foundation.FoundationContract\1.0.0.0\Windows.Foundation.FoundationContract.winmd
c:\Program Files (x86)\Windows Kits\10\References\Windows.Foundation.UniversalApiContract\1.0.0.0\Windows.Foundation.UniversalApiContract.winmd
c:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.WinMD
c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

Then you can turn on flashlight using MediaCaptur from UWP.


问:
How to pass to the next element when the requested value is not found in a json file
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

```<code>    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass
</code>```

but it doesn't work.

Could anyone help me, please?

The script

```<code>r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)
</code>```

The Error message

```<code>---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'
</code>```

答:
Hey you used the syntax of the following Part wrong:

```<code>try:
    r = requests.get(package_url)
    package_json = r.json()
exception:
    pass
</code>```

I just ran the code in colab, it worked fine for me, just change exception to except.

```<code>import requests
import json
import time

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    except:
      pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)
</code>```

Result

```<code>Got a2ps in 0.028664 seconds
Got a52dec in 0.027885 seconds
Got aacgain in 0.028514 seconds
Got aalib in 0.026989 seconds
</code>```

And so on .. Good Luck

Body:
I am quite a beginner on Python. I am trying to extract analytics infos from homebrew packackages APIs through Request module. To do so I first dynamically get the urls for each package and then I loop over each url to get the infos I need. The script runs well until the loop stops over the "carina" package. I suppose the stopping is due to the fact the path package_json['analytics']['install']['30d'][package_name] is no longer correct in the [package_name] part (the package name in the analytics dictionary becomes "carina --HEAD").

For this time I would like the loop just pass to the next package and print an error message.

So far I tried to solve it using the following:

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

but it doesn't work.

Could anyone help me, please?

The script

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    exception:
        pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)

The Error message

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-42e0fb795383> in <module>
     16
     17
---> 18     installs_30 = package_json['analytics']['install']['30d'][package_name]
     19     installs_90 = package_json['analytics']['install']['90d'][package_name]
     20     installs_365 = package_json['analytics']['install']['365d'][package_name]

KeyError: 'carina'

Body:
Hey you used the syntax of the following Part wrong:

try:
    r = requests.get(package_url)
    package_json = r.json()
exception:
    pass

I just ran the code in colab, it worked fine for me, just change exception to except.

import requests
import json
import time

r = requests.get("https://formulae.brew.sh/api/formula.json")
packages_json = r.json()
packages_string = json.dumps(packages_json, indent=2)

results = []

t1 = time.perf_counter()

for package in packages_json:

    package_name = package["name"]
    package_desc = package["desc"]
    package_url = f'https://formulae.brew.sh/api/formula/{package_name}.json'

    try:
        r = requests.get(package_url)
        package_json = r.json()
    except:
      pass

    installs_30 = package_json['analytics']['install']['30d'][package_name]
    installs_90 = package_json['analytics']['install']['90d'][package_name]
    installs_365 = package_json['analytics']['install']['365d'][package_name]

    data = {
        "nome": package_name,
        "descrizione": package_desc,
        "analytics": {
            "30d": installs_30,
            "90d": installs_90,
            "365d": installs_365
        }
    }

    results.append(data)

    time.sleep(r.elapsed.total_seconds())

    if r.status_code != 200:
        print (f"Got error for {package_name}")
    else:
        print(f'Got {package_name} in {r.elapsed.total_seconds()} seconds')

t2 = time.perf_counter()

print(f"Finito in {t2-t1} secondi")

with open("packages_info.json", "w") as f:
    json.dump(results, f, indent=2)

Result

Got a2ps in 0.028664 seconds
Got a52dec in 0.027885 seconds
Got aacgain in 0.028514 seconds
Got aalib in 0.026989 seconds

And so on .. Good Luck


问:
Jasper hide staticText and textField don't remove the space
I created a main report and subreport with Jasper. From main report I am sending 2 parameters (Value A and Value B) to the sub report which either one can be 0. if one parameter gets 0 it needs to get hide.

I am using <printWhenExpression> and isRemoveLineWhenBlank="true" attributes to hide these elements. They are hiding properly according to the parameters, but if Value A get 0 there will be space in between KKK and Value B.

for Value B I have set the positionType="FixRelativeToTop". It can be seen in the property box but not in the source of the JRXML.
Is there any way to get rid of this white space ?

Thanks in advance.

答:
I got this sorted by making single Value B row as another sub report. Remove all print when conditions from the sub report.
Added printWhenExpression and  isRemoveLineWhenBlank attributes on the main report , sub report reportElement tag.


问:
Implementing a lambda layer within a Keras model
I'm trying to implement an external lambda function from a Keras model. But the function is called twice or the '### x' and '### x_reshape'are printed twice. How to eliminate this?</p>

```<code>def RA_reshape(x):
    print('\n### x ', x)
    x_reshape = K.reshape(x, [1, x.shape[1].value, x.shape[2].value, x.shape[3].value])
    print('\n### x_reshape ', x_reshape)
    return x_reshape

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(lambda y: RA_reshape(x=y) )
    conv1 = RA_0(conv1)
</code>```

答:
This is Keras working internally and building "the graph", it does call functions twice and there is nothing much we can do.

Notice that since it's a graph, it will not print the values as you want! It will print only the symbolic tensors.

For printing the data you need to create a little model only to predict the data you want to see. Or you need to enable eager mode and not use "predict", but manually go calling each layer with a tensor.

Body:
I'm trying to implement an external lambda function from a Keras model. But the function is called twice or the '### x' and '### x_reshape'are printed twice. How to eliminate this?

def RA_reshape(x):
    print('\n### x ', x)
    x_reshape = K.reshape(x, [1, x.shape[1].value, x.shape[2].value, x.shape[3].value])
    print('\n### x_reshape ', x_reshape)
    return x_reshape

def unet(pretrained_weights = None,input_size = None):
    inputs = Input(input_size)

    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)
    conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)

    RA_0 = Lambda(lambda y: RA_reshape(x=y) )
    conv1 = RA_0(conv1)


问:
Visual Basic connect database with ODBC setting with register
I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.

Thank you

```<code>Private Sub DsnLookup()

    Dim dsnNames As New List(Of String)
    Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")

    If reg IsNot Nothing Then
        reg = reg.OpenSubKey("ODBC")
        If reg IsNot Nothing Then
            reg = reg.OpenSubKey("ODBC.INI")
            If reg IsNot Nothing Then
                For Each dsn As String In reg.GetSubKeyNames
                    dsnNames.Add(dsn)
                Next
            End If
        End If
    End If

    For Each Name As String In dsnNames
        ComboBox1.Items.Add(Name)
    Next Name

End Sub

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DsnLookup()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
    & "User Id=root;Password=' odbc PWD"
</code>```

答:
thank you for the answer

I tried to edit it

```<code>    Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
        Dim dsnNames As New List(Of String)
        Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
        reg = reg.OpenSubKey("ODBC")
        reg = reg.OpenSubKey("ODBC.INI")
        reg = reg.OpenSubKey(ODBCName)
        Return reg.GetValue(ValueName)

        For Each dsn As String In reg.GetSubKeyNames
            dsnNames.Add(dsn)
        Next
        For Each Name As String In dsnNames
            ComboBox1.Items.Add(Name)
        Next Name

    End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

 Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
        Dim conn As New MySqlConnection(connString)
        Dim cmd As New MySqlCommand()
</code>```

Try
            Call conecDB()
            dt = New DataTable 's_table

         Dim con As New SqlConnection

```<code>        DateTimePicker1.CustomFormat = "yyyy-MM-dd"
        DateTimePicker1.Format = DateTimePickerFormat.Custom
        DateTimePicker2.CustomFormat = "yyyy-MM-dd"
        DateTimePicker2.Format = DateTimePickerFormat.Custom
        conn.Open()
        cmd.Connection = conn
 da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)

        comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
        da.Fill(dt)
        dbvypis.DataSource = dt

        conn.Close()
        MessageBox.Show("COMPLET")

    Catch ex As MySqlException
        Console.WriteLine("Error: " & ex.ToString())
    End Try

    Try
        'declaring variable as integer to store the value of the total rows in the datagridview

        Dim max As Integer = dbvypis.Rows.Count - 1
        Dim total As String = "TOTAL ----->"
        Dim TOTALCOST As Integer = 0
        'getting the values of a specific rows

        For Each row As DataGridViewRow In dbvypis.Rows
            'formula for adding the values in the rows
            TOTALCOST += row.Cells(1).Value
        Next
        dbvypis.Rows(max).Cells(1).Value += TOTALCOST
        dbvypis.Rows(max).Cells(0).Value = total

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
</code>```

It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name

Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index

Body:
I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.

Thank you

Private Sub DsnLookup()

    Dim dsnNames As New List(Of String)
    Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")

    If reg IsNot Nothing Then
        reg = reg.OpenSubKey("ODBC")
        If reg IsNot Nothing Then
            reg = reg.OpenSubKey("ODBC.INI")
            If reg IsNot Nothing Then
                For Each dsn As String In reg.GetSubKeyNames
                    dsnNames.Add(dsn)
                Next
            End If
        End If
    End If

    For Each Name As String In dsnNames
        ComboBox1.Items.Add(Name)
    Next Name

End Sub

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DsnLookup()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
    & "User Id=root;Password=' odbc PWD"

Body:
thank you for the answer

I tried to edit it

    Private Function GetODBCValu(ByVal ODBCName As String, ByVal ValueName As String) As String
        Dim dsnNames As New List(Of String)
        Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
        reg = reg.OpenSubKey("ODBC")
        reg = reg.OpenSubKey("ODBC.INI")
        reg = reg.OpenSubKey(ODBCName)
        Return reg.GetValue(ValueName)

        For Each dsn As String In reg.GetSubKeyNames
            dsnNames.Add(dsn)
        Next
        For Each Name As String In dsnNames
            ComboBox1.Items.Add(Name)
        Next Name

    End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

 Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValu(ComboBox1.SelectedItem, "Database"), GetODBCValu(ComboBox1.SelectedItem, "Server"))
        Dim conn As New MySqlConnection(connString)
        Dim cmd As New MySqlCommand()

Try
            Call conecDB()
            dt = New DataTable 's_table

         Dim con As New SqlConnection

        DateTimePicker1.CustomFormat = "yyyy-MM-dd"
        DateTimePicker1.Format = DateTimePickerFormat.Custom
        DateTimePicker2.CustomFormat = "yyyy-MM-dd"
        DateTimePicker2.Format = DateTimePickerFormat.Custom
        conn.Open()
        cmd.Connection = conn
 da = New MySql.Data.MySqlClient.MySqlDataAdapter("select --- ", connDB)

        comBuilderDB = New MySql.Data.MySqlClient.MySqlCommandBuilder(da)
        da.Fill(dt)
        dbvypis.DataSource = dt

        conn.Close()
        MessageBox.Show("COMPLET")

    Catch ex As MySqlException
        Console.WriteLine("Error: " & ex.ToString())
    End Try

    Try
        'declaring variable as integer to store the value of the total rows in the datagridview

        Dim max As Integer = dbvypis.Rows.Count - 1
        Dim total As String = "TOTAL ----->"
        Dim TOTALCOST As Integer = 0
        'getting the values of a specific rows

        For Each row As DataGridViewRow In dbvypis.Rows
            'formula for adding the values in the rows
            TOTALCOST += row.Cells(1).Value
        Next
        dbvypis.Rows(max).Cells(1).Value += TOTALCOST
        dbvypis.Rows(max).Cells(0).Value = total

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

It occurred to me that if I select a database in the comboboxu so it gets into ODBC and connString to the command adds the server and database name

Then it writes to me in the result Index is out of range, Index must be non-negative and must be smaller than the collection size. Parameter name: index


问:
The fastest minimum spanning tree algorithm
http://en.wikipedia.org/wiki/Minimum_spanning_tree

I'm looking to benchmark my minimum spanning tree algorithm against the best of the best.
Does someone know where I can find a C++ implementation of these algorithms? I binged and googled the and didn't find anything. If these algorithms are the best, surely there must be a C++ implementation somewhere?

The fastest minimum spanning tree
  algorithm to date was developed by
  David Karger, Philip Klein, and Robert
  Tarjan, who found a linear time
  randomized algorithm based on a
  combination of Borůvka's algorithm and
  the reverse-delete algorithm.[2][3]
  The fastest non-randomized algorithm,
  by Bernard Chazelle, is based on the
  soft heap, an approximate priority
  queue.[4][5] Its running time is O(m
  α(m,n)), where m is the number of
  edges, n is the number of vertices and
  α is the classical functional inverse
  of the Ackermann function. The
  function α grows extremely slowly, so
  that for all practical purposes it may
  be considered a constant no greater
  than 4; thus Chazelle's algorithm
  takes very close to linear time. If
  the edge weights are integers with a
  bounded bit length, then deterministic
  algorithms are known with linear
  running time.[6] Whether there exists
  a deterministic algorithm with linear
  running time for general weights is
  still an open question. However, Seth
  Petie and Vijaya Ramachandran have
  found a provably optimal deterministic
  minimum spanning tree algorithm, the
  computational complexity of which is
  unknown.[7]

I already test against Boost C++'s graph algorithms.

答:
"On Sorting, Heaps, and Minimum Spanning Trees",
Gonzalo Navarro and Rodrigo Paredes

presents some "best of the best" in-core and external
memory measurements, and gives references to older
implementations.

They report # of I/Os and CPU time as a function of
graph size, and describe their test cases well, so
in principle you could do the tests and compare with
their published graphs.  You might use their Prim2
reference (code from Peter Sanders, who makes many
of his fast codes freely available) to calibrate
your own measurements.

ContentLicense: CC BY-SA 2.5


问:
Asking for user input between 2 genders using a while loop and to be stored in a variable?
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

```<code>gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)
</code>```

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)

答:
```<code>x=gender.lower()
if x="male":
    print "U re Male"
else if x="famale":
    print "U re Famale"
else:
    print "You enter Wrong gender"
</code>```

Body:
Want to create a small program that can ask a user a question. Do you want your character to be Male or Female? And output the result. However as you can tell the results are poor from my side.

Can someone give me a hand in fixing this mess as I feel I have over complicated it.

Just some general rules that the program must have:

It must accept both "Male" and "male" as input and vice versa for
female

The user input must be stored in the variable created.

If the user types anything else that is not: 'female' 'Female' 'male' or 'Male' they must try the question again (which is why I put in a while loop)

It's strange but this should be simple for me normally but I've made a bit of a mess of it.

Any help would be appreciated :)

gender = None

gender = str(input("Enter your Gender1: "))
while gender != 'Male' or 'male' or 'female' or 'Female':
    gender = input("Enter your Gender2: ")
if gender in ['Male', 'male']:
    print("You have chosen Male")
if gender in ['Female', 'female']:
    print("You have chosen Female")

print(gender)

I don't mind the whole method changing where options can be used such as:

Press 1 for 'Male' or 2 for 'Female'

Would be of a help :)


问:
Has anyone successfully used react-testing-library to test change events on a draftJS Editor component?
The fireEvent.change() just doesn't work.

It says there are no setters on the element.

I tried using aria selectors instead

```<code>const DraftEditor = getByRole('textbox')
DraftEditor.value ='something';
fireEvent.change(DraftEditor);
</code>```

I tried same again using query selector

```<code>const DraftEditor = container.querySelector('.public-DraftEditor-content'));
</code>```

Tried keyboard events instead.

Nothing.

Has anyone managed to text a rich text input with draftjs and react testing library?

答:
I managed to get it working mocking the editor and intercepting the onChange method so you can still execute all the lib functions:

```<code>const draftjs = require('draft-js');

draftjs.Editor = jest.fn(props => {
  const modifiedOnchange = e => {
    const text = e.target.value;
    const content = ContentState.createFromText(text);
    props.onChange(EditorState.createWithContent(content));
  };
  return <input className="editor" onChange={e => modifiedOnchange(e)} />;
});
</code>```

Body:
The fireEvent.change() just doesn't work.

It says there are no setters on the element.

I tried using aria selectors instead

const DraftEditor = getByRole('textbox')
DraftEditor.value ='something';
fireEvent.change(DraftEditor);

I tried same again using query selector

const DraftEditor = container.querySelector('.public-DraftEditor-content'));

Tried keyboard events instead.

Nothing.

Has anyone managed to text a rich text input with draftjs and react testing library?

Body:
I managed to get it working mocking the editor and intercepting the onChange method so you can still execute all the lib functions:

const draftjs = require('draft-js');

draftjs.Editor = jest.fn(props => {
  const modifiedOnchange = e => {
    const text = e.target.value;
    const content = ContentState.createFromText(text);
    props.onChange(EditorState.createWithContent(content));
  };
  return <input className="editor" onChange={e => modifiedOnchange(e)} />;
});


问:
How to sum numbers considered as strings?
I have a column in my dataset like this:

```<code>col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1
</code>```

I am trying to sum each row in a new column like this output:

```<code>col2
1
4
2
5
1
</code>```

I have tried doing:

```<code>rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion
</code>```

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

```<code>structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

</code>```

答:
Using stringr:

```<code>library(stringr)

# assumes we are only summing integers, ignores decimals
sapply(str_extract_all(df$col1, "[0-9]+"), function(x) sum(as.integer(x)))
[1] 1 4 2 5 1

# Assumes we are only looking for the integer 1
str_count(df$col1, "1")
[1] 1 4 2 5 1
</code>```

Body:
I have a column in my dataset like this:

col1
1
1, 1, 1, 1
1, 1
1, 1, 1, 1, 1
1

I am trying to sum each row in a new column like this output:

col2
1
4
2
5
1

I have tried doing:

rowSums(as.numeric(as.character(df$col1)))
Error in rowSums(as.numeric(as.character(df$col1))) :
  'x' must be an array of at least two dimensions
In addition: Warning message:
In is.data.frame(x) : NAs introduced by coercion

I am new to R and likely missing something obvious, but I can't find any similar problems online also in R to adapt to my data, any help or advice on what functions to use would be appreciated.

Data:

structure(list(col1 = c("1", "1, 1, 1, 1", "1, 1", "1, 1, 1, 1, 1", "1"),
row.names = c(NA, -5L), class = "data.frame")

Body:
Using stringr:

library(stringr)

# assumes we are only summing integers, ignores decimals
sapply(str_extract_all(df$col1, "[0-9]+"), function(x) sum(as.integer(x)))
[1] 1 4 2 5 1

# Assumes we are only looking for the integer 1
str_count(df$col1, "1")
[1] 1 4 2 5 1


问:
V-for is not iterating through objects
I have an array of coupon objects named offers:

```<code> [{ "coupon":
             { "id": "1", "name": "Coupon 1" }
  },
  { "coupon":
             { "id": "2", "name": "Coupon 2" }
  }]
</code>```

And i try to iterate trough it like this:

```<code><div v-for="(coupon, $index) in offers" :key="$index">
     <p>{{coupon.id}}</p>
</div>
</code>```

The problem is that div does not iterate anything.

答:
```<code><div v-for="{ coupon } in offers" :key="coupon.id">
   <p>{{ coupon.name }}</p>
</div>
</code>```

<p>Dont use index as key </p>

Title: V-for is not iterating through objects

Body:
I have an array of coupon objects named offers:

 [{ "coupon":
             { "id": "1", "name": "Coupon 1" }
  },
  { "coupon":
             { "id": "2", "name": "Coupon 2" }
  }]

And i try to iterate trough it like this:

{{coupon.id}}

The problem is that div does not iterate anything.

Body:
<div v-for="{ coupon } in offers" :key="coupon.id">
   <p>{{ coupon.name }}</p>
</div>

Dont use index as key


问:
Flash frame-rate is different in browser than it is in flash player
I am using Flash CS4 and when testing my application my frame rate changes as it is programmed to do so. When I try to run the application in a browser (tried Firefox 4, Opera 10.5 and IE 8) the frame rate does not change.

Why does the frame-rate not change? How do I fix it?

答:
Set your HTML so that the Flash Object's wmode is "opaque" (or transparent if you really need to). If you don't specify it, it will interpret it as some other default parameter which gives you that drop in frame-rate performance.

Sample:

```<code><object type="application/x-shockwave-flash" data=
 "YourFlashMovie.swf" width="640" height="480"
 id="flash_id_1" style="visibility: visible;">
  <param name="allowScriptAccess" value="always" />
  <param name="allowScale" value="never" />
  <param name="allowFullScreen" value="true" />
  <param name="wmode" value="opaque" /> <!-- THIS IS WHAT YOU MUST SET -->
  <param name="quality" value="high" />
  <param name="scale" value="" />
  <param name="scaleMode" value="" />
  <param name="menu" value="false" />
</object>
</code>```

Hope that helps.

ContentLicense: CC BY-SA 3.0

Body:
Set your HTML so that the Flash Object's wmode is "opaque" (or transparent if you really need to). If you don't specify it, it will interpret it as some other default parameter which gives you that drop in frame-rate performance.

Sample:

<object type="application/x-shockwave-flash" data=
 "YourFlashMovie.swf" width="640" height="480"
 id="flash_id_1" style="visibility: visible;">
  <param name="allowScriptAccess" value="always" />
  <param name="allowScale" value="never" />
  <param name="allowFullScreen" value="true" />
  <param name="wmode" value="opaque" /> <!-- THIS IS WHAT YOU MUST SET -->
  <param name="quality" value="high" />
  <param name="scale" value="" />
  <param name="scaleMode" value="" />
  <param name="menu" value="false" />
</object>

Hope that helps.


问:
Oracle Select max where a certain key is matched
i'm working with oracle, plSql, i need to query a table and select the max id where a key is matched, now i have this query

```<code>select t.* from (
select  distinct (TO_CHAR(I.DATE, 'YYMMDD') || I.AUTH_CODE || I.AMOUNT || I.CARD_NUMBER)  as kies, I.SID as ids
from transactions I) t group by kies, ids order by ids desc;
</code>```

It's displaying this data

If i remove the ID from the query, it displays the distinct keys (in the query i use the alias KIES because keys was in blue, so i thought it might be a reserved word)

How can i display the max id (last one inserted) for every different key without displaying all the data like in the first image??

greetings.

答:
Since you haven't provided data in text format, its difficult to type such long numbers and recreated the data.

However I think you can simply use the MAX analytical function to achieve your results.

```<code>with data as (
select 1111 keys,1 id from dual
union
select 2222, 1 from dual
union
select 1111, 2 from dual
union
select 2222,3 from dual
union
select 9999, 1 from dual
union
select 1111, 5 from dual
)
select distinct keys, max(id) over( partition by (keys)) from data
</code>```

This query returns -

```<code>KEYS    MAX(ID)OVER(PARTITIONBY(KEYS))
1111    5
9999    1
2222    3
</code>```

Body:
i'm working with oracle, plSql, i need to query a table and select the max id where a key is matched, now i have this query

select t.* from (
select  distinct (TO_CHAR(I.DATE, 'YYMMDD') || I.AUTH_CODE || I.AMOUNT || I.CARD_NUMBER)  as kies, I.SID as ids
from transactions I) t group by kies, ids order by ids desc;

It's displaying this data

If i remove the ID from the query, it displays the distinct keys (in the query i use the alias KIES because keys was in blue, so i thought it might be a reserved word)

How can i display the max id (last one inserted) for every different key without displaying all the data like in the first image??

greetings.

Body:
Since you haven't provided data in text format, its difficult to type such long numbers and recreated the data.

However I think you can simply use the MAX analytical function to achieve your results.

with data as (
select 1111 keys,1 id from dual
union
select 2222, 1 from dual
union
select 1111, 2 from dual
union
select 2222,3 from dual
union
select 9999, 1 from dual
union
select 1111, 5 from dual
)
select distinct keys, max(id) over( partition by (keys)) from data

This query returns -

KEYS    MAX(ID)OVER(PARTITIONBY(KEYS))
1111    5
9999    1
2222    3


问:
Auto check Create account field in Woocommerce Checkout Page
I am using woocommerce for a wordpress site and I would like for users to create an account during the checkout process when entering in payment details. Normally there is checkbox option that users must physically click to make an account.

Is there some implementation that can have this "create an account" box pre-checked and all users have to do is create a password.

(http://imgur.com/lANhCfn)

(http://imgur.com/qyfs4fy)

答:
Woocommerce--> settings --> account and privacy

Your account should have settings like this.
no need for development


问:
Expanding a Map<String,String> to Map<String,Map> based on the key
If I have a map like:

```<code>Map.of("key1", "value1",
       "key2.subkey1", "subvalue1",
       "key2.subkey2", "subvalue2",
       "key2.subkey3.subsubkey", "subsubvalue");
</code>```

Then I would like to convert it to a map of (possibly) maps like this:

```<code>Map.of("key1", "value1",
       "key2", Map.of("subkey1", "subvalue1",
                      "subkey2", "subvalue2",
                      "subkey3", Map.of("subsubkey", "subsubvalue)));
</code>```

I figure I need to split the keys like so:

```<code>entry.getKey().split("\\.", 2);
</code>```

But I cant figure out what to do after that.

答:
I have managed to make this method which does what I want, but it doesn't look very pretty :(

```<code>private Map<String, Object> expandMap(Map<String, String> oldMap) {
    HashMap<String, Object> newMap = new HashMap<>();
    oldMap.forEach((key, value) -> {
        String[] keys = key.split("\\.", 2);
        if (keys.length == 1) {
            newMap.put(keys[0], value);
        } else {
            newMap.merge(keys[0], expandMap(Map.of(keys[1], value)), (obj1, obj2) -> {
                if (obj1 instanceof Map && obj2 instanceof Map) {
                    Map<String, Object> map1 = (Map<String, Object>) obj1;
                    Map<String, Object> map2 = (Map<String, Object>) obj2;
                    return Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(toMap(Entry::getKey, Entry::getValue));
                }
                return null;
            });
        }
    });
    return newMap;
}
</code>```

You are welcome to share your thoughts.

Body:
If I have a map like:

Map.of("key1", "value1",
       "key2.subkey1", "subvalue1",
       "key2.subkey2", "subvalue2",
       "key2.subkey3.subsubkey", "subsubvalue");

Then I would like to convert it to a map of (possibly) maps like this:

Map.of("key1", "value1",
       "key2", Map.of("subkey1", "subvalue1",
                      "subkey2", "subvalue2",
                      "subkey3", Map.of("subsubkey", "subsubvalue)));

I figure I need to split the keys like so:

entry.getKey().split("\\.", 2);

But I cant figure out what to do after that.

Body:
I have managed to make this method which does what I want, but it doesn't look very pretty :(

private Map<String, Object> expandMap(Map<String, String> oldMap) {
    HashMap<String, Object> newMap = new HashMap<>();
    oldMap.forEach((key, value) -> {
        String[] keys = key.split("\\.", 2);
        if (keys.length == 1) {
            newMap.put(keys[0], value);
        } else {
            newMap.merge(keys[0], expandMap(Map.of(keys[1], value)), (obj1, obj2) -> {
                if (obj1 instanceof Map && obj2 instanceof Map) {
                    Map<String, Object> map1 = (Map<String, Object>) obj1;
                    Map<String, Object> map2 = (Map<String, Object>) obj2;
                    return Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(toMap(Entry::getKey, Entry::getValue));
                }
                return null;
            });
        }
    });
    return newMap;
}

You are welcome to share your thoughts.


问:
Passing JS array as a List<> to Spring MVC controller
I'm developing the front end to my webapp using ReactJs. Here, I make an API POST passing in a array of objects.

The objects are created in an event handler, as follows:

```<code>eventHandler(id1, id2, e) {
    let payload = this.state.payload;
    let changedItem= {
        changeTo: e,
        id1: id1,
        id2: id2
    };

    let res = [];
    payload.forEach(item=> {
        if (item.id1 !== id1
            || item.id2 !== id2) {
            res.push(control);
        }
    });
    res.push(changedItem);

    this.setState({
        payload: res
    });
}
</code>```

I have verified this works by printing the array after this. Next, I make a POST call, passing in the array:

```<code>onClick() {

    let changedControls = (this.state.payload);

    updateControls(changedControls).then(() => {
        this.setState({
            payload: []
        });
    }).catch((error) => {
         console.log(error);
    })
}
</code>```

The API call is defined in a separate file, as:

```<code>export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => {
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})
</code>```

};

Ideally, the next step would have been my Java controller being called, defined as:

```<code>@RequestMapping(value = "/update-controls", method = RequestMethod.POST)
public void updateControls(@RequestParam(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {
    initServiceClientRest();
    String user = getUserId();

    ResponseEntity responseEntity = serviceClientRest.update(updatedControls, user);

    if (responseEntity != null) {
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throwErrorMessages(responseEntity);
        }
    }
}
</code>```

I believe this is where the error lies. I get a 400 error, saying: Required List parameter 'updatedControls' is not present'.

Any suggestions?

EDIT: Sorry about the typo in the API POST call! But that wasn't the issue, just a typo I made while copying in the code

EDIT2:

Error:

```<code>feign.FeignException$InternalServerError: status 500 reading serviceClientRest#updateAccessControls(List,String)
at feign.FeignException.errorStatus(FeignException.java:114) ~[feign-core-10.2.3.jar:na]
at feign.FeignException.errorStatus(FeignException.java:86) ~[feign-core-10.2.3.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:93) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:149) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:78) ~[feign-core-10.2.3.jar:na]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-10.2.3.jar:na]
at com.sun.proxy.$Proxy155.updateAccessControls(Unknown Source) ~[na:na]
at ScoringConfigController.updateControls(ScoringConfigController.java:135) ~[main/:na]
</code>```

答:
```<code>axios.post(uri, changedControls).then(response => {
</code>```

instead of

```<code>axios.post(uri, updatedControls).then(response => {
</code>```

Body:
I'm developing the front end to my webapp using ReactJs. Here, I make an API POST passing in a array of objects.

The objects are created in an event handler, as follows:

eventHandler(id1, id2, e) {
    let payload = this.state.payload;
    let changedItem= {
        changeTo: e,
        id1: id1,
        id2: id2
    };

    let res = [];
    payload.forEach(item=> {
        if (item.id1 !== id1
            || item.id2 !== id2) {
            res.push(control);
        }
    });
    res.push(changedItem);

    this.setState({
        payload: res
    });
}

I have verified this works by printing the array after this. Next, I make a POST call, passing in the array:

onClick() {

    let changedControls = (this.state.payload);

    updateControls(changedControls).then(() => {
        this.setState({
            payload: []
        });
    }).catch((error) => {
         console.log(error);
    })
}

The API call is defined in a separate file, as:

export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => {
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})

};

Ideally, the next step would have been my Java controller being called, defined as:

@RequestMapping(value = "/update-controls", method = RequestMethod.POST)
public void updateControls(@RequestParam(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {
    initServiceClientRest();
    String user = getUserId();

    ResponseEntity responseEntity = serviceClientRest.update(updatedControls, user);

    if (responseEntity != null) {
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throwErrorMessages(responseEntity);
        }
    }
}

I believe this is where the error lies. I get a 400 error, saying: Required List parameter 'updatedControls' is not present'.

Any suggestions?

EDIT: Sorry about the typo in the API POST call! But that wasn't the issue, just a typo I made while copying in the code

EDIT2:

Error:

feign.FeignException$InternalServerError: status 500 reading serviceClientRest#updateAccessControls(List,String)
at feign.FeignException.errorStatus(FeignException.java:114) ~[feign-core-10.2.3.jar:na]
at feign.FeignException.errorStatus(FeignException.java:86) ~[feign-core-10.2.3.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:93) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:149) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:78) ~[feign-core-10.2.3.jar:na]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-10.2.3.jar:na]
at com.sun.proxy.$Proxy155.updateAccessControls(Unknown Source) ~[na:na]
at ScoringConfigController.updateControls(ScoringConfigController.java:135) ~[main/:na]

Body:
axios.post(uri, changedControls).then(response => {

instead of

axios.post(uri, updatedControls).then(response => {


问:
I recently took interest in python using python3.8 and I' writing code to store user data and then verify it
I'm writing a code in python3.8 to ask user its Name, email, password and phone and storing then in different .txt file and now i have to verify it . Please help me write this program . I added a path in program. Now i need it to check if program has any pre-stored data like name,email,password and phone.And my working directory also have my program file. When I'm running it just getting to directly 2nd part where it's asking me for authentication. How should i define my program so that path does not include my program and checkpoints but only .txt files.

```<code>import os
path = 'C:\\Users\\User\\Downloads\\Class Work\\Project Python\\files'
dir = os.listdir(path)
# Here is the problem
if len(dir)==0:
    with open ('name.txt','w') as Name:
        Name.write(str(input("Name: ")))
    with open('mobile.txt','w') as Mob:
        Mob.write(str(input("Mobile No.: ")))
    with open('email.txt','w') as email:
        email.write(str(input("Email ID: ")))
    with open('password.txt','w') as password:
        password.write(input("password: "))
else: # Authentication
    a= str(input("Enter email ID: "))
    b=input("Enter Password: ")
    with open('email.txt','r') as email:
        x = email.read()
    with open('password.txt','r') as password:
        y= password.read()
    if x==a and y==b:
        with open('password.txt','w') as password:
            password.write(input("New Password  "))
    else:
        c = input("Enter Email ID: ")
        d = input("Enter Phone: ")
        with open('email.txt','r') as email:
            s = email.read()
        with open("mobile.txt",'r') as mobile:
            t = mobile.read()
        if c==s and d==t:
            with open('password.txt','r') as password:
                p = password.read()
            print(p)

</code>```

enter image description here

答:
I guess you want just to see how python syntax works... I made a script similar to yours just with less stuff because extending it once you get how this works it's trivial.</p>

```<code>#Here I declare a writing function:
#it accepts input from the user
#and save it into a file
def write(label,filename):
    text = input(label)
    f = open(filename,'w')
    f.write(text)
    f.close()

#This is a checking function:
#you insert name and password
#it reads the respective files
#if the input are the same of the
#stored one then the test it returns 1
#otherwise a 0
def check(filename1,filename2):
    name = input('Insert your name: ')
    pas = input('Insert your password: ')
    f1 = open(filename1,'r')
    f2 = open(filename2,'r')
    stored_name = f1.read()
    stored_pass = f2.read()
    f1.close()
    f2.close()
    if stored_name == name and stored_pass == pas:
        return 1
    return 0

#Creating and saving the files
namefile = 'Name.dat'
passfile = 'Password.dat'
write('Insert your name: ',namefile)
write('Insert your password: ',passfile)

#Reading and checking
recovery = check(namefile,passfile)
if recovery == 1:
    print ('everything correct')
else:
    print ('wrong ID or pass')
</code>```

Body:
I'm writing a code in python3.8 to ask user its Name, email, password and phone and storing then in different .txt file and now i have to verify it . Please help me write this program . I added a path in program. Now i need it to check if program has any pre-stored data like name,email,password and phone.And my working directory also have my program file. When I'm running it just getting to directly 2nd part where it's asking me for authentication. How should i define my program so that path does not include my program and checkpoints but only .txt files.

import os
path = 'C:\\Users\\User\\Downloads\\Class Work\\Project Python\\files'
dir = os.listdir(path)
# Here is the problem
if len(dir)==0:
    with open ('name.txt','w') as Name:
        Name.write(str(input("Name: ")))
    with open('mobile.txt','w') as Mob:
        Mob.write(str(input("Mobile No.: ")))
    with open('email.txt','w') as email:
        email.write(str(input("Email ID: ")))
    with open('password.txt','w') as password:
        password.write(input("password: "))
else: # Authentication
    a= str(input("Enter email ID: "))
    b=input("Enter Password: ")
    with open('email.txt','r') as email:
        x = email.read()
    with open('password.txt','r') as password:
        y= password.read()
    if x==a and y==b:
        with open('password.txt','w') as password:
            password.write(input("New Password  "))
    else:
        c = input("Enter Email ID: ")
        d = input("Enter Phone: ")
        with open('email.txt','r') as email:
            s = email.read()
        with open("mobile.txt",'r') as mobile:
            t = mobile.read()
        if c==s and d==t:
            with open('password.txt','r') as password:
                p = password.read()
            print(p)

enter image description here

Body:
I guess you want just to see how python syntax works... I made a script similar to yours just with less stuff because extending it once you get how this works it's trivial.

#Here I declare a writing function:
#it accepts input from the user
#and save it into a file
def write(label,filename):
    text = input(label)
    f = open(filename,'w')
    f.write(text)
    f.close()

#This is a checking function:
#you insert name and password
#it reads the respective files
#if the input are the same of the
#stored one then the test it returns 1
#otherwise a 0
def check(filename1,filename2):
    name = input('Insert your name: ')
    pas = input('Insert your password: ')
    f1 = open(filename1,'r')
    f2 = open(filename2,'r')
    stored_name = f1.read()
    stored_pass = f2.read()
    f1.close()
    f2.close()
    if stored_name == name and stored_pass == pas:
        return 1
    return 0

#Creating and saving the files
namefile = 'Name.dat'
passfile = 'Password.dat'
write('Insert your name: ',namefile)
write('Insert your password: ',passfile)

#Reading and checking
recovery = check(namefile,passfile)
if recovery == 1:
    print ('everything correct')
else:
    print ('wrong ID or pass')


问:
Configure Eclipse workspace automatically
I have a eclipse workspace which constitutes of 15 different java projects . To configure the eclipse workspace , every time I need to add the java projects manually and add the dependency and refrences in the java build path.
Adding all the  projects and resolving dependency every time becomes a manual and redundant task. I explored on the .classpath inside the every projects which stores the dependency and refrences information.
I would like to automate this redundant process.
Have any one tried doing that , any inputs will be helpful.

I don't need to add same project more than once , but often need to create a new eclipse workspace with new code changes and delivery (I can't take some of the changes in the current work space).In simple terms for e.g if some one need to create eclipse workspace again and again , or multiple people need to create the same workspace for their work . How can we reduce that manual effort?

答:
If you're checking out the projects from CVS / SVN in Eclipse, then it's possible to create a Team Project Set. This is essentially an XML file that will contain a list of projects and their source repository path

It can be exported via File | Export | Team | Team Project Set, and imported into another workspace via File | Import | Team | Team Project Set

There's more information on this feature at this link on Javalobby


问:
Switching from Msmq to RabbitMQ on MassTransit 2.10
I am moving a old app from Msmq to RabbitMQ. The App uses MassTransit 2.10 and I need a function that returns the number of messages in queue for a specific message type.

In the current implementation there is this line of code that returns the message types:

```<code>var messages = MsmqEndpointManagement.New(endpoint.Address).MessageTypes();
</code>```

Is it possible to replace this instruction with something similar when using RabbitMQ ?

答:
When moving to RabbitMQ, the management of queues is different. Since it's a broker (compared to MSMQ, which is a, well, different), it was designed with a separate management API and console. There are other libraries that can be used to get message counts, but not one that will get you the message types (since it would require reading every message to find the type - which is what that MSMQ method above is doing, btw).

I'd suggest looking at HareDu to manage your broker from the application/API.

Body:
I am moving a old app from Msmq to RabbitMQ. The App uses MassTransit 2.10 and I need a function that returns the number of messages in queue for a specific message type.

In the current implementation there is this line of code that returns the message types:

var messages = MsmqEndpointManagement.New(endpoint.Address).MessageTypes();

Is it possible to replace this instruction with something similar when using RabbitMQ ?


问:
how to change permissions for all text channels with discord.py?
I'm trying to make a command to change the permissions on all text channels
but it does not work

```<code>@bot.command()
async def close_all(ctx):
  overwrite = discord.PermissionOverwrite()
  overwrite.send_messages = False
  overwrite.read_messages = False
  ctx.get_channel = ctx.message.server
  await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
</code>```

i also tried to put guild but it say AttributeError: 'Guild' object has no attribute 'channel'

```<code>@bot.command()
async def close_all(ctx):
  await ctx.guild.channel.set_permissions(ctx.guild.default_role, send_messages=False)
</code>```

答:
Guild has no attribute channel, but it does have channels which is a list of all channels in the guild that you can loop through:

```<code>for chan in guild.channels:
    await chan.set_permissions(cts.guild.default_role, send_messages=False)
</code>```

Body:
I'm trying to make a command to change the permissions on all text channels
but it does not work

@bot.command()
async def close_all(ctx):
  overwrite = discord.PermissionOverwrite()
  overwrite.send_messages = False
  overwrite.read_messages = False
  ctx.get_channel = ctx.message.server
  await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)

i also tried to put guild but it say AttributeError: 'Guild' object has no attribute 'channel'

@bot.command()
async def close_all(ctx):
  await ctx.guild.channel.set_permissions(ctx.guild.default_role, send_messages=False)

Body:
Guild has no attribute channel, but it does have channels which is a list of all channels in the guild that you can loop through:

for chan in guild.channels:
    await chan.set_permissions(cts.guild.default_role, send_messages=False)


问:
Aggregate data and plot in a bar plot in R
i have a data set with parameter_variations and a score. This score has four scales: like, anth, comf and ueq.</p>

答:
The bargraph.CI function accepts raw data, not aggregated data. So try the following:

```<code>bargraph.CI(parameter_variants, response=score, group=scale, data=dat,
            main="likeability", legend=TRUE)
</code>```

This should give you one "two-way" plot. If you don't like the look of it, there are many arguments that make superficial adjustments. Check the help page for details.

To obtain separate plots for each of the four scales, I think you can do something like this:

```<code>library(dplyr)
    dat %>%
    filter(scale=="like") %>%  # change the value here.
    bargraph.CI(parameter_variants, response=score, data=., main="likeability")
</code>```

Base R solution:

```<code>with(subset(dat, subset=scale=="like"),
        bargraph.CI(parameter_variants, response=score, main="likeability")
)
</code>```

Body:
The bargraph.CI function accepts raw data, not aggregated data. So try the following:

bargraph.CI(parameter_variants, response=score, group=scale, data=dat,
            main="likeability", legend=TRUE)

This should give you one "two-way" plot. If you don't like the look of it, there are many arguments that make superficial adjustments. Check the help page for details.

To obtain separate plots for each of the four scales, I think you can do something like this:

library(dplyr)
    dat %>%
    filter(scale=="like") %>%  # change the value here.
    bargraph.CI(parameter_variants, response=score, data=., main="likeability")

Base R solution:

with(subset(dat, subset=scale=="like"),
        bargraph.CI(parameter_variants, response=score, main="likeability")
)


问:
Typescript can't find module on compile
I'm trying to get path resolution to work in typescript.

My folder structure so far looks like this:

src:

index.ts

types:

global.d.ts

cache.d.ts

util:

index.ts

Cache.ts

Since It's getting pretty nested I would like to be able to access for example the util folder by typing
import { Whatever } from '@util'. I've tried setting baseUrl to ./src and paths to "@util": ["util/index"] with moduleResolution set to node.

This is how my files look so far:

src/index.ts

```<code>import {Cache} from '@util'

const c = new Cache();
</code>```

src/util/index.ts

```<code>export { default as Cache } from './Cache';
</code>```

src/util/Cache.ts

```<code>export default class {
// class code goes here
}
</code>```

Now, the compiler doesn't complain while I'm coding in VS Code but when I run tsc in the command line I get an error saying that it can't find the module '@util'.

Does anyone have any ideas as to why I can't compile?

答:
what you are trying to import is a namespaced NPM package here while what you actually want to do is do a relative or absolute import i.e.:

import {Cache} from './util'

const c = new Cache();
```

For better understanding of the '@' import check this post

Title: Typescript can't find module on compile

Body:
I'm trying to get path resolution to work in typescript.

My folder structure so far looks like this:

src:

index.ts

types:

global.d.ts

cache.d.ts

util:

index.ts

Cache.ts

Since It's getting pretty nested I would like to be able to access for example the util folder by typing
import { Whatever } from '@util'. I've tried setting baseUrl to ./src and paths to "@util": ["util/index"] with moduleResolution set to node.

This is how my files look so far:

src/index.ts

import {Cache} from '@util'

const c = new Cache();

src/util/index.ts

export { default as Cache } from './Cache';

src/util/Cache.ts

export default class {
// class code goes here
}

Now, the compiler doesn't complain while I'm coding in VS Code but when I run tsc in the command line I get an error saying that it can't find the module '@util'.

Does anyone have any ideas as to why I can't compile?

Body:
what you are trying to import is a namespaced NPM package here while what you actually want to do is do a relative or absolute import i.e.:

import {Cache} from './util'

const c = new Cache();

For better understanding of the '@' import check this post


问:
AttributeError: 'Response' object has no attribute 'type'
Can anyone please help me out with this error. I am trying to save an image from query string imagle url. but got stuck with the following error.
My code below, please ignore unnecessary libraries

```<code>from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import urllib.request as urllib
import io

app = Flask(__name__)
api = Api(app)

abc = uuid.uuid4().hex[:6].upper()

class Predict(Resource):
    def get(self):
        url = request.args['url']
        r = requests.get(url)
        fd = urllib.urlopen(r)
        image_file = io.BytesIO(fd.read())
        im = Image.open(image_file)
        return im.save(abc+".png")

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)
</code>```

Output Error :

答:
To save in file you don't need Image and BytesIO() - you can use directly open() and write()

If you want to save every image with different name then you should create abc inside get()

```<code>from flask import Flask, request
from flask_restful import Resource, Api
import requests
import uuid

app = Flask(__name__)
api = Api(app)

#abc = uuid.uuid4().hex[:6].upper()  # one name for all images

class Predict(Resource):

    def get(self):
        abc = uuid.uuid4().hex[:6].upper()  # generate new name for new image
        filename = abc + '.png'
        #print(filename)

        url = request.args['url']

        r = requests.get(url)

        f = open(filename, 'wb')  # write in bytes-mode 'wb'
        f.write(r.content)
        f.close()

        return {'status': 'OK', 'name': filename}

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)
</code>```

You would need Image and BytesIO only if you would like to edit image before save.

```<code>from flask import Flask, request
from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import io

app = Flask(__name__)
api = Api(app)

#abc = uuid.uuid4().hex[:6].upper() # one name for all images

class Predict(Resource):

    def get(self):
        abc = uuid.uuid4().hex[:6].upper()  # generate new name for new image
        filename = abc + '.png'
        #print(filename)

        url = request.args['url']

        r = requests.get(url)

        fp = io.BytesIO(r.content)
        img = Image.open(fp)

        img = img.resize( (800, 600) )  # resize image

        img.save(filename)

        return {'status': 'OK', 'name': filename}

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)
</code>```

Body:
Can anyone please help me out with this error. I am trying to save an image from query string imagle url. but got stuck with the following error.
My code below, please ignore unnecessary libraries

from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import urllib.request as urllib
import io

app = Flask(__name__)
api = Api(app)

abc = uuid.uuid4().hex[:6].upper()

class Predict(Resource):
    def get(self):
        url = request.args['url']
        r = requests.get(url)
        fd = urllib.urlopen(r)
        image_file = io.BytesIO(fd.read())
        im = Image.open(image_file)
        return im.save(abc+".png")

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)

Output Error :

Body:
To save in file you don't need Image and BytesIO() - you can use directly open() and write()

If you want to save every image with different name then you should create abc inside get()

from flask import Flask, request
from flask_restful import Resource, Api
import requests
import uuid

app = Flask(__name__)
api = Api(app)

#abc = uuid.uuid4().hex[:6].upper()  # one name for all images

class Predict(Resource):

    def get(self):
        abc = uuid.uuid4().hex[:6].upper()  # generate new name for new image
        filename = abc + '.png'
        #print(filename)

        url = request.args['url']

        r = requests.get(url)

        f = open(filename, 'wb')  # write in bytes-mode 'wb'
        f.write(r.content)
        f.close()

        return {'status': 'OK', 'name': filename}

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)

You would need Image and BytesIO only if you would like to edit image before save.

from flask import Flask, request
from flask_restful import Resource, Api
import requests
import uuid
from PIL import Image
import io

app = Flask(__name__)
api = Api(app)

#abc = uuid.uuid4().hex[:6].upper() # one name for all images

class Predict(Resource):

    def get(self):
        abc = uuid.uuid4().hex[:6].upper()  # generate new name for new image
        filename = abc + '.png'
        #print(filename)

        url = request.args['url']

        r = requests.get(url)

        fp = io.BytesIO(r.content)
        img = Image.open(fp)

        img = img.resize( (800, 600) )  # resize image

        img.save(filename)

        return {'status': 'OK', 'name': filename}

api.add_resource(Predict, '/')

if __name__ == "__main__":
    app.run("", port=7999, debug=True)


问:
ArrayBuffer to base64 encoded string
I need an efficient (read native) way to convert an ArrayBuffer to a base64 string which needs to be used on a multipart post.

答:
The OP did not specify the Running Enviroment but if you are using Node.JS there is a very simple way to do such thing.

Accordig with the official Node.JS docs
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

```<code>// This step is only necessary if you don't already have a Buffer Object
const buffer = Buffer.from(yourArrayBuffer);

const base64String = buffer.toString('base64');
</code>```

Also, If you are running under Angular for example, the Buffer Class will also be made available in a Browser Environment.

Title: ArrayBuffer to base64 encoded string

Body:
The OP did not specify the Running Enviroment but if you are using Node.JS there is a very simple way to do such thing.

Accordig with the official Node.JS docs
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

// This step is only necessary if you don't already have a Buffer Object
const buffer = Buffer.from(yourArrayBuffer);

const base64String = buffer.toString('base64');

Also, If you are running under Angular for example, the Buffer Class will also be made available in a Browser Environment.


问:
How to disable @typescript-eslint/no-non-null-assertion rule
I want to allow data!.id

Error:

warning  Forbidden non-null assertion
  @typescript-eslint/no-non-null-assertion

Current config:

```<code>module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'eslint:recommended',
    'plugin:jsx-a11y/recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],
  plugins: ['react-hooks'],
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    '@typescript-eslint/ban-ts-ignore': 0,
    '@typescript-eslint/no-explicit-any': 0,
    '@typescript-eslint/consistent-type-assertions': ['warn', { assertionStyle: 'as' }],
    eqeqeq: 1,
    'react/prop-types': 0,
    '@typescript-eslint/camelcase': 0,
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': 'warn'
  },
  globals: {
    React: 'writable'
  }
}
</code>```

答:
Please add '@typescript-eslint/no-non-null-assertion': 'off' to your config file like below.

```<code>module.exports = {
  ...
  rules: {
    ...
    '@typescript-eslint/no-non-null-assertion': 'off'
  },
  ...
}
</code>```

Body:
I want to allow data!.id

Error:

warning  Forbidden non-null assertion
  @typescript-eslint/no-non-null-assertion

Current config:

module.exports = {
  parser: '@typescript-eslint/parser',
  extends: [
    'eslint:recommended',
    'plugin:jsx-a11y/recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react/recommended',
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ],
  plugins: ['react-hooks'],
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true
    }
  },
  rules: {
    '@typescript-eslint/ban-ts-ignore': 0,
    '@typescript-eslint/no-explicit-any': 0,
    '@typescript-eslint/consistent-type-assertions': ['warn', { assertionStyle: 'as' }],
    eqeqeq: 1,
    'react/prop-types': 0,
    '@typescript-eslint/camelcase': 0,
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': 'warn'
  },
  globals: {
    React: 'writable'
  }
}

Body:
Please add '@typescript-eslint/no-non-null-assertion': 'off' to your config file like below.

module.exports = {
  ...
  rules: {
    ...
    '@typescript-eslint/no-non-null-assertion': 'off'
  },
  ...
}


问:
Upload files to Box directly from SFTP server without saving an intermediate file using Python

sftp.get(remotepath, localpath) #for sftp to localdrive
upload = client.folder(Folder_id).upload(localpath) #localdrive to box
```

Using Python I'm downloading files from SFTP server to local drive and then from local drive to my box.

Is that possible to upload my files to box directly from SFTP server using Python without saving the file to local drive?

I'm using Paramiko and Box SDK.

答:
You can use SFTPClient.open to open a file on an SFTP server as if it were a local file. It returns a file-like object. You can then use the object with Folder.upload_stream:

```<code>with sftp.open(remotepath, "rb") as flo:
    flo.prefetch()
    client.folder(folder_id).upload_stream(flo, file_name)
</code>```

For the SFTPFile.prefetch call, refer to:

Reading file opened with Python Paramiko SFTPClient.open method is slow.

Body:
sftp.get(remotepath, localpath) #for sftp to localdrive
upload = client.folder(Folder_id).upload(localpath) #localdrive to box

Using Python I'm downloading files from SFTP server to local drive and then from local drive to my box.

Is that possible to upload my files to box directly from SFTP server using Python without saving the file to local drive?

I'm using Paramiko and Box SDK.

Body:
You can use SFTPClient.open to open a file on an SFTP server as if it were a local file. It returns a file-like object. You can then use the object with Folder.upload_stream:

with sftp.open(remotepath, "rb") as flo:
    flo.prefetch()
    client.folder(folder_id).upload_stream(flo, file_name)

For the SFTPFile.prefetch call, refer to:

Reading file opened with Python Paramiko SFTPClient.open method is slow.


问:
JPA & Hibernate: Eager loading performing subsequent queries to fetch all data, instead of doing it in just one query
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

```<code>@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;
</code>```

In the other side there is the class named Classroom as follows:

```<code>@Entity
public class Classroom {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;
</code>```

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

```<code>Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID
</code>```

And then it performs the next query as many times as Students assigned to each classroom.

```<code>  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?
</code>```

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

```<code>SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */
</code>```

And then, the output query does takes all the information in just one query:

```<code>Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID
</code>```

答:
By default fetchtype is lazy, that mean if you dont ask for the List in your request Hibernate will not collect it.

In first request you ask for all attribute of Classroom r including the Student list so Hibernate will load them lazily (after finding out that you need them).

But when fetchtype is set to eager hibernate collect it even if you dont ask it.

Body:
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;

In the other side there is the class named Classroom as follows:

@Entity
public class Classroom {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID

And then it performs the next query as many times as Students assigned to each classroom.

  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */

And then, the output query does takes all the information in just one query:

Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID


问:
Deleting large continuous blocks of lines separated by empty lines
I have a large dataset, composed of text in the following form. </p>

```<code>Vil [SENT]2 [POS]AUX [NUM]4 [DEP]aux O
du [SENT]2 [POS]PRON [NUM]4 [DEP]nsubj O
gerne [SENT]2 [POS]ADV [NUM]4 [DEP]advmod O
arbejde [SENT]2 [POS]VERB [NUM]0 [DEP]root O
med [SENT]2 [POS]ADP [NUM]9 [DEP]case O
et [SENT]2 [POS]DET [NUM]9 [DEP]det O
globalt [SENT]2 [POS]ADV [NUM]8 [DEP]advmod O
anerkendt [SENT]2 [POS]VERB [NUM]9 [DEP]amod O
brand [SENT]2 [POS]NOUN [NUM]4 [DEP]obl O
? [SENT]2 [POS]PUNCT [NUM]4 [DEP]punct O
XXX. [SENT]3 [POS]ADP [NUM]2 [DEP]case O
XXX [SENT]3 [POS]PROPN [NUM]0 [DEP]root O
XXX [SENT]3 [POS]NOUN [NUM]2 [DEP]flat O
, [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O
XXX [SENT]3 [POS]PROPN [NUM]2 [DEP]flat O
. [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O

Deltidsjob [SENT]4 [POS]NOUN [NUM]0 [DEP]root O
i [SENT]4 [POS]ADP [NUM]3 [DEP]case O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]NOUN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]ADJ [NUM]6 [DEP]amod O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
. [SENT]4 [POS]PUNCT [NUM]1 [DEP]punct O
</code>```

<p>I am using python and would like to delete "line blocks" that are longer than a certain threshold. That is, the length from one empty line to the next crosses the threshold. I thought about iterating over lines, keeping a count and keeping track with a while loop, but can anyone come up with a more elegant solution? </p>

答:
```<code>sample = """Vil [SENT]2 [POS]AUX [NUM]4 [DEP]aux O
du [SENT]2 [POS]PRON [NUM]4 [DEP]nsubj O
gerne [SENT]2 [POS]ADV [NUM]4 [DEP]advmod O
arbejde [SENT]2 [POS]VERB [NUM]0 [DEP]root O
med [SENT]2 [POS]ADP [NUM]9 [DEP]case O
et [SENT]2 [POS]DET [NUM]9 [DEP]det O
globalt [SENT]2 [POS]ADV [NUM]8 [DEP]advmod O
anerkendt [SENT]2 [POS]VERB [NUM]9 [DEP]amod O
brand [SENT]2 [POS]NOUN [NUM]4 [DEP]obl O
? [SENT]2 [POS]PUNCT [NUM]4 [DEP]punct O
XXX. [SENT]3 [POS]ADP [NUM]2 [DEP]case O
XXX [SENT]3 [POS]PROPN [NUM]0 [DEP]root O
XXX [SENT]3 [POS]NOUN [NUM]2 [DEP]flat O
, [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O
XXX [SENT]3 [POS]PROPN [NUM]2 [DEP]flat O
. [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O

Deltidsjob [SENT]4 [POS]NOUN [NUM]0 [DEP]root O
i [SENT]4 [POS]ADP [NUM]3 [DEP]case O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]NOUN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]ADJ [NUM]6 [DEP]amod O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
. [SENT]4 [POS]PUNCT [NUM]1 [DEP]punct O"""

samples = sample.split('\n\n')
threshold = 300

remaining_samples = []

for s in samples:
    if len(s) < threshold:
        remaining_samples.append(s)

print(remaining_samples)
</code>```

Body:
I have a large dataset, composed of text in the following form.

Vil [SENT]2 [POS]AUX [NUM]4 [DEP]aux O
du [SENT]2 [POS]PRON [NUM]4 [DEP]nsubj O
gerne [SENT]2 [POS]ADV [NUM]4 [DEP]advmod O
arbejde [SENT]2 [POS]VERB [NUM]0 [DEP]root O
med [SENT]2 [POS]ADP [NUM]9 [DEP]case O
et [SENT]2 [POS]DET [NUM]9 [DEP]det O
globalt [SENT]2 [POS]ADV [NUM]8 [DEP]advmod O
anerkendt [SENT]2 [POS]VERB [NUM]9 [DEP]amod O
brand [SENT]2 [POS]NOUN [NUM]4 [DEP]obl O
? [SENT]2 [POS]PUNCT [NUM]4 [DEP]punct O
XXX. [SENT]3 [POS]ADP [NUM]2 [DEP]case O
XXX [SENT]3 [POS]PROPN [NUM]0 [DEP]root O
XXX [SENT]3 [POS]NOUN [NUM]2 [DEP]flat O
, [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O
XXX [SENT]3 [POS]PROPN [NUM]2 [DEP]flat O
. [SENT]3 [POS]PUNCT [NUM]2 [DEP]punct O

Deltidsjob [SENT]4 [POS]NOUN [NUM]0 [DEP]root O
i [SENT]4 [POS]ADP [NUM]3 [DEP]case O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]NOUN [NUM]1 [DEP]nmod O
XXX [SENT]4 [POS]ADJ [NUM]6 [DEP]amod O
XXX [SENT]4 [POS]PROPN [NUM]1 [DEP]nmod O
. [SENT]4 [POS]PUNCT [NUM]1 [DEP]punct O

I am using python and would like to delete "line blocks" that are longer than a certain threshold. That is, the length from one empty line to the next crosses the threshold. I thought about iterating over lines, keeping a count and keeping track with a while loop, but can anyone come up with a more elegant solution?


问:
pandas bar chart y-axis min max range in floating number

I have a graph like this. I want to build it using python matplotlib.pyplot. However I get the graph like this.

How can I change the range of y-axis? instead of 0 to 13, I want it to range from min_value-1 to max_value+1 in floating values.

答:
Something like this?
Just a simple example. </p>

```<code>import numpy as np
import matplotlib.pyplot as plt

array = np.array([110,200,300])
ax = plt.gca()

minimum = array.min()-10
maximum = array.max()+10
ax.set_ylim([minimum,maximum])
plt.bar(range(len(array)), array)
</code>```

Body:
Something like this?
Just a simple example.

import numpy as np
import matplotlib.pyplot as plt

array = np.array([110,200,300])
ax = plt.gca()

minimum = array.min()-10
maximum = array.max()+10
ax.set_ylim([minimum,maximum])
plt.bar(range(len(array)), array)


问:
Javac is not recognized even after setting the path
I have installed my jdk file. I have also set my path in the advanced setting in the user variable as well as system variable. When I tried to compile my program through  javac filename.java the command prompt is showing javac is not recognized as an internal or external command. I again set my path but still the problem remains the same</p>

答:
This problem happens when you define your JAVA_HOME under User variables and not under the system variables.

Try moving the JAVA_HOME to System Variables and restart the command prompt. It will work like a charm.