问:
Selenium doesn't seem to work on this website. Why is that? What can I do?
I need to automate a procedure with selenium on the website Plus500, but I can't even get to log in. I just get the TimeoutException without being able to locate the part of the page where I need to enter my credentials.
This is the code that I'm using for the log in but I fear the problem is a more general one. Does anyone know why is this happening?</p>

```<code>driver.execute_script("window.open('https://app.plus500.com/trade?refurl=https%3A%2F%2Fwww.google.com%2F&innerTags=_cc_%20exp_new_sas_c&webvisitid=2a3139bc-78f7-4f48-a50d-c79e7b3e7abd&page=login&_ga=2.24870842.1255829517.1590833562-259196075.1590833562', 'new window')")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="email"]'))).send_keys('myemail')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="password"]'))).send_keys('mypassword')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH, '//*[@id="submitLogin"]'))).click()
</code>```

答:
You need to tell selenium which tab it should consider active, opening a new tab does not change the active tab in selenium's perspective. There are multiple options to achieve this, like described in this answer.

Basically you need to add this extra line after opening a new tab: driver.switch_to.window(driver.window_handles[-1]) and selenium will know that you want it to execute commands on the last tab in the browser.

So the fixed code is:

driver.execute_script("window.open('https://app.plus500.com/trade?refurl=https%3A%2F%2Fwww.google.com%2F&innerTags=_cc_%20exp_new_sas_c&webvisitid=2a3139bc-78f7-4f48-a50d-c79e7b3e7abd&page=login&_ga=2.24870842.1255829517.1590833562-259196075.1590833562', 'new window')")
driver.switch_to.window(driver.window_handles[-1])
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="email"]'))).send_keys('myemail')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="password"]'))).send_keys('mypassword')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH, '//*[@id="submitLogin"]'))).click()
```

Body:
I need to automate a procedure with selenium on the website Plus500, but I can't even get to log in. I just get the TimeoutException without being able to locate the part of the page where I need to enter my credentials.
This is the code that I'm using for the log in but I fear the problem is a more general one. Does anyone know why is this happening?

driver.execute_script("window.open('https://app.plus500.com/trade?refurl=https%3A%2F%2Fwww.google.com%2F&innerTags=_cc_%20exp_new_sas_c&webvisitid=2a3139bc-78f7-4f48-a50d-c79e7b3e7abd&page=login&_ga=2.24870842.1255829517.1590833562-259196075.1590833562', 'new window')")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="email"]'))).send_keys('myemail')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH,'//*[@id="password"]'))).send_keys('mypassword')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
        (By.XPATH, '//*[@id="submitLogin"]'))).click()


来源: stackexchange

问:
How to create a rectangle that exactly fills the device screen
I'm trying to create a Rectangle that fills the device's screen. I've tried this:

```<code>Rectangle()
            .fill(Color.green)
            .frame( height: UIScreen.main.bounds.size.height)
            .frame( width: UIScreen.main.bounds.size.width)
            .edgesIgnoringSafeArea(.all)

</code>```

Using this extension:

```<code>extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}
</code>```

However, the height is slightly too small:

and I'm not sure why.

答:
If you are filling the screen why not just set the Color of the View?

```<code>struct ContentView: View {
    var body: some View {
        Color.green
            .edgesIgnoringSafeArea(.all)
    }
}
</code>```

And you can stack other Views on top of that using a ZStack:

```<code>struct ContentView: View {
    var body: some View {
        ZStack {
            Color.green
                .edgesIgnoringSafeArea(.all)

            // Other Views on top here
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create a Rectangle that fills the device's screen. I've tried this:

Rectangle()
            .fill(Color.green)
            .frame( height: UIScreen.main.bounds.size.height)
            .frame( width: UIScreen.main.bounds.size.width)
            .edgesIgnoringSafeArea(.all)

Using this extension:

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}

However, the height is slightly too small:

and I'm not sure why.

Body:
If you are filling the screen why not just set the Color of the View?

struct ContentView: View {
    var body: some View {
        Color.green
            .edgesIgnoringSafeArea(.all)
    }
}

And you can stack other Views on top of that using a ZStack:

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.green
                .edgesIgnoringSafeArea(.all)

            // Other Views on top here
        }
    }
}


问:
Android NDK: Assertion failure: LOCAL_MAKEFILE is not defined
I was trying to build a project and when I execute a gradle task to build, I'm receiving the folllow error:

```<code>~/Library/Android/sdk/ndk/21.2.6472646/build/core/prebuilt-library.mk:20: *** Android NDK:  Assertion failure: LOCAL_MAKEFILE is not defined    .  Stop.
</code>```

I never used NDK before, and I'm not sure where I need to start.

Apparently LOCAL_MAKEFILE is not defined, but where should I define it?

Follows below, line 20 of prebuilt-library file:

```<code>    15
    16  # this file is included from prebuilt-shared-library.mk or
    17  # prebuilt-static-library.mk to declare prebuilt library binaries.
    18  #
    19
    20  $(call assert-defined, LOCAL_BUILD_SCRIPT LOCAL_MAKEFILE LOCAL_PREBUILT_PREFIX LOCAL_PREBUILT_SUFFIX)
    21
    22  $(call check-defined-LOCAL_MODULE,$(LOCAL_BUILD_SCRIPT))
    23  $(call check-LOCAL_MODULE,$(LOCAL_MAKEFILE))
    24  $(call check-LOCAL_MODULE_FILENAME)
    25
</code>```

Somebody have any idea what's going on?

Every help is welcome!

Thanks for now!

答:
On NDK r21d the same error. Thanks Dan Albert for the patch.
This fixes the error:

in build/core/definitions.mk change the line:

```<code>local-makefile = $(lastword $(filter %Android.mk,$(MAKEFILE_LIST)))
</code>```

to

```<code>_last_android_mk = $(lastword $(filter %Android.mk,$(MAKEFILE_LIST)))
_last_non_ndk_makefile = $(lastword $(filter-out $(NDK_ROOT)%,$(MAKEFILE_LIST)))
local-makefile = $(if $(_last_android_mk),$(_last_android_mk),$(_last_non_ndk_makefile))
</code>```

Body:
I was trying to build a project and when I execute a gradle task to build, I'm receiving the folllow error:

~/Library/Android/sdk/ndk/21.2.6472646/build/core/prebuilt-library.mk:20: *** Android NDK:  Assertion failure: LOCAL_MAKEFILE is not defined    .  Stop.

I never used NDK before, and I'm not sure where I need to start.

Apparently LOCAL_MAKEFILE is not defined, but where should I define it?

Follows below, line 20 of prebuilt-library file:

    15
    16  # this file is included from prebuilt-shared-library.mk or
    17  # prebuilt-static-library.mk to declare prebuilt library binaries.
    18  #
    19
    20  $(call assert-defined, LOCAL_BUILD_SCRIPT LOCAL_MAKEFILE LOCAL_PREBUILT_PREFIX LOCAL_PREBUILT_SUFFIX)
    21
    22  $(call check-defined-LOCAL_MODULE,$(LOCAL_BUILD_SCRIPT))
    23  $(call check-LOCAL_MODULE,$(LOCAL_MAKEFILE))
    24  $(call check-LOCAL_MODULE_FILENAME)
    25

Somebody have any idea what's going on?

Every help is welcome!

Thanks for now!

Body:
On NDK r21d the same error. Thanks Dan Albert for the patch.
This fixes the error:

in build/core/definitions.mk change the line:

local-makefile = $(lastword $(filter %Android.mk,$(MAKEFILE_LIST)))

to

_last_android_mk = $(lastword $(filter %Android.mk,$(MAKEFILE_LIST)))
_last_non_ndk_makefile = $(lastword $(filter-out $(NDK_ROOT)%,$(MAKEFILE_LIST)))
local-makefile = $(if $(_last_android_mk),$(_last_android_mk),$(_last_non_ndk_makefile))


问:
page method question
I'm building an asp.net page that uses a page method call from jquery. This is a simple test page but I can't get it to work and I can't see why.

I added a script manager to the aspx. Here's the javascript function:

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

    function CallGetLoaded() {

        var ConfirmLoad = "test string";

        $.ajax({
            type: "POST",
            url: "../Pages/TestPage.aspx/GetLoaded",
            data: ConfirmLoad,
            contentType: "application/text; charset=utf-8",
            dataType: "text",
            success: successLoadLeads,
            error: errorLoadLeads
        });

    };

    function successLoadLeads(thereturn) { alert((thereturn)); };
    function errorLoadLeads() { alert("problem getting return"); };

</script>
</code>```

And here's the full code behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Web.Services;

public partial class Pages_TestPage : System.Web.UI.Page
{

    [WebMethod]
    public static string GetLoaded(string ConfirmLoad)
    {

        string ResultString = "got test";

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

Instead of getting back a simple string in the alert popup, I'm sometimes getting back the HTML of the whole page and sometimes the error function; not sure why it varies.
What am I missing?

Thanks for your suggestions.

答:
I have made some small changes to your code.

Changed your contentType, data and dataType of your $.ajax request

Changed your onsuccess handler to check for .hasOwnProperty("d")

Changed your onerror handler so that you may see what the actual error is.

I strongly believe that you had a parse error since you used text for parsing and retrieving.

Here is a sample done from your code that works.

The MarkUp

```<code><asp:Button ID="testclick" runat="server" Text="Click Me"/>
</code>```

The Scripts

```<code>$(function () {
    $('#testclick').click(function (e) {
        CallGetLoaded();
        e.preventDefault();
    });
});

function CallGetLoaded() {

    var ConfirmLoad = "test string";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestPage.aspx/Getloaded",
        data: "{'ConfirmLoad':'" + ConfirmLoad + "'}",
        dataType: "json",
        success: function (msg) {
            var data = msg.hasOwnProperty("d") ? msg.d : msg;
            OnSucessCallBack(data);
        },
        error: function (xhr, status, error) {
            alert(xhr.statusText);
        }
    });

};

function OnSucessCallBack(data) {
    alert(data);
}
</code>```

The Code-Behind

```<code>[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
    string ResultString = "got test";
    return ResultString;
}
</code>```

P.S: As FiveTools have correctly pointed out,

url:"../Pages/TestPage.aspx/Getloaded" is unnecessary. url:"TestPage.aspx/Getloaded" will do.

ContentLicense: CC BY-SA 3.0

Title: page method question

Body:
I'm building an asp.net page that uses a page method call from jquery. This is a simple test page but I can't get it to work and I can't see why.

I added a script manager to the aspx. Here's the javascript function:

And here's the full code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Web.Services;

public partial class Pages_TestPage : System.Web.UI.Page
{

    [WebMethod]
    public static string GetLoaded(string ConfirmLoad)
    {

        string ResultString = "got test";

        return ResultString;
    }
}

Instead of getting back a simple string in the alert popup, I'm sometimes getting back the HTML of the whole page and sometimes the error function; not sure why it varies.
What am I missing?

Thanks for your suggestions.

Body:
I have made some small changes to your code.

Changed your contentType, data and dataType of your $.ajax request

Changed your onsuccess handler to check for .hasOwnProperty("d")

Changed your onerror handler so that you may see what the actual error is.

I strongly believe that you had a parse error since you used text for parsing and retrieving.

Here is a sample done from your code that works.

The MarkUp

<asp:Button ID="testclick" runat="server" Text="Click Me"/>

The Scripts

$(function () {
    $('#testclick').click(function (e) {
        CallGetLoaded();
        e.preventDefault();
    });
});

function CallGetLoaded() {

    var ConfirmLoad = "test string";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestPage.aspx/Getloaded",
        data: "{'ConfirmLoad':'" + ConfirmLoad + "'}",
        dataType: "json",
        success: function (msg) {
            var data = msg.hasOwnProperty("d") ? msg.d : msg;
            OnSucessCallBack(data);
        },
        error: function (xhr, status, error) {
            alert(xhr.statusText);
        }
    });

};

function OnSucessCallBack(data) {
    alert(data);
}

The Code-Behind

[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
    string ResultString = "got test";
    return ResultString;
}

P.S: As FiveTools have correctly pointed out,

url:"../Pages/TestPage.aspx/Getloaded" is unnecessary. url:"TestPage.aspx/Getloaded" will do.


问:
Get the last entered id from a table in sql
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

```<code>SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id
</code>```

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

答:
last taken loan value and date

You seem to want:

```<code>SELECT sr.*
FROM single_roww1 sr
WHERE sr.loan_date = (SELECT MAX(sr2.load_date)
                      FROM single_roww1 sr2
                      WHERE sr2.employee_id = sr.employee_id
                     );
</code>```

This assumes shat loan_date has a proper date/time type in the database (despite what the data in the image looks like).

For performance, you want an index on (employee_id, load_date).

Note that if an employee has multiple loans on the same date, this will retrieve the last one.

Body:
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

Body:
last taken loan value and date

You seem to want:

SELECT sr.*
FROM single_roww1 sr
WHERE sr.loan_date = (SELECT MAX(sr2.load_date)
                      FROM single_roww1 sr2
                      WHERE sr2.employee_id = sr.employee_id
                     );

This assumes shat loan_date has a proper date/time type in the database (despite what the data in the image looks like).

For performance, you want an index on (employee_id, load_date).

Note that if an employee has multiple loans on the same date, this will retrieve the last one.


问:
All c# project was unloaded
I encountered this error

after cloned my project.

i tried to reload the project but it didn't work.

how to resolve this?

答:
i solved the problem, by matching my current sdk version in global.json

this are my procedure,

Result

Title: All c# project was unloaded


问:
Storing the values of a column of a data.frame after removing the name in R
I want to store the values of a  column of a data.frame after removing the name in a vector. I tried the following code, but it did not work. It shows me that the type of 'my_vector' is data.frame. I would like to know why the type is data.frame and how to do it. Here is my code:</p>

```<code>my_vector <- as.vector(unname(my_data.frame[column]))
</code>```

答: The typical way to do this in R is my_vector <- my_data.frame[[column]]

Body:
I want to store the values of a  column of a data.frame after removing the name in a vector. I tried the following code, but it did not work. It shows me that the type of 'my_vector' is data.frame. I would like to know why the type is data.frame and how to do it. Here is my code:

my_vector <- as.vector(unname(my_data.frame[column]))


问:
how to get rid of default apache page "it works!"?
I created a virtual host on MAMP PRO 5 like this "mywebsite.test"   but it does not open the local site unless I add :8888 so it has to be like this "mywebsite.test:8888" then I changed the Apache port to 80 and whenever I try to get them to local site using "mywebsite.test"  is show me the default page of apache "it works!" instead.

I did uncomment this line

```<code># Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf
</code>```

in

```<code>/private/etc/apache2/httpd.conf
</code>```

but still not working
any solution?

答:
I just found the solution this could be helpful to anyone facing this same problem.
After contacting the support they told me to check indexes under Apache tab and it works

make sure the Apache port is at 80 and not 8888

Body:
I created a virtual host on MAMP PRO 5 like this "mywebsite.test"   but it does not open the local site unless I add :8888 so it has to be like this "mywebsite.test:8888" then I changed the Apache port to 80 and whenever I try to get them to local site using "mywebsite.test"  is show me the default page of apache "it works!" instead.

I did uncomment this line

# Virtual hosts
#Include /private/etc/apache2/extra/httpd-vhosts.conf

in

/private/etc/apache2/httpd.conf

but still not working
any solution?


问:
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0
I'm quite new to Locust, just started tinkering with it a couple of days ago.
To quick start, i was following someone else example as below,
file : locustfile.py

```<code>import random
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before
            any task is scheduled
        """
        self.login()
    def login(self):
        self.client.post("/login",
                         {"username":"ellen_key",
                          "password":"education"})
    @task(2)
    def index(self):
        self.client.get("/")
    @task(1)
    def profile(self):
        self.client.get("/profile")
class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000
</code>```

When i run locust from the current directory, i am getting the below exception,

```<code>Traceback (most recent call last):
  File "/usr/local/bin/locust", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 113, in main
    docstring, user_classes = load_locustfile(locustfile)
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 77, in load_locustfile
    imported = __import_locustfile__(locustfile, path)
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 53, in __import_locustfile__
    return  source.load_module()
  File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 823, in load_module
  File "<frozen importlib._bootstrap_external>", line 682, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 684, in _load
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/koushic/kk-ldl/locust/locustfile.py", line 19, in <module>
    class WebsiteUser(HttpLocust):
  File "/usr/local/lib/python3.6/dist-packages/locust/util/deprecation.py", line 23, in __new__
    raise ImportError(deprecation_message)
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0
</code>```

Could someone help me to understand the issue here.

```<code>Python 3.6.9
pip 20.1.1
</code>```

答:
Just check the last line of the error message:

```<code>ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0
</code>```

If you're lucky all you'll need to do is change these two lines:

from locust import HttpUser, TaskSet, task

class WebsiteUser(HttpUser):

Body:
I'm quite new to Locust, just started tinkering with it a couple of days ago.
To quick start, i was following someone else example as below,
file : locustfile.py

import random
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before
            any task is scheduled
        """
        self.login()
    def login(self):
        self.client.post("/login",
                         {"username":"ellen_key",
                          "password":"education"})
    @task(2)
    def index(self):
        self.client.get("/")
    @task(1)
    def profile(self):
        self.client.get("/profile")
class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000

When i run locust from the current directory, i am getting the below exception,

Traceback (most recent call last):
  File "/usr/local/bin/locust", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 113, in main
    docstring, user_classes = load_locustfile(locustfile)
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 77, in load_locustfile
    imported = __import_locustfile__(locustfile, path)
  File "/usr/local/lib/python3.6/dist-packages/locust/main.py", line 53, in __import_locustfile__
    return  source.load_module()
  File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 823, in load_module
  File "<frozen importlib._bootstrap_external>", line 682, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 684, in _load
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/koushic/kk-ldl/locust/locustfile.py", line 19, in <module>
    class WebsiteUser(HttpLocust):
  File "/usr/local/lib/python3.6/dist-packages/locust/util/deprecation.py", line 23, in __new__
    raise ImportError(deprecation_message)
ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0

Could someone help me to understand the issue here.

Python 3.6.9
pip 20.1.1

Body:
Just check the last line of the error message:

ImportError: The HttpLocust class has been renamed to HttpUser in version 1.0. For more info see: https://docs.locust.io/en/latest/changelog.html#changelog-1-0

If you're lucky all you'll need to do is change these two lines:

from locust import HttpUser, TaskSet, task

class WebsiteUser(HttpUser):


问:
Redis sentinel vs clustering
I understand redis sentinel is a way of configuring HA (high availability) among multiple redis instances. As I see, there is one redis instance actively serving the client requests at any given time. There are two additional servers are on standby (waiting for a failure to happen, so one of them can be in action again).

Is it waste of resources?

Is there a better way of using full use of the resources available?

Is Redis clustering an alternative to Redis sentinel?

I already looked up redis documentation for sentinel and clustering, can somebody having experience explain please.

UPDATE

OK. In my real deployment scenario I have two servers dedicated for redis. I have another server my Jboss server is running. The application running in Jboss is configured to connect to redis master server(M).

Failover scenario

Ideally, I think when Master cache server fails (either Redis process goes down or machine failure) the application in Jboss needs to connect to Slave cache server. How would I configure the redis servers to achieve this?

```<code>+--------+          +--------+
| Master  |---------| Slave  |
|         |         |        |
+--------+          +--------+

Configuration: quorum = 1
</code>```

答:
Additional info to above answers

Redis Cluster

One main purpose of the Redis cluster is to equally/uniformly distribute
your data load by sharding

Redis Cluster does not use consistent hashing, but a different form of sharding where every key is conceptually part of what is called as hash slot

There are 16384 hash slots in Redis Cluster, Every node in a Redis Cluster is responsible for a subset of the hash slots, so, for example, you may have a cluster with 3 nodes,
where:

Node A contains hash slots from 0 to 5500,
Node B contains hash slots from 5501 to 11000,
Node C contains hash slots from 11001 to 16383

This allows us to add and remove nodes in the cluster easily. For example, if we want to add a new node D, we need to move some hash slot from nodes A, B, C to D

Redis cluster supports the master-slave structure, you can create slaves A1,B1, C2 along with master A, B, C when  creating a cluster, so when master B goes down slave B1 gets promoted as master

You don't need additional failover handling when using Redis Cluster and you should definitely not point Sentinel instances at any of the Cluster nodes.

So in practical terms, what do you get with Redis Cluster?

1.The ability to automatically split your dataset among multiple nodes.

2.The ability to continue operations when a subset of the nodes are experiencing failures or are unable to communicate with the rest of the cluster.

Redis Sentinel

Redis supports multiple slaves replicating data from a master node.

This provides a backup for data in master node.

Redis Sentinel is a system designed to manage master and slave. It runs as separate program. The minimum number of sentinels required in an ideal system is 3. They communicate among themselves and make sure that the Master is alive, if not alive they will promote one of the slaves as master, so later when the dead node spins up it will be acting as a slave for the new master

Quorum is configurable. Basically it is the number of sentinels that need to agree as the master is down. N/2 +1 should agree. N is the number of nodes in the Pod (note this setup is called a pod and is not a cluster)

So in practical terms, what do you get with Redis Sentinel?

It will make sure that Master is always available (if master goes down, the slave will be promoted as master)

Reference :

https://fnordig.de/2015/06/01/redis-sentinel-and-redis-cluster/

https://redis.io/topics/cluster-tutorial

Title: Redis sentinel vs clustering

Body:
I understand redis sentinel is a way of configuring HA (high availability) among multiple redis instances. As I see, there is one redis instance actively serving the client requests at any given time. There are two additional servers are on standby (waiting for a failure to happen, so one of them can be in action again).

Is it waste of resources?

Is there a better way of using full use of the resources available?

Is Redis clustering an alternative to Redis sentinel?

I already looked up redis documentation for sentinel and clustering, can somebody having experience explain please.

UPDATE

OK. In my real deployment scenario I have two servers dedicated for redis. I have another server my Jboss server is running. The application running in Jboss is configured to connect to redis master server(M).

Failover scenario

Ideally, I think when Master cache server fails (either Redis process goes down or machine failure) the application in Jboss needs to connect to Slave cache server. How would I configure the redis servers to achieve this?

+--------+          +--------+
| Master  |---------| Slave  |
|         |         |        |
+--------+          +--------+

Configuration: quorum = 1


问:
How to save & retrive image to/from mysql?
Two part quersion.

Part 1:

Im uploading an image to my server and want to save it to my database.

So far:

table:

resolver:

```<code>registerPhoto: inSequence([
  async (obj, { file }) => {
    const { filename, mimetype, createReadStream } = await file;
    const stream = createReadStream();

    const t = await db.images.create({
      Name: 'test',
      imageData: stream ,
    });
  },
])
</code>```

executing query:

```<code>Executing (default): INSERT INTO `images` (`Id`,`imageData`,`Name`) VALUES (DEFAULT,?,?);
</code>```

But nothing is saved.

Im new to this and im probably missing something but dont know what.

Part2:

This is followed by part 1, lets say I manage to save the image, how do I read it and send it back to my FE?

An edit: Ive read alot of guides saving the an image name to the db and then tha actuall image in a folder. This is NOT what im after, want to save the image to the DB and then be able to fetch it from the DB abd present it.

答:
This took me some time but I finaly figured it out.

First step (saving to the db):

Have to get the entire stream data and read it like this:

```<code>export const readStream = async (stream, encoding = 'utf8') => {
  stream.setEncoding('base64');

  return new Promise((resolve, reject) => {
    let data = '';

    // eslint-disable-next-line no-return-assign
    stream.on('data', chunk => (data += chunk));
    stream.on('end', () => resolve(data));
    stream.on('error', error => reject(error));
  });
};
</code>```

use like this:

```<code>const streamData = await readStream(stream);
</code>```

Before saving I tur the stream into a buffer:

```<code>const buff = Buffer.from(streamData);
</code>```

Finaly the save part:

```<code>db.images.create(
            {
              Name: filename,
              imageData: buff,
              Length: stream.bytesRead,
              Type: mimetype,
            },
            { transaction: param }
          );
</code>```

Note that I added Length and Type parameter, this is needed if you like to return a stream when you return the image.

Step 2 (Retrieving the image).

As @xadm said multiple times you can not return an image from GRAPHQL and after some time I had to accept that fact, hopefully graphql will remedy this in the future.

S What I needed to do is set up a route on my fastify backend, send a image Id to this route, fetch the image and then return it.

I had a few diffirent approaches to this but in the end I simpy returned a binary and on the fronted I encoded it to base64.

Backend part:

```<code>const handler = async (req, reply) => {
  const p: postParams = req.params;

  const parser = uuIdParserT();

  const img = await db.images.findByPk(parser.setValueAsBIN(p.id));

  const binary = img.dataValues.imageData.toString('binary');

  const b = Buffer.from(binary);

  const myStream = new Readable({
    read() {
      this.push(Buffer.from(binary));
      this.push(null);
    },
  });
  reply.send(myStream);
};

export default (server: FastifyInstance) =>
  server.get<null, any>('/:id', opts, handler);
</code>```

Frontend part:

```<code>  useEffect(() => {
     // axiosState is the obj that holds the image
    if (!axiosState.loading && axiosState.data) {
      // @ts-ignore
      const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
          const slice = byteCharacters.slice(offset, offset + sliceSize);

          const byteNumbers = new Array(slice.length);
          // @ts-ignore
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }

          const byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, { type: contentType });
        return blob;
      };

      const blob = b64toBlob(axiosState.data, 'image/jpg');

      const urlCreator = window.URL || window.webkitURL;
      const imageUrl = urlCreator.createObjectURL(blob);
      setimgUpl(imageUrl);
    }
  }, [axiosState]);
</code>```

and finaly in the html:

```<code>   <img src={imgUpl} alt="NO" className="imageUpload" />
</code>```

OTHER:
For anyone who is attempting the same NOTE that this is not a best practice thing to do.
Almost every article I found saved the images on the sever and save an image Id and other metadata in the datbase. For the exact pros and cons for this I have found the following helpful:

Storing Images in DB - Yea or Nay?

I was focusing on finding out how to do it if for some reason I want to save an image in the datbase and finaly solved it.

Body:
Two part quersion.

Part 1:

Im uploading an image to my server and want to save it to my database.

So far:

table:

resolver:

registerPhoto: inSequence([
  async (obj, { file }) => {
    const { filename, mimetype, createReadStream } = await file;
    const stream = createReadStream();

    const t = await db.images.create({
      Name: 'test',
      imageData: stream ,
    });
  },
])

executing query:

Executing (default): INSERT INTO `images` (`Id`,`imageData`,`Name`) VALUES (DEFAULT,?,?);

But nothing is saved.

Im new to this and im probably missing something but dont know what.

Part2:

This is followed by part 1, lets say I manage to save the image, how do I read it and send it back to my FE?

An edit: Ive read alot of guides saving the an image name to the db and then tha actuall image in a folder. This is NOT what im after, want to save the image to the DB and then be able to fetch it from the DB abd present it.

Body:
This took me some time but I finaly figured it out.

First step (saving to the db):

Have to get the entire stream data and read it like this:

export const readStream = async (stream, encoding = 'utf8') => {
  stream.setEncoding('base64');

  return new Promise((resolve, reject) => {
    let data = '';

    // eslint-disable-next-line no-return-assign
    stream.on('data', chunk => (data += chunk));
    stream.on('end', () => resolve(data));
    stream.on('error', error => reject(error));
  });
};

use like this:

const streamData = await readStream(stream);

Before saving I tur the stream into a buffer:

const buff = Buffer.from(streamData);

Finaly the save part:

db.images.create(
            {
              Name: filename,
              imageData: buff,
              Length: stream.bytesRead,
              Type: mimetype,
            },
            { transaction: param }
          );

Note that I added Length and Type parameter, this is needed if you like to return a stream when you return the image.

Step 2 (Retrieving the image).

As @xadm said multiple times you can not return an image from GRAPHQL and after some time I had to accept that fact, hopefully graphql will remedy this in the future.

S What I needed to do is set up a route on my fastify backend, send a image Id to this route, fetch the image and then return it.

I had a few diffirent approaches to this but in the end I simpy returned a binary and on the fronted I encoded it to base64.

Backend part:

const handler = async (req, reply) => {
  const p: postParams = req.params;

  const parser = uuIdParserT();

  const img = await db.images.findByPk(parser.setValueAsBIN(p.id));

  const binary = img.dataValues.imageData.toString('binary');

  const b = Buffer.from(binary);

  const myStream = new Readable({
    read() {
      this.push(Buffer.from(binary));
      this.push(null);
    },
  });
  reply.send(myStream);
};

export default (server: FastifyInstance) =>
  server.get<null, any>('/:id', opts, handler);

Frontend part:

  useEffect(() => {
     // axiosState is the obj that holds the image
    if (!axiosState.loading && axiosState.data) {
      // @ts-ignore
      const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
          const slice = byteCharacters.slice(offset, offset + sliceSize);

          const byteNumbers = new Array(slice.length);
          // @ts-ignore
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }

          const byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, { type: contentType });
        return blob;
      };

      const blob = b64toBlob(axiosState.data, 'image/jpg');

      const urlCreator = window.URL || window.webkitURL;
      const imageUrl = urlCreator.createObjectURL(blob);
      setimgUpl(imageUrl);
    }
  }, [axiosState]);

and finaly in the html:

   <img src={imgUpl} alt="NO" className="imageUpload" />

OTHER:
For anyone who is attempting the same NOTE that this is not a best practice thing to do.
Almost every article I found saved the images on the sever and save an image Id and other metadata in the datbase. For the exact pros and cons for this I have found the following helpful:

Storing Images in DB - Yea or Nay?

I was focusing on finding out how to do it if for some reason I want to save an image in the datbase and finaly solved it.


问:
Is it okay to use functions to stay organized in C?
I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().

答:
i think it is more than OK, I would recommend it! short easy to prove correct functions with well thought out names lead to code which is more self documenting than long complex functions.

Any compiler worth using will be able to inline these calls to generate efficient code if needed.


问:
Angular get checked checkbox value return undefined
I am using angular with ionic but i can't validate checked items.

HTML:

 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone.id)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>

```

<p>Script:</p>

<pre class="lang-js prettyprint-override"><code>selectedArray: any = []; // should be array of selected items

selectMember(data, isChecked: boolean) {
  console.log(isChecked); //undefined
  if (isChecked === true) {
    this.selectedArray.push(data);
  } else {
    let index = this.selectedArray(data);
    this.selectedArray.splice(index, 1);
  }
  console.log(this.selectedArray);
}
</code>```

Any idea?

答:
You aren't sending if is checked or not, you're just sending the id. Just send your all object and use it.

In the HTML:

```<code><div *ngIf="phones.length > 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>
</div>
</code>```

In the component:

```<code>selectedArray :any = []; // should be array of selected items
selectMember(data) {
    console.log(data.isChecked); //undefined
    if (data.isChecked === true) {
      this.selectedArray.push(data.id);
    }
    else {
      let index = this.selectedArray.indexOf(data.id);
      this.selectedArray.splice(index, 1);
    }
    console.log(this.selectedArray);
  }
</code>```

Body:
I am using angular with ionic but i can't validate checked items.

HTML:

 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone.id)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>

Script:

selectedArray: any = []; // should be array of selected items

selectMember(data, isChecked: boolean) {
  console.log(isChecked); //undefined
  if (isChecked === true) {
    this.selectedArray.push(data);
  } else {
    let index = this.selectedArray(data);
    this.selectedArray.splice(index, 1);
  }
  console.log(this.selectedArray);
}

Any idea?

Body:
You aren't sending if is checked or not, you're just sending the id. Just send your all object and use it.

In the HTML:

<div *ngIf="phones.length > 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>
</div>

In the component:

selectedArray :any = []; // should be array of selected items
selectMember(data) {
    console.log(data.isChecked); //undefined
    if (data.isChecked === true) {
      this.selectedArray.push(data.id);
    }
    else {
      let index = this.selectedArray.indexOf(data.id);
      this.selectedArray.splice(index, 1);
    }
    console.log(this.selectedArray);
  }


问:
How to Change date format in php?
I have a date in an input
15/01/1995.But, I want to save this date in this format 1995-01-15.
I tried this code

$date_format = date("Y-m-d", strtotime($Data['date']));

but, the output is 1970-01-01 which is wrong.

答:
Try this:

```<code>    $date="15/01/1995";
    $date=str_replace('/','-',$date);
    echo date("Y-m-d", strtotime($date));
</code>```

Title: How to Change date format in php?

Body:
Try this:

    $date="15/01/1995";
    $date=str_replace('/','-',$date);
    echo date("Y-m-d", strtotime($date));


问:
Finding sum of elements in Swift array
What is the easiest (best) way to find the sum of an array of integers in swift?
I have an array called multiples and I would like to know the sum of the multiples.</p>

答:
For me, it was like  this using property </p>

```<code>    let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
        result + participant.kills
    })
</code>```

Title: Finding sum of elements in Swift array

Body:
For me, it was like  this using property

    let blueKills = match.blueTeam.participants.reduce(0, { (result, participant) -> Int in
        result + participant.kills
    })


问:
Why heatmap row order is not the same as the data row order?
Hello for my work I creates a ggplot2 heatmap.

here are the data

```<code>structure(list(label = structure(c(4L, 5L, 7L, 2L, 3L, 6L, 8L,
1L, 4L, 5L, 7L, 2L, 3L, 6L, 8L, 1L, 4L, 5L, 7L, 2L, 3L, 6L, 8L,
1L), .Label = c("SP1", "SP2", "SP3", "SP4", "SP5", "SP6", "SP7",
"SP8"), class = "factor"), Categories = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L), .Label = c("VAR1", "VAR2", "VAR3"), class = "factor"),
    Value = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L,
    3L, 3L, 3L, 2L, 1L, 1L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L), .Label = c("<NA>",
    "A", "B"), class = "factor")), class = "data.frame", row.names = c(NA,
-24L))
</code>```

as you can see there is a specific order of labels :

```<code>1 - SP4
2 - SP5
3 - SP7
...
7 - SP8
8 - SP1
</code>```

here is the df :

```<code>> table
   label Categories Value
1    SP4       VAR1  <NA>
2    SP5       VAR1  <NA>
3    SP7       VAR1  <NA>
4    SP2       VAR1  <NA>
5    SP3       VAR1  <NA>
6    SP6       VAR1  <NA>
7    SP8       VAR1  <NA>
8    SP1       VAR1  <NA>
9    SP4       VAR2     A
10   SP5       VAR2     B
11   SP7       VAR2     B
12   SP2       VAR2     B
13   SP3       VAR2     B
14   SP6       VAR2     A
15   SP8       VAR2  <NA>
16   SP1       VAR2  <NA>
17   SP4       VAR3     A
18   SP5       VAR3     B
19   SP7       VAR3     B
20   SP2       VAR3     B
21   SP3       VAR3     B
22   SP6       VAR3     B
23   SP8       VAR3  <NA>
24   SP1       VAR3  <NA>
</code>```

so I'm expecting to see the same row order if I do a heatmap with ggplot, but instead I get this order:

I used the code :

```<code>ggplot(mod_mat_gen_env, aes(x=Categories, y=label))+
  geom_tile(aes(fill=Value))
</code>```

答:
One option is to refactor it in your data.frame, or you can provide the order using limits= option in scale_y_discrete()

```<code>df$Value = replace(as.character(df$Value),df$Value=="<NA>",NA)
list_correct_order=c("SP4","SP5","SP7","SP2","SP3","SP6","SP8","SP1")

ggplot(df, aes(x=Categories, y=label))+
  geom_tile(aes(fill=Value)) +
scale_y_discrete(limits=rev(list_correct_order))
</code>```

Body:
Hello for my work I creates a ggplot2 heatmap.

here are the data

structure(list(label = structure(c(4L, 5L, 7L, 2L, 3L, 6L, 8L,
1L, 4L, 5L, 7L, 2L, 3L, 6L, 8L, 1L, 4L, 5L, 7L, 2L, 3L, 6L, 8L,
1L), .Label = c("SP1", "SP2", "SP3", "SP4", "SP5", "SP6", "SP7",
"SP8"), class = "factor"), Categories = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L), .Label = c("VAR1", "VAR2", "VAR3"), class = "factor"),
    Value = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L,
    3L, 3L, 3L, 2L, 1L, 1L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L), .Label = c("<NA>",
    "A", "B"), class = "factor")), class = "data.frame", row.names = c(NA,
-24L))

as you can see there is a specific order of labels :

1 - SP4
2 - SP5
3 - SP7
...
7 - SP8
8 - SP1

here is the df :

> table
   label Categories Value
1    SP4       VAR1  <NA>
2    SP5       VAR1  <NA>
3    SP7       VAR1  <NA>
4    SP2       VAR1  <NA>
5    SP3       VAR1  <NA>
6    SP6       VAR1  <NA>
7    SP8       VAR1  <NA>
8    SP1       VAR1  <NA>
9    SP4       VAR2     A
10   SP5       VAR2     B
11   SP7       VAR2     B
12   SP2       VAR2     B
13   SP3       VAR2     B
14   SP6       VAR2     A
15   SP8       VAR2  <NA>
16   SP1       VAR2  <NA>
17   SP4       VAR3     A
18   SP5       VAR3     B
19   SP7       VAR3     B
20   SP2       VAR3     B
21   SP3       VAR3     B
22   SP6       VAR3     B
23   SP8       VAR3  <NA>
24   SP1       VAR3  <NA>

so I'm expecting to see the same row order if I do a heatmap with ggplot, but instead I get this order:

I used the code :

ggplot(mod_mat_gen_env, aes(x=Categories, y=label))+
  geom_tile(aes(fill=Value))

Body:
One option is to refactor it in your data.frame, or you can provide the order using limits= option in scale_y_discrete()

df$Value = replace(as.character(df$Value),df$Value=="<NA>",NA)
list_correct_order=c("SP4","SP5","SP7","SP2","SP3","SP6","SP8","SP1")

ggplot(df, aes(x=Categories, y=label))+
  geom_tile(aes(fill=Value)) +
scale_y_discrete(limits=rev(list_correct_order))


答: Yes.  Please.  Don't write long functions.  Write short ones that do one thing and do it well.  The fact that they may only be called once is fine.  One benefit is that if you name your function well, you can avoid writing comments that will get out of sync with the code over time.  </p>

Title: Is it okay to use functions to stay organized in C?

Body:
I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().


问:
multiple form dont update mysql
I have this function an first query working fine
but second is multiple form like input name="id[]" ,urunad="id[]",birim="id[]"...
I take $_POST to function</p>

```<code>$id2 = $gid;
$sid2 = $sid;
$urunad2 = $urunad;
$birim2 = $birim;
$adet2 = $adet;
$fiyat2 = $fiyat;
$kdvsiztoplam2 = $kdvsiztoplam;
whats the problem please help me

     public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
            {
                    $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
                    $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));
                    return $update;

                    $id2 = $gid;
                    $sid2 = $sid;
                    $urunad2 = $urunad;
                    $birim2 = $birim;
                    $adet2 = $adet;
                    $fiyat2 = $fiyat;
                    $kdvsiztoplam2 = $kdvsiztoplam;

                for($i=0;$i<count($id2);$i++)
                {
                    $query = $this->db->prepare("update surunler set id = ? ,sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? ");
                    $update = $query->execute(array($id2[$i],$sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i]));
                    return $update;
                }

            }
</code>```

答:
thanks your help working code here maybe someone need help</p>

```<code>    public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
{
        $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
        $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));

        $id2 = $gid;
        $sid2 = $sid;
        $urunad2 = $urunad;
        $birim2 = $birim;
        $adet2 = $adet;
        $fiyat2 = $fiyat;
        $kdvsiztoplam2 = $kdvsiztoplam;

    for($i=0;$i<count($id2);$i++)
    {
        $query = $this->db->prepare("update surunler set sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? where id = ?");
        $update = $query->execute(array($sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i],$id2[$i]));
    }

}
</code>```

Title: multiple form dont update mysql

Body:
I have this function an first query working fine
but second is multiple form like input name="id[]" ,urunad="id[]",birim="id[]"...
I take $_POST to function

$id2 = $gid;
$sid2 = $sid;
$urunad2 = $urunad;
$birim2 = $birim;
$adet2 = $adet;
$fiyat2 = $fiyat;
$kdvsiztoplam2 = $kdvsiztoplam;
whats the problem please help me

     public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
            {
                    $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
                    $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));
                    return $update;

                    $id2 = $gid;
                    $sid2 = $sid;
                    $urunad2 = $urunad;
                    $birim2 = $birim;
                    $adet2 = $adet;
                    $fiyat2 = $fiyat;
                    $kdvsiztoplam2 = $kdvsiztoplam;

                for($i=0;$i<count($id2);$i++)
                {
                    $query = $this->db->prepare("update surunler set id = ? ,sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? ");
                    $update = $query->execute(array($id2[$i],$sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i]));
                    return $update;
                }

            }

Body:
thanks your help working code here maybe someone need help

    public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
{
        $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
        $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));

        $id2 = $gid;
        $sid2 = $sid;
        $urunad2 = $urunad;
        $birim2 = $birim;
        $adet2 = $adet;
        $fiyat2 = $fiyat;
        $kdvsiztoplam2 = $kdvsiztoplam;

    for($i=0;$i<count($id2);$i++)
    {
        $query = $this->db->prepare("update surunler set sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? where id = ?");
        $update = $query->execute(array($sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i],$id2[$i]));
    }

}


问:
Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});
</code>```

but after compiling i get this error :

```<code>Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
</code>```

I tried this but same error

```<code>...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
.open()
.then(( d ) => d.result
...
</code>```

I also tried that but getting ; expected

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .result => {...};
</code>```

Here's my package.json :

```<code>{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}
</code>```

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

答:
I fixed it by  adding result before then :

```<code>...
this.modal.confirm().showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
.open()
.result
.then(( d ) => d.result
...
</code>```

Body:
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});

but after compiling i get this error :

Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)

I tried this but same error

...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
.open()
.then(( d ) => d.result
...

I also tried that but getting ; expected

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .result => {...};

Here's my package.json :

{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

Body:
I fixed it by  adding result before then :

...
this.modal.confirm().showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
.open()
.result
.then(( d ) => d.result
...


问:
Array sorting by key value in php
I would like to sort below array based on amount but I don't know how. Anyone help me </p>

```<code>Array(
    [0] => Array
     (
          [id] => 1
          [amount] => 20
     )
     [1] => Array
     (
          [id] => 2
          [amount] => 30
     )
     [2] => Array
     (
          [id] => 3
          [amount] => 10
     )
)
</code>```

答:
Use usort function like this (know more about usort click here):

```<code>  $array = array(array('id'=>1,'amount'=>20),array('id'=>2,'amount'=>30),array('id'=>3,'amount'=>10));
</code>```

Create custom function like this:

```<code>function sortByAmount($x,$y){
  return $x['amount']-$y['amount'];
}
</code>```

Then use usort function like this:

```<code>usort($array,'sortByAmount');
// then print
echo"```"; print_r($array);
```

Title: Array sorting by key value in php

Body:
I would like to sort below array based on amount but I don't know how. Anyone help me

Array(
    [0] => Array
     (
          [id] => 1
          [amount] => 20
     )
     [1] => Array
     (
          [id] => 2
          [amount] => 30
     )
     [2] => Array
     (
          [id] => 3
          [amount] => 10
     )
)

Body:
Use usort function like this (know more about usort click here):

  $array = array(array('id'=>1,'amount'=>20),array('id'=>2,'amount'=>30),array('id'=>3,'amount'=>10));

Create custom function like this:

function sortByAmount($x,$y){
  return $x['amount']-$y['amount'];
}

Then use usort function like this:

usort($array,'sortByAmount');
// then print
echo"<pre>"; print_r($array);


问:
Append pandas dataframe with dictionary using for loop
I have the following dictionary and I want to add these in to a pandas dataframe:

```<code>crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}
</code>```

I create the blank dataframe with the column names I want:

```<code>column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)
</code>```

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

```<code>for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)
</code>```

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

答:
You can try this.</p>

```<code>crimes2 = pd.DataFrame(crimes1.items(), columns=['Neighborhood', 'Count'])
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503
</code>```

Body:
I have the following dictionary and I want to add these in to a pandas dataframe:

crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}

I create the blank dataframe with the column names I want:

column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

Body:
You can try this.

crimes2 = pd.DataFrame(crimes1.items(), columns=['Neighborhood', 'Count'])
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503


问:
Why does Java's BitSet internally store long array but use int for set method?
According to the BitSet implementation, it internally uses an array of longs:

```<code>/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;
</code>```

But for the set method it uses int:

```<code>public void set(int bitIndex) {...}
</code>```

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.

答:
Each chunk of 64 bits is packed into long, not one long per bit index, so length of the long[] words array will use up to 268,435,456 bytes with int index when calling set(2147483647) or just one long if calling only bitset.set(1). Example in jshell:</p>

```<code>BitSet b = new BitSet();
b.size();
==> 64 (ie words is length 1 can store 64 bits)
b.set(1);
b.size();
==> 64 (ie words is still length 1)
b.set(64)
==> 128 (ie words array is length 2, can store up to 128 bits)
</code>```

Body:
According to the BitSet implementation, it internally uses an array of longs:

/**
 * The internal field corresponding to the serialField "bits".
 */
private long[] words;

But for the set method it uses int:

public void set(int bitIndex) {...}

So basically we can store (2^31 - 1) * 64 * 8 = 2,147,483,642 * 64 * 8 = 137,438,953,088 bits, but using int indexing we have access only to the first 2,147,483,648 bits.

Which means that 137,438,953,088 - 2,147,483,648 = 135,291,469,440 bits are unavailable.

But if developers of this class used long instead of int for bits indexing, it would solve all the problems, since with long we can navigate trough 2^63 - 1 = 9,223,372,036,854,775,807 bits

It does not make any sense even from performance point of view.

What the reasoning behind the logic of using int instead of long for indexing and missing billions of bits?

P.S. One can say that the problem is 2 GiB of heap size, but today it is not an issue anymore.

Body:
Each chunk of 64 bits is packed into long, not one long per bit index, so length of the long[] words array will use up to 268,435,456 bytes with int index when calling set(2147483647) or just one long if calling only bitset.set(1). Example in jshell:

BitSet b = new BitSet();
b.size();
==> 64 (ie words is length 1 can store 64 bits)
b.set(1);
b.size();
==> 64 (ie words is still length 1)
b.set(64)
==> 128 (ie words array is length 2, can store up to 128 bits)


问:
How to create a rectangle that exactly fills the device screen
I'm trying to create a Rectangle that fills the device's screen. I've tried this:

```<code>Rectangle()
            .fill(Color.green)
            .frame( height: UIScreen.main.bounds.size.height)
            .frame( width: UIScreen.main.bounds.size.width)
            .edgesIgnoringSafeArea(.all)

</code>```

Using this extension:

```<code>extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}
</code>```

However, the height is slightly too small:

and I'm not sure why.

答:
Use just as below</p>

```<code>Rectangle()
   .fill(Color.green)
   .edgesIgnoringSafeArea(.all)
</code>```

Body:
I'm trying to create a Rectangle that fills the device's screen. I've tried this:

Rectangle()
            .fill(Color.green)
            .frame( height: UIScreen.main.bounds.size.height)
            .frame( width: UIScreen.main.bounds.size.width)
            .edgesIgnoringSafeArea(.all)

Using this extension:

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}

However, the height is slightly too small:

and I'm not sure why.

Body:
Use just as below

Rectangle()
   .fill(Color.green)
   .edgesIgnoringSafeArea(.all)


问:
Import a config file in Google Cloud Build yaml config to assign values
Before, I have a makefile which contains commands for docker build and docker run. I also have a config file which is imported by the makefile, and it has some variable values. Then, I use build-arg flag to assign values to variables which are used in the dockerfile and my code. </p>

<p>Now I want to switch to Google Cloud Build and use the yaml config. I know the structure of the yaml config file and I still can use the build-arg flag. However, can i still import my config file and assign variable values as I did before? </p>

答:
You shared few information on your current process,but I will try to provide you some tips

First, you can import your file. I don't know where it is, but if it is on Google CLoud Storage, your can do this

```<code>step:
  - name: gcr.io/cloud-builders/gcloud:latest
    entrypoint: "gsutil"
    args: ["cp","gs://yourbuket/config.file", "/workspace/config.file"]
</code>```

Then, and it's the boring thing of Cloud Build, you can't define global environment variable inside the code (I mean dynamically) and for all the steps. You have to do it step by step, for example like this

```<code>step:
  ....
  - name: gcr.io/cloud-builders/gcloud:latest
    entrypoint: "bash"
    args:
      - "-c"
      - |
        # Add it in the environment
        export MY_VAR=$(grep MY_VAR /workspace/config.file | cut -d'=' -f2)
</code>```

Here I supposed that the config file format is key=value

If you need to add it in Docker Build, you can do the same thing with the -e param. For your code, I don't know how you passe it.

Body:
Before, I have a makefile which contains commands for docker build and docker run. I also have a config file which is imported by the makefile, and it has some variable values. Then, I use build-arg flag to assign values to variables which are used in the dockerfile and my code.

Now I want to switch to Google Cloud Build and use the yaml config. I know the structure of the yaml config file and I still can use the build-arg flag. However, can i still import my config file and assign variable values as I did before?

Body:
You shared few information on your current process,but I will try to provide you some tips

First, you can import your file. I don't know where it is, but if it is on Google CLoud Storage, your can do this

step:
  - name: gcr.io/cloud-builders/gcloud:latest
    entrypoint: "gsutil"
    args: ["cp","gs://yourbuket/config.file", "/workspace/config.file"]

Then, and it's the boring thing of Cloud Build, you can't define global environment variable inside the code (I mean dynamically) and for all the steps. You have to do it step by step, for example like this

step:
  ....
  - name: gcr.io/cloud-builders/gcloud:latest
    entrypoint: "bash"
    args:
      - "-c"
      - |
        # Add it in the environment
        export MY_VAR=$(grep MY_VAR /workspace/config.file | cut -d'=' -f2)

Here I supposed that the config file format is key=value

If you need to add it in Docker Build, you can do the same thing with the -e param. For your code, I don't know how you passe it.


问:
Code 1 is not working but the other is. What is wrong with 1st code?
I'm trying to learn javascript. For the life of me I can't tell what is wrong with my object code below. I get an error saying:

this.signIn is not a function

```<code>let socialAppFunctions = {
  displayNewsFeed: function () {
    let socialPostsSection = document.querySelector("#socialPosts");

    newsFeed.forEach(function (posts) {
      let socialPosts = document.createElement("h4");
      socialPosts.textContent = posts;
      socialPostsSection.appendChild(socialPosts);
    });
  },
  loginButton: function () {
    let loginButton = document.querySelector("#loginButton");

    loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      this.signIn(userName.value, passWord.value);

    });
  },
  signIn: function (username, password) {

    if (this.userValidation(username, password)) {
        this.displayNewsFeed();
      } else {
        alert("Please check username and password");
      }
  },
  userValidation: function (username, password) {

    for (let i = 0; i < database.length; i++) {
      if (database[i].username === username && database[i].password === password) {
        return true;
      }
    }
    return false;
  }
};

socialAppFunctions.loginButton();
</code>```

This one below works if I don't put them as inside as one object:

```<code>function signIn (username, password) {

      if (userValidation(username, password)) {
        displayNewsFeed();
      } else {
        alert("Please check username and password");
      }
    }

function userValidation (username, password) {

    for (let i = 0; i < database.length; i++) {
      if (database[i].username === username && database[i].password === password) {
        return true;
      }
    }
    return false;
  }

function loginButton () {
    let loginButton = document.querySelector("#loginButton");

    loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      signIn(userName.value, passWord.value);

    });
  }
loginButton();

function displayNewsFeed () {
    let socialPostsSection = document.querySelector("#socialPosts");

    newsFeed.forEach(function (posts) {
      let socialPosts = document.createElement("h4");
      socialPosts.textContent = posts;
      socialPostsSection.appendChild(socialPosts);
    });
  }
</code>```

答:
It's about the context of this keyword within your addEventListener block in the above code.

The value of this will refer to loginButton inside the add event listener and loginButton doesnt have a signIn method, to make your code still work you need to bind this by doing the following.

```<code>loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      this.signIn(userName.value, passWord.value);

    }.bind(this));
</code>```

And now this inside addEventListener block will refer to socialAppFunctions object and it would work.

Body:
I'm trying to learn javascript. For the life of me I can't tell what is wrong with my object code below. I get an error saying:

this.signIn is not a function

let socialAppFunctions = {
  displayNewsFeed: function () {
    let socialPostsSection = document.querySelector("#socialPosts");

    newsFeed.forEach(function (posts) {
      let socialPosts = document.createElement("h4");
      socialPosts.textContent = posts;
      socialPostsSection.appendChild(socialPosts);
    });
  },
  loginButton: function () {
    let loginButton = document.querySelector("#loginButton");

    loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      this.signIn(userName.value, passWord.value);

    });
  },
  signIn: function (username, password) {

    if (this.userValidation(username, password)) {
        this.displayNewsFeed();
      } else {
        alert("Please check username and password");
      }
  },
  userValidation: function (username, password) {

    for (let i = 0; i < database.length; i++) {
      if (database[i].username === username && database[i].password === password) {
        return true;
      }
    }
    return false;
  }
};

socialAppFunctions.loginButton();

This one below works if I don't put them as inside as one object:

function signIn (username, password) {

      if (userValidation(username, password)) {
        displayNewsFeed();
      } else {
        alert("Please check username and password");
      }
    }

function userValidation (username, password) {

    for (let i = 0; i < database.length; i++) {
      if (database[i].username === username && database[i].password === password) {
        return true;
      }
    }
    return false;
  }

function loginButton () {
    let loginButton = document.querySelector("#loginButton");

    loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      signIn(userName.value, passWord.value);

    });
  }
loginButton();

function displayNewsFeed () {
    let socialPostsSection = document.querySelector("#socialPosts");

    newsFeed.forEach(function (posts) {
      let socialPosts = document.createElement("h4");
      socialPosts.textContent = posts;
      socialPostsSection.appendChild(socialPosts);
    });
  }

Body:
It's about the context of this keyword within your addEventListener block in the above code.

The value of this will refer to loginButton inside the add event listener and loginButton doesnt have a signIn method, to make your code still work you need to bind this by doing the following.

loginButton.addEventListener("click", function() {

      let userName = document.querySelector("#user");
      let passWord = document.querySelector("#pass");

      this.signIn(userName.value, passWord.value);

    }.bind(this));

And now this inside addEventListener block will refer to socialAppFunctions object and it would work.


问:
Mongo Error: Duplicate Key error makes no sense
Hi fellow developers!
I've got this error showing up in my console when I try to save two identical documents in a collection in MongoDB that has nothing to do with the index shown in the error.

Here's the error: E11000 duplicate key error collection: Bohemian.orders index: user.email_1 dup key: { user.email: null }

Now this makes no sense, because I'm trying to save an Order document in a separate collection, which has nothing to do with the user router I had set up previously.

Here is the schema and model code:

const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
    amountToPay: Number,
});

const Order = mongoose.model("Order", orderSchema);

module.exports.Order = Order;```
</div>
</div>
</p>

<p>As shown here, I am only trying to save the amount to be payed into the database in a separate collection.</p>

<p><strong>Here is the router file:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
const router = express.Router();
const { Order } = require('../models/Order');

router.get("/", async (req, res, next) => {
    try {
        const orders = await Order.find();
        if (orders.length === 0) return res.status(404).send("There are currently no orders");
        res.send(orders);
    } catch (ex) {
        console.error(ex);
        next();
    }
});

router.post("/", async (req, res, next) => {
    try {
        const order = new Order({
            amountToPay: req.body.amountToPay
        });
        await order.save();
        res.send(order);
    } catch (ex) {
        console.error(ex);
        next();
    }
});

module.exports = router;</code>```

As you can see there is nothing relative to the error that I'm getting and I have no clue why I'm getting a duplicate user.email = null key , when I haven't made any reference to the User model or router.

Here is the POST call I'm making from POSTMAN to test:

Pretty straight forward, nothing extreme, nothing tangled, right? Well the first ever POST call saves the document in the Database, but from then on I keep getting the same error. The only thing I can take from that is that when I save the first document, Mongo looks for the user.email property when I'm creating the new instance of Order and when it doesnt find it, it creates it with a value of null and then the next document would naturally be a duplicate, hence the error. But I'm confused, because this model and router should not absolutely nothing to do with the user ones.

Here is the error:

So please if anyone can help me understand why MongoDB is screwing with me or where I'm making a mistake, I would really appreciate it.

答:
I found out what the problems was, thanks to Molda:
At some point I had created these indexes, which I'm still unsure when and how, but I did. Which essentially lead to this error, when I tried to save the second document.
A simple quick console log of the indexes in the collection showed that I had that index in there.

const indexes = await Order.collection.getIndexes();
console.log(indexes);```
</div>
</div>
</p>

<p>Then I removed them using this method: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>await Order.collection.dropIndexes("user.email_1");</code>```

And everything worked flawlessly from there.
I hope this helps anyone in this situation in the future and thanks Molda! :)

Body:
Hi fellow developers!
I've got this error showing up in my console when I try to save two identical documents in a collection in MongoDB that has nothing to do with the index shown in the error.

Here's the error: E11000 duplicate key error collection: Bohemian.orders index: user.email_1 dup key: { user.email: null }

Now this makes no sense, because I'm trying to save an Order document in a separate collection, which has nothing to do with the user router I had set up previously.

Here is the schema and model code:

const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
    amountToPay: Number,
});

const Order = mongoose.model("Order", orderSchema);

module.exports.Order = Order;

As shown here, I am only trying to save the amount to be payed into the database in a separate collection.

Here is the router file:

const express = require('express');
const router = express.Router();
const { Order } = require('../models/Order');

router.get("/", async (req, res, next) => {
    try {
        const orders = await Order.find();
        if (orders.length === 0) return res.status(404).send("There are currently no orders");
        res.send(orders);
    } catch (ex) {
        console.error(ex);
        next();
    }
});

router.post("/", async (req, res, next) => {
    try {
        const order = new Order({
            amountToPay: req.body.amountToPay
        });
        await order.save();
        res.send(order);
    } catch (ex) {
        console.error(ex);
        next();
    }
});

module.exports = router;

As you can see there is nothing relative to the error that I'm getting and I have no clue why I'm getting a duplicate user.email = null key , when I haven't made any reference to the User model or router.

Here is the POST call I'm making from POSTMAN to test:

Pretty straight forward, nothing extreme, nothing tangled, right? Well the first ever POST call saves the document in the Database, but from then on I keep getting the same error. The only thing I can take from that is that when I save the first document, Mongo looks for the user.email property when I'm creating the new instance of Order and when it doesnt find it, it creates it with a value of null and then the next document would naturally be a duplicate, hence the error. But I'm confused, because this model and router should not absolutely nothing to do with the user ones.

Here is the error:

So please if anyone can help me understand why MongoDB is screwing with me or where I'm making a mistake, I would really appreciate it.

Body:
I found out what the problems was, thanks to Molda:
At some point I had created these indexes, which I'm still unsure when and how, but I did. Which essentially lead to this error, when I tried to save the second document.
A simple quick console log of the indexes in the collection showed that I had that index in there.

const indexes = await Order.collection.getIndexes();
console.log(indexes);

Then I removed them using this method:

await Order.collection.dropIndexes("user.email_1");

And everything worked flawlessly from there.
I hope this helps anyone in this situation in the future and thanks Molda! :)


问:
Django - Make migration command detects changes but on migrating says 'No migrations to apply'
i am new to django developement after making changes to my model i tried to run the command python manage.py makemigrations my_app
it detects changes in my model and shows me the message
todoapp/migrations/0001_initial.py
    - Create model confess
    - Create model UserChoice
    - Create model comment
but on executing  python manage.py migrate my_appcommand i've got this message
No migrations to apply.
i usually do this after making changes in models, i don't know what happened now.
plss help me.

答:
Firstly, try

```<code>python manage.py makemigrations my_app
python manage.py migrate
</code>```

If this does not work and the project is still in development:

Delete migrations folder and pycache folder.

Delete db.sqlite3 (your database).

Make and apply migrations again.

I think this will work.

Body:
Firstly, try

python manage.py makemigrations my_app
python manage.py migrate

If this does not work and the project is still in development:

Delete migrations folder and pycache folder.

Delete db.sqlite3 (your database).

Make and apply migrations again.

I think this will work.


问:
Don't let a user to use same item for different select inputs
I'm developing an OTC trading interface and a request for quote interface for that with Vue.js. My goal is to don't let user use same item for two different select inputs.

Select input:

```<code><v-select
 v-model="yousendselect"
 :items="items"
 :rules="[v => !!v || 'Item is required']"
 label="You get"
 required
></v-select>
</code>```

Select input 2:

```<code><v-select
 v-model="yougetselect"
 :items="items"
 :rules="[v => !!v || 'Item is required']"
 label="You get"
 required
></v-select>
</code>```

Items:

```<code>items: [
 'Bitcoin',
 'Ethereum',
 'Litecoin',
 'Ripple',
],
</code>```

If an user selects Bitcoin for v-model="yousendselect", user won't be able to select Bitcoin for v-model="yougetselect".

答:
new Vue({
  el: '#app',
  template: `

Send

      <select v-model="yousendselect">
        <option :value="undefined">---</option>
        <option v-for="item in itemForSendSelect" :key="item" :value="item">{{ item }}</option>
      </select>

Get

      <select v-model="yougetselect">
        <option :value="undefined">---</option>
        <option v-for="item in itemForGetSelect" :key="item" :value="item">{{ item }}</option>
      </select>

  `,
  data() {
    return {
      items: [
        "Bitcoin",
        "Ethereum",
        "Litecoin",
        "Ripple",
      ],
      yousendselect: undefined,
      yougetselect: undefined,
    };
  },
  computed: {
    itemForSendSelect() {
      return this.items.filter(i => i !== this.yougetselect);
    },

    itemForGetSelect() {
      return this.items.filter(i => i !== this.yousendselect);
    },
  },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app"></div></code>```

Body:
I'm developing an OTC trading interface and a request for quote interface for that with Vue.js. My goal is to don't let user use same item for two different select inputs.

Select input:

<v-select
 v-model="yousendselect"
 :items="items"
 :rules="[v => !!v || 'Item is required']"
 label="You get"
 required
></v-select>

Select input 2:

<v-select
 v-model="yougetselect"
 :items="items"
 :rules="[v => !!v || 'Item is required']"
 label="You get"
 required
></v-select>

Items:

items: [
 'Bitcoin',
 'Ethereum',
 'Litecoin',
 'Ripple',
],

If an user selects Bitcoin for v-model="yousendselect", user won't be able to select Bitcoin for v-model="yougetselect".

Body:
new Vue({
  el: '#app',
  template: `
    <div>
      <h2>Send</h2>
      <select v-model="yousendselect">
        <option :value="undefined">---</option>
        <option v-for="item in itemForSendSelect" :key="item" :value="item">{{ item }}</option>
      </select>
      <h2>Get</h2>
      <select v-model="yougetselect">
        <option :value="undefined">---</option>
        <option v-for="item in itemForGetSelect" :key="item" :value="item">{{ item }}</option>
      </select>
    </div>
  `,
  data() {
    return {
      items: [
        "Bitcoin",
        "Ethereum",
        "Litecoin",
        "Ripple",
      ],
      yousendselect: undefined,
      yougetselect: undefined,
    };
  },
  computed: {
    itemForSendSelect() {
      return this.items.filter(i => i !== this.yougetselect);
    },

    itemForGetSelect() {
      return this.items.filter(i => i !== this.yousendselect);
    },
  },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app"></div>