问:
Merge two objects List in Java
How to merge two user list, if user is common merge its attribute.

I have two user lists, getting first list from DB and second from web service, if their firstname and lastname are same then user merge attribute and return combined list.

```<code>import java.util.List;
import java.util.Objects;

 class User {
     String firstName;
     String lastName;
     Integer count;
     Integer marks;
     String status;

     @Override
     public boolean equals(Object o) {
         if (this == o) return true;
         if (!(o instanceof User)) return false;
         User user = (User) o;
         return Objects.equals(firstName, user.firstName) &&
                 Objects.equals(lastName, user.lastName);
     }

     @Override
     public int hashCode() {
         return Objects.hash(firstName, lastName);
     }

    //constructor getter setter....

 }

 public class MainTest {

     public static void main(String[] args) {

         List<User> source1 = List.of(new User("A", "A", 1, 0, null),
                 new User("B", "B", 2, 0, null),
                 new User("C", "C", 3, 0, null));

         List<User> source2 = List.of(new User("A", "A", 0, 10, "FAIL"),
                 new User("B", "B", 0, 20, "FAIL"),
                 new User("D", "D", 0, 30, "PASS"));

         List<User> combinedExpectedList = List.of(new User("A", "A", 1, 10, "FAIL"),
                 new User("B", "B", 2, 20, "FAIL"),
                 new User("C", "C", 3, 0, null),
                 new User("D", "D", 0, 30, "PASS"));

         //List<User> userList3= Stream.concat(source1.stream(), source2.stream()).distinct().collect(Collectors.toList());//Adding 4 records but marks and status not copied
         //BeanUtils.copyProperties(model2, model1); - can't user don't have library

         for (User t : source2) {
             for (User s : source1) {
                 if (t.getFirstName().equals(s.getFirstName()) && t.getLastName().equals(s.getLastName())) {
                     t.setCount(s.getCount());
                 }
             }
         }// Not adding record with firstName=C and LastName=C

         System.out.println(combinedExpectedList.equals(source2));
     }
 }
</code>```

答:
Assuming that you want to retain non zero marks and non null status elements, you can not directly use distinct. You can use Collectors.toMap as below,

```<code>List<User> userList3 = Stream.concat(source1.stream(), source2.stream())
                .collect(Collectors.toMap(e -> e.firstName + e.lastName, e -> e,
                        (User u1, User u2) -> {
                            if (u1.marks == 0)
                                u1.marks = u2.marks;
                            if (u1.status == null)
                                u1.status = u2.status;
                            return u1;
                        })).values().stream().collect(Collectors.toList());
</code>```

Note that you may need to reorder elements.

Title: Merge two objects List in Java

Body:
How to merge two user list, if user is common merge its attribute.

I have two user lists, getting first list from DB and second from web service, if their firstname and lastname are same then user merge attribute and return combined list.

import java.util.List;
import java.util.Objects;

 class User {
     String firstName;
     String lastName;
     Integer count;
     Integer marks;
     String status;

     @Override
     public boolean equals(Object o) {
         if (this == o) return true;
         if (!(o instanceof User)) return false;
         User user = (User) o;
         return Objects.equals(firstName, user.firstName) &&
                 Objects.equals(lastName, user.lastName);
     }

     @Override
     public int hashCode() {
         return Objects.hash(firstName, lastName);
     }

    //constructor getter setter....

 }

 public class MainTest {

     public static void main(String[] args) {

         List<User> source1 = List.of(new User("A", "A", 1, 0, null),
                 new User("B", "B", 2, 0, null),
                 new User("C", "C", 3, 0, null));

         List<User> source2 = List.of(new User("A", "A", 0, 10, "FAIL"),
                 new User("B", "B", 0, 20, "FAIL"),
                 new User("D", "D", 0, 30, "PASS"));

         List<User> combinedExpectedList = List.of(new User("A", "A", 1, 10, "FAIL"),
                 new User("B", "B", 2, 20, "FAIL"),
                 new User("C", "C", 3, 0, null),
                 new User("D", "D", 0, 30, "PASS"));

         //List<User> userList3= Stream.concat(source1.stream(), source2.stream()).distinct().collect(Collectors.toList());//Adding 4 records but marks and status not copied
         //BeanUtils.copyProperties(model2, model1); - can't user don't have library

         for (User t : source2) {
             for (User s : source1) {
                 if (t.getFirstName().equals(s.getFirstName()) && t.getLastName().equals(s.getLastName())) {
                     t.setCount(s.getCount());
                 }
             }
         }// Not adding record with firstName=C and LastName=C

         System.out.println(combinedExpectedList.equals(source2));
     }
 }

Body:
Assuming that you want to retain non zero marks and non null status elements, you can not directly use distinct. You can use Collectors.toMap as below,

List<User> userList3 = Stream.concat(source1.stream(), source2.stream())
                .collect(Collectors.toMap(e -> e.firstName + e.lastName, e -> e,
                        (User u1, User u2) -> {
                            if (u1.marks == 0)
                                u1.marks = u2.marks;
                            if (u1.status == null)
                                u1.status = u2.status;
                            return u1;
                        })).values().stream().collect(Collectors.toList());

Note that you may need to reorder elements.


来源: stackexchange

问:
Python doesn't let me change the number of axis ticks when using subplots
I have code which looks like this:

```<code>plt.figure()

plt.subplot(211)
plt.plot(timestamps_SW, np.random.randn(len(testLabelsSW_ds)), label='truth')
plt.plot(timestamps_SW, np.random.randn(len(testLabelsSW_ds)), label='pred.')
plt.locator_params(axis='y', nbins=5)
plt.legend()

plt.subplot(212)
plt.plot(timestamps_SE,np.random.randn(len(testLabelsSE_ds)), label='truth')
plt.plot(timestamps_SE,np.random.randn(len(testLabelsSE_ds)), label='pred.')
plt.locator_params(axis='y', nbins=5)
plt.legend()
</code>```

The resulting plot looks as such:

Clearly each y-axis doesn't have 5 ticks. How do I fix?

答:
Using plt.locator_params(..., nbins=5) you ask the default locator to use 5 bins. The default locator is an AutoLocator. It's a subclass of the MaxNLocator. MaxN means, it will try to find a maximum of N nice locations, where N is equal to nbins + 1.
"Nice" locations means, e.g. something like 1.0, 0.25 etc are considered "nice", while something like 0.761 is of course not so nice.

The two constraints (a) "nice" and (b) "N locations" are of course seldomly fulfillable at the same time. Therefore "nice" has priority here.

If you leave out the constraint (a), you can get N locations simply by placing the ticks manually,

```<code>plt.yticks(np.linspace(*plt.ylim(), 5))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have code which looks like this:

plt.figure()

plt.subplot(211)
plt.plot(timestamps_SW, np.random.randn(len(testLabelsSW_ds)), label='truth')
plt.plot(timestamps_SW, np.random.randn(len(testLabelsSW_ds)), label='pred.')
plt.locator_params(axis='y', nbins=5)
plt.legend()

plt.subplot(212)
plt.plot(timestamps_SE,np.random.randn(len(testLabelsSE_ds)), label='truth')
plt.plot(timestamps_SE,np.random.randn(len(testLabelsSE_ds)), label='pred.')
plt.locator_params(axis='y', nbins=5)
plt.legend()

The resulting plot looks as such:

Clearly each y-axis doesn't have 5 ticks. How do I fix?

Body:
Using plt.locator_params(..., nbins=5) you ask the default locator to use 5 bins. The default locator is an AutoLocator. It's a subclass of the MaxNLocator. MaxN means, it will try to find a maximum of N nice locations, where N is equal to nbins + 1.
"Nice" locations means, e.g. something like 1.0, 0.25 etc are considered "nice", while something like 0.761 is of course not so nice.

The two constraints (a) "nice" and (b) "N locations" are of course seldomly fulfillable at the same time. Therefore "nice" has priority here.

If you leave out the constraint (a), you can get N locations simply by placing the ticks manually,

plt.yticks(np.linspace(*plt.ylim(), 5))


问:
Django, creating a custom 500/404 error page
Following the tutorial found here exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up?

File directories:

```<code>mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

</code>```

within mysite/settings.py I have these enabled:

```<code>DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates',
)
</code>```

within mysite/polls/urls.py:

```<code>from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
</code>```

I can post any other code necessary, but what should I be changing to get a custom 500 error page if I use a bad url?

答:
In Django 3.x, the accepted answer won't work because render_to_response has been removed completely as well as some more changes have been made since the version the accepted answer worked for.

Some other answers are also there but I'm presenting a little cleaner answer:

In your main urls.py file:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'
```

<p>In <code>yourapp/views.py</code> file:</p>

<pre class="lang-py prettyprint-override"><code>def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response

def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response
</code>```

Ensure that you have imported render() in yourapp/views.py file:

from django.shortcuts import render
```

Side note: render_to_response() was deprecated in Django 2.x and it has been completely removed in verision 3.x.

Body:
Following the tutorial found here exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up?

File directories:

mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

within mysite/settings.py I have these enabled:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates',
)

within mysite/polls/urls.py:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

I can post any other code necessary, but what should I be changing to get a custom 500 error page if I use a bad url?

Body:
In Django 3.x, the accepted answer won't work because render_to_response has been removed completely as well as some more changes have been made since the version the accepted answer worked for.

Some other answers are also there but I'm presenting a little cleaner answer:

In your main urls.py file:

handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'

In yourapp/views.py file:

def handler404(request, exception):
    context = {}
    response = render(request, "pages/errors/404.html", context=context)
    response.status_code = 404
    return response

def handler500(request):
    context = {}
    response = render(request, "pages/errors/500.html", context=context)
    response.status_code = 500
    return response

Ensure that you have imported render() in yourapp/views.py file:

from django.shortcuts import render

Side note: render_to_response() was deprecated in Django 2.x and it has been completely removed in verision 3.x.


问:
Making at least One Checkbox mandatory out of the given checkboxes on submit
I have the several check boxes inside of the form group. How can I made this Area of Interest checkbox mandatory on submit? At least the user clicks on one checkbox before submitting. I have used react-bootstrap.

Any help are appreciated.

<Form.Group>
    <Form.Label>Area of Interest</Form.Label>
    <Form.Check
        name="areaOfInterest"
        label="Dedicated Teams"
        id="dt"
        value={"Dedicated Teams" || formInput.areaOfInterest}
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Cloud Expert Advice & Support"
        id="ceas"
        value="Cloud Expert Advice & Support"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Software Development"
        id="sd"
        value="Software Development"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Digital Transformation"
        id="dit"
        value="Digital Transformation"
        onChange={handleCheck}
    />
</Form.Group>
```

答:
On form submit you can check the existence of checked checkbox, if there is not any checked you can return false.

Demo:

function submitForm(){
  if(!document.querySelector(':checked'))
    return false;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return submitForm()">
  <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
  <label for="vehicle3"> I have a boat</label><br>

  <button>Submit</button>
</form></code>```

Body:
On form submit you can check the existence of checked checkbox, if there is not any checked you can return false.

Demo:

function submitForm(){
  if(!document.querySelector(':checked'))
    return false;
};

<form onsubmit="return submitForm()">
  <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
  <label for="vehicle3"> I have a boat</label><br>

  <button>Submit</button>
</form>


问:
Remeshing 3D triangulated surface for better mesh quaility
I am using marching cubes to extract a 2D surface from a volume. In this case a Gyroid.

```<code>import numpy as np
from numpy import sin, cos, pi
from skimage import measure
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def gyroid(x, y, z, t):
    return cos(x)*sin(y) + cos(y)*sin(z) + cos(z)*sin(x) - t

lattice_param = 1.0
strut_param = 0.0
resolution = 31j

x, y, z = pi*np.mgrid[-1:1:resolution, -1:1:resolution, -1:1:resolution] * lattice_param
vol = gyroid(x, y, z, strut_param)

verts, faces = measure.marching_cubes(vol, 0, spacing=(0.1, 0.1, 0.1)) # , normals, values

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], faces, verts[:, 2], cmap='ocean', lw=1)
</code>```

This all works fine but the mesh quailty is appalling in a lot of places. I cant run any FEA on the meshes as many of the elements/faces have near zero area or are highly distorted.

Is there a way of either remeshing given the vertices & ensuring particular elementface/facet metrics (such as aspect ratio) or forcing marching cubes to do such a thing?

I am not bothered about moving vertices as long as the mesh is a fair approximation.

答:
Use can use pygalmesh for surface remeshing, too. (It's a easy-to-use interface to CGAL.)

import pygalmesh

# create verts, faces

meshio.write_points_cells("in.vtu", verts, [("triangle", faces)])

mesh = pygalmesh.remesh_surface(
    "in.vtu",
    edge_size=0.025,
    facet_angle=25,
    facet_size=0.1,
    facet_distance=0.001,
    verbose=False,
)
# mesh.points, mesh.cells
```

Body:
I am using marching cubes to extract a 2D surface from a volume. In this case a Gyroid.

import numpy as np
from numpy import sin, cos, pi
from skimage import measure
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def gyroid(x, y, z, t):
    return cos(x)*sin(y) + cos(y)*sin(z) + cos(z)*sin(x) - t

lattice_param = 1.0
strut_param = 0.0
resolution = 31j

x, y, z = pi*np.mgrid[-1:1:resolution, -1:1:resolution, -1:1:resolution] * lattice_param
vol = gyroid(x, y, z, strut_param)

verts, faces = measure.marching_cubes(vol, 0, spacing=(0.1, 0.1, 0.1)) # , normals, values

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(verts[:, 0], verts[:, 1], faces, verts[:, 2], cmap='ocean', lw=1)

This all works fine but the mesh quailty is appalling in a lot of places. I cant run any FEA on the meshes as many of the elements/faces have near zero area or are highly distorted.

Is there a way of either remeshing given the vertices & ensuring particular elementface/facet metrics (such as aspect ratio) or forcing marching cubes to do such a thing?

I am not bothered about moving vertices as long as the mesh is a fair approximation.


问:
Laravel check if storage exists is not working
I'm trying to check if file already exist in the storage by

```<code>if(Storage::exists($request->file_name)):
    dd(var_dump("it did exist"));
else:
    dd(var_dump("it did not exist"));
endif
</code>```

but it always return a string "it did exist" even though the file is actually deleted or the file did not exist, any ideas, help?

I'm sure there's no problem on my storage location set up as I'm having no problem when uploading a file to the storage,

```<code>Storage::put($file_name, File::get($file));
</code>```

PS: I'm on Laravel 5.0

UPDATE:

here's my filesystems.php from the config folder of my Laravel 5.0

```<code><?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => 'local',

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root'   => storage_path().'/employee_documents/',
        ],

        's3' => [
            'driver' => 's3',
            'key'    => 'your-key',
            'secret' => 'your-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

        'rackspace' => [
            'driver'    => 'rackspace',
            'username'  => 'your-username',
            'key'       => 'your-key',
            'container' => 'your-container',
            'endpoint'  => 'https://identity.api.rackspacecloud.com/v2.0/',
            'region'    => 'IAD',
        ],

    ],

];
</code>```

答:
I had the same problem on Laravel 5.5 and the solution was to use

```<code>Storage::disk('public')->exists($file_name)
</code>```

instead of

```<code>Storage::exists($file_name)
</code>```

On my config/filesystem.php by default I have two types of local disks (local and public) and I wasn't aware of it:

```<code>    'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

],
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to check if file already exist in the storage by

if(Storage::exists($request->file_name)):
    dd(var_dump("it did exist"));
else:
    dd(var_dump("it did not exist"));
endif

but it always return a string "it did exist" even though the file is actually deleted or the file did not exist, any ideas, help?

I'm sure there's no problem on my storage location set up as I'm having no problem when uploading a file to the storage,

Storage::put($file_name, File::get($file));

PS: I'm on Laravel 5.0

UPDATE:

here's my filesystems.php from the config folder of my Laravel 5.0

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default filesystem disk that should be used
    | by the framework. A "local" driver, as well as a variety of cloud
    | based drivers are available for your choosing. Just store away!
    |
    | Supported: "local", "s3", "rackspace"
    |
    */

    'default' => 'local',

    /*
    |--------------------------------------------------------------------------
    | Default Cloud Filesystem Disk
    |--------------------------------------------------------------------------
    |
    | Many applications store files both locally and in the cloud. For this
    | reason, you may specify a default "cloud" driver here. This driver
    | will be bound as the Cloud disk implementation in the container.
    |
    */

    'cloud' => 's3',

    /*
    |--------------------------------------------------------------------------
    | Filesystem Disks
    |--------------------------------------------------------------------------
    |
    | Here you may configure as many filesystem "disks" as you wish, and you
    | may even configure multiple disks of the same driver. Defaults have
    | been setup for each driver as an example of the required options.
    |
    */

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root'   => storage_path().'/employee_documents/',
        ],

        's3' => [
            'driver' => 's3',
            'key'    => 'your-key',
            'secret' => 'your-secret',
            'region' => 'your-region',
            'bucket' => 'your-bucket',
        ],

        'rackspace' => [
            'driver'    => 'rackspace',
            'username'  => 'your-username',
            'key'       => 'your-key',
            'container' => 'your-container',
            'endpoint'  => 'https://identity.api.rackspacecloud.com/v2.0/',
            'region'    => 'IAD',
        ],

    ],

];

Body:
I had the same problem on Laravel 5.5 and the solution was to use

Storage::disk('public')->exists($file_name)

instead of

Storage::exists($file_name)

On my config/filesystem.php by default I have two types of local disks (local and public) and I wasn't aware of it:

    'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
    ],

],


问:
Javascript Firebase-Storage image upload not working
I am trying to upload an image from HTML form to firebase storage using an external JS file, but when I try to upload the image file (which is not empty - it exists) the path to the image location is not created on firebase storage when I execute the storageRef.put(image); function, and also the image itself (obviously) not being saved.

this is my code:

index.html file:

```<code><!DOCTYPE html>
<html>
<head>
    <title>אורט ביאליק עדכון פרטים</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
    <style>
        html, body {
            min-height: 100%;
            direction: rtl
        }

        body, div, form, input, select, p {
            padding: 0;
            margin: 0;
            outline: none;
            font-family: Roboto, Arial, sans-serif;
            font-size: 16px;
            color: #eee;
        }

    body { background: url("https://firebasestorage.googleapis.com/v0/b/XXXXXXXX.appspot.com/o/not%20to%20delete%2Fbackground.jpeg?alt=media&token=b5e0cc70-dc1c-40c7-a3fa-15694541828e") no-repeat center; background-size: cover; }

        h1, h2 {
            text-transform: uppercase;
            font-weight: 400;
        }

        h2 {
            margin: 0 0 0 8px;
        }

        .main-block {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 25px;
            background: rgba(0, 0, 0, 0.5);
        }

        .left-part, form {
            padding: 25px;
        }

        .left-part {
            text-align: center;
        }

        .fa-graduation-cap {
            font-size: 72px;
        }

        form {
            background: rgba(0, 0, 0, 0.7);
        }

        .title {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .info {
            display: flex;
            flex-direction: column;
        }

        input, select {
            padding: 5px;
            margin-bottom: 30px;
            background: transparent;
            border: none;
            border-bottom: 1px solid #eee;
        }

            input::placeholder {
                color: #eee;
            }

        option:focus {
            border: none;
        }

        option {
            background: black;
            border: none;
        }

        .btn-item, button {
            padding: 10px 5px;
            margin-top: 20px;
            border-radius: 5px;
            border: none;
            background: #26a9e0;
            text-decoration: none;
            font-size: 15px;
            font-weight: 400;
            color: #fff;
        }

        .btn-item {
            display: inline-block;
            margin: 20px 5px 0;
        }

        button {
            width: 100%;
        }

            button:hover, .btn-item:hover {
                background: #85d6de;
            }

        @media (min-width: 568px) {
            html, body {
                height: 100%;
            }

            .main-block {
                flex-direction: row;
                height: calc(100% - 50px);
            }

            .left-part, form {
                flex: 1;
                height: auto;
            }
        }
    </style>
</head>
<body>
    <div class="main-block">
        <div class="left-part">
            <img src="https://firebasestorage.googleapis.com/v0/b/XXXXXXXXX.appspot.com/o/not%20to%20delete%2Fkiryat_bialik_img.jpg?alt=media&token=5d637243-1cb1-430c-a7c5-1a98329bb3a0">
        </div>

        <form name="RegForm" action="/">
            <div class="title">
                <i class="fas fa-pencil-alt"></i>
                <h2>מכללת אורט ביאליק - עדכון פרטים אישיים</h2>
            </div>
            <div class="info">
                <input class="fname" type="text" name="HEfname" id="HEfname" maxlength="20" required autofocus placeholder="שם פרטי">
                <input class="fname" type="text" name="HElname" id="HElname" maxlength="20" required placeholder="שם משפחה">
                <input class="fname" type="text" name="ENfname" id="ENfname" maxlength="20" required placeholder="שם פרטי באנגלית">
                <input class="fname" type="text" name="ENlname" id="ENlname" maxlength="20" required placeholder="שם משפחה באנגלית">
                <input type="text" name="Email" inputmode="email" id="email" required maxlength="40" placeholder="Email">
                <input type="text" name="id" id="id" required maxlength="9" placeholder="מספר תעודת זהות">
                <input type="file" name="img" id="img" required accept="image/*">
            </div>
            <button type="submit" name="submit" id="submit" value="submit" onclick="return validation();" href="/">שלח</button>
        </form>
    </div>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js"></script>

    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-database.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.8.2/firebase-storage.js"></script>

    <script src="js/formValidation.js"></script>
    <script src="js/formSubmission.js"></script>
</body>
</html>
</code>```

formSubmission.js:

```<code>

// My web app's Firebase configuration
var firebaseConfig = {
    apiKey: "XXXXXXXXXXXX",
    authDomain: "XXXXXXXXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXXXXXXXX.firebaseio.com",
    projectId: "XXXXXXXXXXXX",
    storageBucket: "XXXXXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXXXXX",
    appId: "XXXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Reference Users collection
var databaseRef = firebase.database().ref('Users');

// Listen for form submit
document.forms.RegForm.addEventListener('submit', submitForm);

// Submit form
function submitForm() {
    //if (validation()) {
    // Get values
    var HEfname = getInputVal('HEfname');
    var ENfname = getInputVal('ENfname');
    var HElname = getInputVal('HElname');
    var ENlname = getInputVal('ENlname');
    var email = getInputVal('email');
    var id1 = getInputVal('id');
    var imageFile = document.getElementById('img').files[0];

    //this VAR's are used in 'saveUser()'; function. ---NOT IN USE---
    // unused value=5;  if false value=0; if true value=1
    var isSavedDatabase = false; //  if user data successfully commited to Firebase Database.
    var isSavedImage = false; //  if user image successfully commited to Firebase Storage.

    // Save User
    saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile);

}
    // Function to get get form values
    function getInputVal(id) {
        return document.getElementById(id).value;
    }

    // Save User to firebase
function saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile) {

    // reference to image path in storage 'passportImages/id1' (id1 is current user ID)
    var imageRef = firebase.storage().ref().child('passportImages/' + id1);

    //save User to database
    var newUserRef = databaseRef.child(id1);
    newUserRef.set({
        HEfname: HEfname,
        HElname: HElname,
        ENfname: ENfname,
        ENlname: ENlname,
        email: email,
        id: id1
    }, function (error) {
        if (error) {
            // The write failed
            console.log("User info could not be saved: " + error);
        } else {
            // Data saved successfully!
            isSavedDatabase = true;
            console.log("User info saved successfully!");
            saveImage(imageFile, id1);

            //imageRef.delete(); // remove user image from storage if his info could not be saved t database.
        }
    });

    //save image to storage by ID
    function saveImage(imageFile, id) {
        // Upload file to the object 'passportImages/id1' (id1 is current user ID)
        var uploadTask = firebase.storage().ref().child('passportImages/' + id).put(imageFile);

        // Listen for state changes, errors, and completion of the upload.
        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
            function (snapshot) {
                // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                console.log('Upload is ' + progress + '% done');
                switch (snapshot.state) {
                    case firebase.storage.TaskState.PAUSED: // or 'paused'
                        console.log('Upload is paused');
                        break;
                    case firebase.storage.TaskState.RUNNING: // or 'running'
                        console.log('Upload is running');
                        break;
                }
            }, function (error) {
                databaseRef.child(id).remove(); //remove user info from database if his image could not be uploaded to storage too.
                console.log(error);
                window.alert("Something went wrong, please try again");

                // A full list of error codes is available at
                // https://firebase.google.com/docs/storage/web/handle-errors
                switch (error.code) {
                    case 'storage/unauthorized':
                        // User doesn't have permission to access the object
                        console.log("Image: User doesn't have permission to access the object");
                        break;

                    case 'storage/canceled':
                        // User canceled the upload
                        console.log("Image: User canceled the upload");
                        break;

                    case 'storage/unknown':
                        // Unknown error occurred, inspect error.serverResponse
                        console.log("Image: Unknown error occurred, inspect error.serverResponse");
                        break;
                }
            }, function () {
                // Upload completed successfully!
                isSavedImage = true;
                console.log("Image uploaded successfully!");
                finalCall();
            });
        //if all data commited successfully to Firebase pop a massage and reset form.
        function finalCall() {

            // Show alert
            window.alert("Your info has been sent!");

            // Clear form
            document.forms.RegForm.reset();
        }
    }
    //}
}
</code>```

答:
It is probably because you assign the submit type to your button. Your form is probably submitted before the submitForm() method is triggered.

If this assumption is correct, changing the type to button, as follows, should do the trick:

```<code><button type="button" id="submit" onclick="return validation();" href="/">שלח</button>
</code>```

See the W3 specification for more detail.

Body:
I am trying to upload an image from HTML form to firebase storage using an external JS file, but when I try to upload the image file (which is not empty - it exists) the path to the image location is not created on firebase storage when I execute the storageRef.put(image); function, and also the image itself (obviously) not being saved.

this is my code:

index.html file:

<!DOCTYPE html>

    <title>אורט ביאליק עדכון פרטים</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css" integrity="sha384-5sAR7xN1Nv6T6+dT2mhtzEpVJvfS3NScPQTrOxhwjIuvcA67KV2R5Jz6kr4abQsz" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">

        <form name="RegForm" action="/">

מכללת אורט ביאליק - עדכון פרטים אישיים

                <input class="fname" type="text" name="HEfname" id="HEfname" maxlength="20" required autofocus placeholder="שם פרטי">
                <input class="fname" type="text" name="HElname" id="HElname" maxlength="20" required placeholder="שם משפחה">
                <input class="fname" type="text" name="ENfname" id="ENfname" maxlength="20" required placeholder="שם פרטי באנגלית">
                <input class="fname" type="text" name="ENlname" id="ENlname" maxlength="20" required placeholder="שם משפחה באנגלית">
                <input type="text" name="Email" inputmode="email" id="email" required maxlength="40" placeholder="Email">
                <input type="text" name="id" id="id" required maxlength="9" placeholder="מספר תעודת זהות">
                <input type="file" name="img" id="img" required accept="image/*">

            <button type="submit" name="submit" id="submit" value="submit" onclick="return validation();" href="/">שלח</button>
        </form>

formSubmission.js:

// My web app's Firebase configuration
var firebaseConfig = {
    apiKey: "XXXXXXXXXXXX",
    authDomain: "XXXXXXXXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXXXXXXXX.firebaseio.com",
    projectId: "XXXXXXXXXXXX",
    storageBucket: "XXXXXXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXXXXXX",
    appId: "XXXXXXXXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Reference Users collection
var databaseRef = firebase.database().ref('Users');

// Listen for form submit
document.forms.RegForm.addEventListener('submit', submitForm);

// Submit form
function submitForm() {
    //if (validation()) {
    // Get values
    var HEfname = getInputVal('HEfname');
    var ENfname = getInputVal('ENfname');
    var HElname = getInputVal('HElname');
    var ENlname = getInputVal('ENlname');
    var email = getInputVal('email');
    var id1 = getInputVal('id');
    var imageFile = document.getElementById('img').files[0];

    //this VAR's are used in 'saveUser()'; function. ---NOT IN USE---
    // unused value=5;  if false value=0; if true value=1
    var isSavedDatabase = false; //  if user data successfully commited to Firebase Database.
    var isSavedImage = false; //  if user image successfully commited to Firebase Storage.

    // Save User
    saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile);

}
    // Function to get get form values
    function getInputVal(id) {
        return document.getElementById(id).value;
    }

    // Save User to firebase
function saveUser(HEfname, HElname, ENfname, ENlname, email, id1, imageFile) {

    // reference to image path in storage 'passportImages/id1' (id1 is current user ID)
    var imageRef = firebase.storage().ref().child('passportImages/' + id1);

    //save User to database
    var newUserRef = databaseRef.child(id1);
    newUserRef.set({
        HEfname: HEfname,
        HElname: HElname,
        ENfname: ENfname,
        ENlname: ENlname,
        email: email,
        id: id1
    }, function (error) {
        if (error) {
            // The write failed
            console.log("User info could not be saved: " + error);
        } else {
            // Data saved successfully!
            isSavedDatabase = true;
            console.log("User info saved successfully!");
            saveImage(imageFile, id1);

            //imageRef.delete(); // remove user image from storage if his info could not be saved t database.
        }
    });

    //save image to storage by ID
    function saveImage(imageFile, id) {
        // Upload file to the object 'passportImages/id1' (id1 is current user ID)
        var uploadTask = firebase.storage().ref().child('passportImages/' + id).put(imageFile);

        // Listen for state changes, errors, and completion of the upload.
        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
            function (snapshot) {
                // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                console.log('Upload is ' + progress + '% done');
                switch (snapshot.state) {
                    case firebase.storage.TaskState.PAUSED: // or 'paused'
                        console.log('Upload is paused');
                        break;
                    case firebase.storage.TaskState.RUNNING: // or 'running'
                        console.log('Upload is running');
                        break;
                }
            }, function (error) {
                databaseRef.child(id).remove(); //remove user info from database if his image could not be uploaded to storage too.
                console.log(error);
                window.alert("Something went wrong, please try again");

                // A full list of error codes is available at
                // https://firebase.google.com/docs/storage/web/handle-errors
                switch (error.code) {
                    case 'storage/unauthorized':
                        // User doesn't have permission to access the object
                        console.log("Image: User doesn't have permission to access the object");
                        break;

                    case 'storage/canceled':
                        // User canceled the upload
                        console.log("Image: User canceled the upload");
                        break;

                    case 'storage/unknown':
                        // Unknown error occurred, inspect error.serverResponse
                        console.log("Image: Unknown error occurred, inspect error.serverResponse");
                        break;
                }
            }, function () {
                // Upload completed successfully!
                isSavedImage = true;
                console.log("Image uploaded successfully!");
                finalCall();
            });
        //if all data commited successfully to Firebase pop a massage and reset form.
        function finalCall() {

            // Show alert
            window.alert("Your info has been sent!");

            // Clear form
            document.forms.RegForm.reset();
        }
    }
    //}
}

Body:
It is probably because you assign the submit type to your button. Your form is probably submitted before the submitForm() method is triggered.

If this assumption is correct, changing the type to button, as follows, should do the trick:

<button type="button" id="submit" onclick="return validation();" href="/">שלח</button>

See the W3 specification for more detail.


问:
After getting all documents in collection can't add field to ArrayList, Android Studio, Java, Firebase Firestore
Hi guys I have a problem as I am getting the whole collection from Firebase Firestore and want get the field "topic name" in each document and add it into an ArrayList to then display this topics in a ListView. It is gonna be a part of Forum part of my application.

BUT!

It seems that it gets the documents, and reads their fields as I can see in the Logs

```<code>Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
</code>```

_

```<code>D/TAG: 6EvC4SqqDxR4TYelLOKM => Topic 1
KpXLBDzSkAb2u96knG8L => Topic 4
SY49j4RqcOI1v79EIVME => Topic 3
xS0Hw4Rj5KPGj1G7vy7T => Topic 2
</code>```

it doesn't add it to the ArrayList or it is in some way gone because the device do not display the list.

At First I thought it is because the ArrayList when it is accessed from within inner class needs to be declared final but that is not the case, as I added a test topics to check that assumption.  (Test Topic 123-Test to Topic 125) and it displays them normally, so that is not the case with ArrayList being final.

I tried putting the whole code responsible for ListView inside the onComplete method but it doesn't seem to work, because the Adapter becomes full of errors, I would like some help if possible or maybe an alternate idea on how to do it. If I replicated the topic I am sorry I tried looking for answer but was unable to find it.

The code is below:

```<code>public class Forum extends Activity {

public static final String TAG = "TAG";
FirebaseFirestore db;

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

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                            Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
                        }

                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    String test_string = "Test Topic 123";
    forumTopics.add(0,test_string);
    forumTopics.add(1,"Test Topic 124");
    forumTopics.add(2,"Test Topic 125");
    forumTopics.add(3,"Test Topic 126");

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
}
</code>```

This is the output on the device

Thank you very much.

答:
I was able to solve the problem with your help below is the solution that worked in my case. Thank you everyone that helped me I am very grateful and may you have wonderful day.        </p>

```<code>    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    final ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                        }
                        ((ArrayAdapter) forumAdapter).notifyDataSetChanged();
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
</code>```

Body:
Hi guys I have a problem as I am getting the whole collection from Firebase Firestore and want get the field "topic name" in each document and add it into an ArrayList to then display this topics in a ListView. It is gonna be a part of Forum part of my application.

BUT!

It seems that it gets the documents, and reads their fields as I can see in the Logs

Log.d(TAG, document.getId() + " => " + document.get("topic_name"));

_

D/TAG: 6EvC4SqqDxR4TYelLOKM => Topic 1
KpXLBDzSkAb2u96knG8L => Topic 4
SY49j4RqcOI1v79EIVME => Topic 3
xS0Hw4Rj5KPGj1G7vy7T => Topic 2

it doesn't add it to the ArrayList or it is in some way gone because the device do not display the list.

At First I thought it is because the ArrayList when it is accessed from within inner class needs to be declared final but that is not the case, as I added a test topics to check that assumption.  (Test Topic 123-Test to Topic 125) and it displays them normally, so that is not the case with ArrayList being final.

I tried putting the whole code responsible for ListView inside the onComplete method but it doesn't seem to work, because the Adapter becomes full of errors, I would like some help if possible or maybe an alternate idea on how to do it. If I replicated the topic I am sorry I tried looking for answer but was unable to find it.

The code is below:

public class Forum extends Activity {

public static final String TAG = "TAG";
FirebaseFirestore db;

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

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                            Log.d(TAG, document.getId() + " => " + document.get("topic_name"));
                        }

                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    String test_string = "Test Topic 123";
    forumTopics.add(0,test_string);
    forumTopics.add(1,"Test Topic 124");
    forumTopics.add(2,"Test Topic 125");
    forumTopics.add(3,"Test Topic 126");

    ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );
}

This is the output on the device

Thank you very much.

Body:
I was able to solve the problem with your help below is the solution that worked in my case. Thank you everyone that helped me I am very grateful and may you have wonderful day.

    db = FirebaseFirestore.getInstance();
    final ArrayList<String> forumTopics = new ArrayList<>();

    final ListAdapter forumAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, forumTopics);
    ListView forumListView =  findViewById(R.id.ForumListView);
    forumListView.setAdapter(forumAdapter);

    db.collection("forum_topics")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    if (task.isSuccessful()) {
                        int count = 0;
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            forumTopics.add(count, document.getString("topic_name"));
                            count += 1;
                        }
                        ((ArrayAdapter) forumAdapter).notifyDataSetChanged();
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });

    forumListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String topic = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(Forum.this, topic, Toast.LENGTH_LONG).show();
                }
            }
    );


问:
How to get latest deployment date of a Function App? Maybe via the Azure REST api?
Like the title says, I need to get the latest deployment date of a function app.
I'm trying different Azure REST calls, but I can't find the right one.
https://learn.microsoft.com/en-us/rest/api/appservice/

For deployment, I mean every time I make a change to the code and re-deploy the Function App.

I'm using Linux/Python environment.

I tried using this GET:

https://learn.microsoft.com/en-us/rest/api/appservice/webapps/listdeployments#code-try-0

But it returns HTML content like:

```<code><html>
<head>
    <title>Your Azure Function App is up and running.</title>
    <style type="text/css">
        @font-face {
            font-family: 'SegoeLight';
...
...
...
</code>```

Which looks like this:

答:
Unfortunately, it's not supported.

Consumption plan

Linux function apps running in the Consumption plan don't have an SCM/Kudu site, which limits the deployment options. However, function apps on Linux running in the Consumption plan do support remote builds.

https://learn.microsoft.com/bs-latn-ba/azure/azure-functions/functions-deployment-technologies

Body:
Like the title says, I need to get the latest deployment date of a function app.
I'm trying different Azure REST calls, but I can't find the right one.
https://learn.microsoft.com/en-us/rest/api/appservice/

For deployment, I mean every time I make a change to the code and re-deploy the Function App.

I'm using Linux/Python environment.

I tried using this GET:

https://learn.microsoft.com/en-us/rest/api/appservice/webapps/listdeployments#code-try-0

But it returns HTML content like:

    <title>Your Azure Function App is up and running.</title>


问:
How to learn tensorflow2.0 quickly and efficiently?
I have mastered the python3 foundation as well as the basic models and algorithms of some neural networks, but I don’t know how to learn tensorflow2.0 package quickly, it’s so messy and lack logic to me to only read the official document. What can I do for systematic learning? Is there any good course video or book for tensorflow2.0. Please recommend it to me. Thanks a lot.</p>

答:
This might be a better question for Quora than StackOverflow. In fact, here is more-or-less the same question on Quora: "What is the most efficient way to learn TensorFlow?". (StackOverflow tends to be less subjective and more technical in nature than general advice.)

The advice I would give though is to try and "do" rather than just learn.

Think of a basic categorization task and do it. Then think about it and your results and try to imagine:

What are the strengths of your approach?

What are the weakenesses to your approach?

By using TensorFlow, you will develop a deeper understanding of what it does. And you will gain real-world experience working with it.


问:
C#/Visual Studio trying to change the content of random array and getting 'Object reference not set to an instance of an object.' error
I am trying to make a tic tac toe game where the user inputs the dimensions and then a board is created with buttons. When a button is clicked, it is disabled and the text inside changes to "X" or "O" accordingly. The user plays against a very basic "AI" which picks the buttons at random.I'm trying to check for empty (enabled) buttons on the board but I get the error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

heres the code:

```<code>public partial class Form1 : Form{
   int num;
   Button[,] buttonspinak;
   private void button2_Click(object sender, EventArgs e)
        {
            int start = 180, end = 30;

            num = Convert.ToInt32(textBox1.Text);
            buttonspinak = new Button[num, num];

                for (int i = 0; i < num; i++)
                {
                    end += 80;
                    start = 180;

                    for (int j = 0; j < num; j++)
                    {
                        Button b = new Button();
                        b.Size = new Size(60, 60);
                        b.Location = new Point(start, end);
                        this.Controls.Add(b);
                        start += 80;
                        b.BackColor = Color.White;
                        buttonspinak[i, j] = b;
                        b.Click += new EventHandler(Computer2);
                        Computer(sender, e);

                    }
                }
            }
   int countercomputer;
        Random randcompu = new Random();
        private void Computer(object sender, EventArgs e)
        {
            int randomi = 0;
            int randomj = 0;
            Button b = (Button)sender;
            b.Enabled = false;
            randomi = randcompu.Next(0, num);
            randomj = randcompu.Next(0, num);
            **while (buttonspinak[randomi, randomj].Text == "O" || buttonspinak[randomi, randomj].Text == "X")** // this is the line where i get the error
            {
                randomi = randcompu.Next(0, num);
                randomj = randcompu.Next(0, num);
                //buttonspinak[randomi, randomj].Text = "C";
            }
            buttonspinak[randomi, randomj].Text = "O";
            b_Elegxos();

        }
private void Computer2(object sender, EventArgs e)
    {
        countercomputer++;
        Button b = (Button)sender;
        b.Enabled = false;
        if (countercomputer % 2 != 0)
        {
            b.Text = "X";
            b.ForeColor = Color.DarkRed;
        }
        b_Elegxos();

    }
}
</code>```

答:
You seem to call Computer() in each iteration of your nested for loop in the button2_Click handler.

This means that, after only initializing buttonspinak[0,0] with a new Button, Computer() gets called, which picks a random position in buttonspinak and tries to get that element's Text. But, most likely, that position in the array isn't initialized yet, so you're trying to call .Text on a null reference, resulting in your exception.

You should in stead call Computer() after the for loops in button2_Click, so you can be sure all positions in buttonspinak are initialized.

Body:
I am trying to make a tic tac toe game where the user inputs the dimensions and then a board is created with buttons. When a button is clicked, it is disabled and the text inside changes to "X" or "O" accordingly. The user plays against a very basic "AI" which picks the buttons at random.I'm trying to check for empty (enabled) buttons on the board but I get the error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

heres the code:

public partial class Form1 : Form{
   int num;
   Button[,] buttonspinak;
   private void button2_Click(object sender, EventArgs e)
        {
            int start = 180, end = 30;

            num = Convert.ToInt32(textBox1.Text);
            buttonspinak = new Button[num, num];

                for (int i = 0; i < num; i++)
                {
                    end += 80;
                    start = 180;

                    for (int j = 0; j < num; j++)
                    {
                        Button b = new Button();
                        b.Size = new Size(60, 60);
                        b.Location = new Point(start, end);
                        this.Controls.Add(b);
                        start += 80;
                        b.BackColor = Color.White;
                        buttonspinak[i, j] = b;
                        b.Click += new EventHandler(Computer2);
                        Computer(sender, e);

                    }
                }
            }
   int countercomputer;
        Random randcompu = new Random();
        private void Computer(object sender, EventArgs e)
        {
            int randomi = 0;
            int randomj = 0;
            Button b = (Button)sender;
            b.Enabled = false;
            randomi = randcompu.Next(0, num);
            randomj = randcompu.Next(0, num);
            **while (buttonspinak[randomi, randomj].Text == "O" || buttonspinak[randomi, randomj].Text == "X")** // this is the line where i get the error
            {
                randomi = randcompu.Next(0, num);
                randomj = randcompu.Next(0, num);
                //buttonspinak[randomi, randomj].Text = "C";
            }
            buttonspinak[randomi, randomj].Text = "O";
            b_Elegxos();

        }
private void Computer2(object sender, EventArgs e)
    {
        countercomputer++;
        Button b = (Button)sender;
        b.Enabled = false;
        if (countercomputer % 2 != 0)
        {
            b.Text = "X";
            b.ForeColor = Color.DarkRed;
        }
        b_Elegxos();

    }
}


问:
Stopped maven install
I am testing a spring boot project with it default pom.xml like that.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>
```

<p>When I am trying to run the command <code>mvn clean install</code> the below two exceptions ProjectBuildingException and UnresolvableModelException appeared like below</p>

<pre class="lang-none prettyprint-override"><code>[INFO] Scanning for projects...
Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.example:demo:0.0.1-SNAPSHOT (C:\Users\User\Desktop\demo\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.240.215] failed: Connection timed out: connect -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

答:
Remove relativePath from parent tag</p>

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
</parent>
</code>```

Title: Stopped maven install

Body:
I am testing a spring boot project with it default pom.xml like that.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>

When I am trying to run the command mvn clean install the below two exceptions ProjectBuildingException and UnresolvableModelException appeared like below

[INFO] Scanning for projects...
Downloading from central: https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project com.example:demo:0.0.1-SNAPSHOT (C:\Users\User\Desktop\demo\pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for com.example:demo:0.0.1-SNAPSHOT: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.2.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): Transfer failed for https://repo.maven.apache.org/maven2/org/springframework/boot/spring-boot-starter-parent/2.2.4.RELEASE/spring-boot-starter-parent-2.2.4.RELEASE.pom and 'parent.relativePath' points at no local POM @ line 5, column 10: Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.240.215] failed: Connection timed out: connect -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

Body:
Remove relativePath from parent tag

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.4.RELEASE</version>
</parent>


问:
How to use concatenated multiple rows of TEXT to update another TEXT column in SQL Server 2000?
I have a problem I'm trying to solve and a solution is not readily apparent. Since I cannot use temporary variables of type Text, I am having some trouble getting this figured out.

First table (DocumentChunks) has two columns - DocumentID (int - foreign key) and TextChunk (Text)

Second table (Document) has many columns including DocumentID (int - primary key) and DocumentText (Text)

Document <-> DocumentChunks is a one-to-many relationship.

I need to concat all the TextChunk values together with a carriage return line feed after each, and use that to update the corresponding DocumentText column in the Document table.

I've seen plenty of example using temporary variables, but I can't use them.

All suggestions are appreciated!

答:
Well you could attempt a scalar function. Use this in your update query like:

```<code>SET DocumentText=fn_ConcatTextChunks(Document.DocumentID)
</code>```

The only problem is that you can't use a text return type or local variables in SQL Server 2000 in a scalar function. So if your data is too large, this won't work.

```<code>CREATE FUNCTION [dbo].[fn_ContatTextChunks]
(
    @DocumentID int
)
RETURNS varchar(8000)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result varchar(8000)

    SELECT @Result = COALESCE(@Result + '\n', '') + CAST(dc.TextChunk As varchar)
    FROM DocumentChunks dc
    WHERE dc.DocumentID=@DocumentID

    -- Return the result of the function
    IF @Result IS NULL BEGIN
        SET @Result = ''
    END
    RETURN @Result
END
</code>```

but I suppose it's worth a shot.

Body:
Well you could attempt a scalar function. Use this in your update query like:

SET DocumentText=fn_ConcatTextChunks(Document.DocumentID)

The only problem is that you can't use a text return type or local variables in SQL Server 2000 in a scalar function. So if your data is too large, this won't work.

CREATE FUNCTION [dbo].[fn_ContatTextChunks]
(
    @DocumentID int
)
RETURNS varchar(8000)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result varchar(8000)

    SELECT @Result = COALESCE(@Result + '\n', '') + CAST(dc.TextChunk As varchar)
    FROM DocumentChunks dc
    WHERE dc.DocumentID=@DocumentID

    -- Return the result of the function
    IF @Result IS NULL BEGIN
        SET @Result = ''
    END
    RETURN @Result
END

but I suppose it's worth a shot.


问:
What is a cluster and a node oriented to containers?
Sorry for this question, but I just started with Docker and Docker Compose and I really didn't need any of this until I read that I need to use Docker Swarn or Kuebernetes to have more stability in production. I started reading about Docker Swarn and they mentioned nodes and clusters.

I was really happy not knowing about this as I understood docker-compose:

Is that I could manage my services/containers from a single file
  and only have to run several commands to launch, build, delete, etc.
  all my services based on the docker-compose configuration.

But now the nodes and cluster have come out and I've really gone a bit crazy, and that's why if you can help me understand this next step in the life of containers. I've been googling and it's not very clear to me.

I hope you can help me and explain it to me in a way that I can understand.

Thank you!

答:
A node is just a physical or virtual machine.

In Kubernetes/Docker Swarm context each node must have the relevant binaries installed (Docker Engine, kubelet etc..)

A cluster is a grouping of one or more nodes.

If you have just been testing on your local machine you have a single node.

If you were to add a second machine and link both machines together using docker swarm/kubernetes then you would have created a 2 node cluster

You can then use docker swarm/kubernetes to run your services/containers on any or all nodes in your cluster. This allows your services to be more resilient and fault tolerant.


问:
ASP.Net Core 2.2 or 3.1 SPA with React and Docker
I am trying two days already to containerize ASP.NET Core 2.2, but without any luck, I have read most than 20 articles about it, and I am not sure if it is even possible. It leads me to an error page stating that it cannot find npm and to check if it exists and is added to PATH.

I tried adding this

```<code>RUN apt-get install --yes curl
RUN curl --silent --location https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install --yes nodejs
</code>```

to the dockerfile, also added **/node_modules to the .dockerignore file as I read in the articles but without luck

Read that someone has succeeded on .NET Core 2.1, but I haven't tried it because it won't work for me. Can someone please share if it is possible with dot net core 2.2 or above, I can settle for 2.2, 3.0, 3.1.

答:
I finally managed to do it.

the trick was to use another image (node:13-alpine) to do the npm install and to add a condition in the .cproj file for the publish part.

It is explained better in this article:

Link

Body:
I am trying two days already to containerize ASP.NET Core 2.2, but without any luck, I have read most than 20 articles about it, and I am not sure if it is even possible. It leads me to an error page stating that it cannot find npm and to check if it exists and is added to PATH.

I tried adding this

RUN apt-get install --yes curl
RUN curl --silent --location https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install --yes nodejs

to the dockerfile, also added **/node_modules to the .dockerignore file as I read in the articles but without luck

Read that someone has succeeded on .NET Core 2.1, but I haven't tried it because it won't work for me. Can someone please share if it is possible with dot net core 2.2 or above, I can settle for 2.2, 3.0, 3.1.


问:
How to set fixed Icon size that scales with HiDPI in Qt
How can I set Icon size in my application so that it's still scaled when the users uses Screen Scaling?

In my application I have a QToolBar in the MainWindow that seems to use an Icon size of 24x24. I have some QToolButton which seem to get an Icon size of 20x20 by default, so I had to manually set it to 24x24 in order to have all Icons with same size, with setIconSize(QSize(24, 24));. Works fine without scaling:

When the Desktop has some scaling enabled, the Icons with the Fixed size don't get scaled, this looks then like this:

Another use case that I have is showing Icons in QLabels, there I have to specify the size when converting QIcon to QPixmap, this also doesn't scale mImageLabel->setPixmap(icon().pixmap(QSize(24, 24)));

Is there any better why then multiplying with the scale factor? How to get the scale factor?

答:
It looks like setting the fixed size prevents any scaling from Qt side so we need to manually adjust the size. In my case it seems that I can get the correct scale factor by dividing the logicalDpi by 96, which is the DPI with scaling factor 1. I'm not sure if this is the best solution for all uses cases (haven't tested against MacOS for example) but fixes my use case.

I wrote a simple class that scales all my fixed size to the correct value:

```<code>#include <QApplication>
#include <QDesktopWidget>

QSize ScaledSizeProvider::getScaledSize(const QSize &size)
{
    return {static_cast<int>(size.width() * getXScaleFactor()), static_cast<int>(size.height() * getYScaleFactor())};
}

qreal ScaledSizeProvider::getXScaleFactor()
{
    auto desktopWidget = QApplication::desktop();
    return desktopWidget->logicalDpiX() / getReferenceDpiValue();
}
qreal ScaledSizeProvider::getYScaleFactor()
{
    auto desktopWidget = QApplication::desktop();
    return desktopWidget->logicalDpiY() / getReferenceDpiValue();
}

qreal ScaledSizeProvider::getReferenceDpiValue()
{
    return 96.0;
}
</code>```

And the simple fetch the correct value with:

```<code>ScaledSizeProvider::getScaledSize(QSize(24, 24))
</code>```

Body:
It looks like setting the fixed size prevents any scaling from Qt side so we need to manually adjust the size. In my case it seems that I can get the correct scale factor by dividing the logicalDpi by 96, which is the DPI with scaling factor 1. I'm not sure if this is the best solution for all uses cases (haven't tested against MacOS for example) but fixes my use case.

I wrote a simple class that scales all my fixed size to the correct value:

#include <QApplication>
#include <QDesktopWidget>

QSize ScaledSizeProvider::getScaledSize(const QSize &size)
{
    return {static_cast<int>(size.width() * getXScaleFactor()), static_cast<int>(size.height() * getYScaleFactor())};
}

qreal ScaledSizeProvider::getXScaleFactor()
{
    auto desktopWidget = QApplication::desktop();
    return desktopWidget->logicalDpiX() / getReferenceDpiValue();
}
qreal ScaledSizeProvider::getYScaleFactor()
{
    auto desktopWidget = QApplication::desktop();
    return desktopWidget->logicalDpiY() / getReferenceDpiValue();
}

qreal ScaledSizeProvider::getReferenceDpiValue()
{
    return 96.0;
}

And the simple fetch the correct value with:

ScaledSizeProvider::getScaledSize(QSize(24, 24))