问:
i want to add the following from a list but the result only concatinates

Sample value of n is 5

```<code>    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

</code>```

Expected Result : 615

答:
After splitting n is a list of strings, you should cast them to int.

```<code>n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=int(n[0])
b=int(n[1])
c=int(n[2])
n = (a + b + c)
print(n)
</code>```

And if necessary add try/except to handle correctly situations when not a valid number would be passed.

Body:
Sample value of n is 5

    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

Expected Result : 615

Body:
After splitting n is a list of strings, you should cast them to int.

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = n.split("+")
a=int(n[0])
b=int(n[1])
c=int(n[2])
n = (a + b + c)
print(n)

And if necessary add try/except to handle correctly situations when not a valid number would be passed.


来源: stackexchange

问:
Making an outbound connection
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

```<code>import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

</code>```

My server side script runs fine, however when i run the client script

```<code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
</code>```

i get the following:

```<code>File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax
</code>```

I've tried changing the IP to my computer host name  and gives the following:

```<code>raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
</code>```

答:
There are multiple issues:

when specifying IP addresses and hostnames, they must be formatted as strings (e.g. "127.0.0.1" and "LAPTOP-XXXXXXX"). Specifying them without quotes causes Python to attempt to interpret them as other tokens, such as variable names, reserved keyword, numbers, etc., which fails causing erros such as SyntaxError and NameError.

socket.gethostname() does not take an argument

specifying port 0 in the socket.bind() call results in a random high numbered port being assigned, so you either need to hardcode the port you use or dynamically specify the correct port in your client (e.g. by specifying it as an argument when executing the program)

in the server code, socket.gethostname() may not end up using the loopback address. One option here is using an empty string, which results in accepting connections on any IPv4 address.

Here's a working implementation:

server.py

```<code>import socket

HOST = ''
PORT = 45555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
    client_socket, client_addr = s.accept()
    print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
    client_socket.send(bytes("welcome to the server!", "utf-8"))
</code>```

client.py

```<code>import socket

HOST = '127.0.0.1'
PORT = 45555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))
</code>```

Output from the server:

```<code>$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established
</code>```

Output from client:

```<code>$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!
</code>```

ContentLicense: CC BY-SA 4.0

Title: Making an outbound connection

Body:
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

My server side script runs fine, however when i run the client script

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))

i get the following:

File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax

I've tried changing the IP to my computer host name  and gives the following:

raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined

Body:
There are multiple issues:

when specifying IP addresses and hostnames, they must be formatted as strings (e.g. "127.0.0.1" and "LAPTOP-XXXXXXX"). Specifying them without quotes causes Python to attempt to interpret them as other tokens, such as variable names, reserved keyword, numbers, etc., which fails causing erros such as SyntaxError and NameError.

socket.gethostname() does not take an argument

specifying port 0 in the socket.bind() call results in a random high numbered port being assigned, so you either need to hardcode the port you use or dynamically specify the correct port in your client (e.g. by specifying it as an argument when executing the program)

in the server code, socket.gethostname() may not end up using the loopback address. One option here is using an empty string, which results in accepting connections on any IPv4 address.

Here's a working implementation:

server.py

import socket

HOST = ''
PORT = 45555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
host_addr = s.getsockname()
print("listening on {}:{}".format(host_addr[0], host_addr[1]))
s.listen(5)
while True:
    client_socket, client_addr = s.accept()
    print("connection from {}:{} established".format(client_addr[0], client_addr[1]))
    client_socket.send(bytes("welcome to the server!", "utf-8"))

client.py

import socket

HOST = '127.0.0.1'
PORT = 45555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
msg = s.recv(1024)
print(msg.decode("utf-8"))

Output from the server:

$ python3 server.py
listening on 0.0.0.0:45555
connection from 127.0.0.1:51188 established
connection from 127.0.0.1:51244 established

Output from client:

$ python3 client.py
welcome to the server!
$ python3 client.py
welcome to the server!


问:
Replacing values with dictionary key in python
So I created a dictionary with every state abbreviation and the keys are "East", "Central", and "West"

```<code>states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}
</code>```

I'm trying to figure out a way to apply this to a column of code and return the dictionary keys instead in the column. For example if it is ["CA", "FL"] I want the column to be ["West","East]. I created a for loop where i appended the keys into a new list and it wasnt the correct length so I started using .replace and that is just continually running. Here is my code.

```<code>for x in df['X20']:
    for i,j in states_dict.items():
        for v in j:
            if x==v:
                x20=df['X20'].replace(x,i)

            else:
                pass
x20
</code>```

答:
You can do a list comprehension that searches for keys that contain search fields in their values:</p>

```<code>states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

search = ["CA", "FL"]
print([k for k, v in states_dict.items() if any(y in v for y in search)])
# ['West', 'East']
</code>```

Body:
So I created a dictionary with every state abbreviation and the keys are "East", "Central", and "West"

states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

I'm trying to figure out a way to apply this to a column of code and return the dictionary keys instead in the column. For example if it is ["CA", "FL"] I want the column to be ["West","East]. I created a for loop where i appended the keys into a new list and it wasnt the correct length so I started using .replace and that is just continually running. Here is my code.

for x in df['X20']:
    for i,j in states_dict.items():
        for v in j:
            if x==v:
                x20=df['X20'].replace(x,i)

            else:
                pass
x20

Body:
You can do a list comprehension that searches for keys that contain search fields in their values:

states_dict = {
    'West': ["CA","OR","WA","NV","ID","UT","AZ","MT","AK"],
    'Central': ["WY","CO","NM","ND","SD","NE","KS","OK","TX","MN","IA","MO","AR","LA","WI","IL","MS"],
    'East': ["MI","IN","KY","TN","AL","OH","GA","FL","SC","NC","VA","WV","DE","MD","NJ","PA","NY","CT","RI","MA","VT","NH","ME"]
}

search = ["CA", "FL"]
print([k for k, v in states_dict.items() if any(y in v for y in search)])
# ['West', 'East']


答:
First instead of looping through the whole dictionary (using states_dict.items()) use the key to find the value as looping destroys the whole purpose of using a dictionary.

i.e. you should instead use

```<code>.replace(x,states_dic[<state code>])
</code>```

replace the  with the variable that stands for the state code

but for that you must remake your dictionary as

```<code>{<state code>:<east/west/north/south>}
</code>```

for example:

```<code>new_dict = {'CA':'west','OR':'west'...}
</code>```

you can do so by using your existing dictionary

```<code>new_dict = {}
for key, value in states_dict.items():
    for states in value:
         new_dict.update({states:key})
</code>```

Title: Replacing values with dictionary key in python

Body:
First instead of looping through the whole dictionary (using states_dict.items()) use the key to find the value as looping destroys the whole purpose of using a dictionary.

i.e. you should instead use

.replace(x,states_dic[<state code>])

replace the  with the variable that stands for the state code

but for that you must remake your dictionary as

{<state code>:<east/west/north/south>}

for example:

new_dict = {'CA':'west','OR':'west'...}

you can do so by using your existing dictionary

new_dict = {}
for key, value in states_dict.items():
    for states in value:
         new_dict.update({states:key})


问:
what is the syntax for field value increment Firestore in iOS swift?
I need to update a field using Field Value increment in firestore

in Android I can use this syntax:

```<code>FieldValue.increment(1)
</code>```

in the backend, I can use this:

```<code>admin.firestore.FieldValue.increment(1)
</code>```

I have tried to google it, but I can't find the documentation about this increment feature. so I need to know the increment syntax for iOS (swift)

答:
```<code>FieldValue.increment(Int64(1))
</code>```

See the Swift API docs for FieldValue.increment() and the Firebase documentation.

Body:
I need to update a field using Field Value increment in firestore

in Android I can use this syntax:

FieldValue.increment(1)

in the backend, I can use this:

admin.firestore.FieldValue.increment(1)

I have tried to google it, but I can't find the documentation about this increment feature. so I need to know the increment syntax for iOS (swift)

Body:
FieldValue.increment(Int64(1))

See the Swift API docs for FieldValue.increment() and the Firebase documentation.


问:
RegularExpression Validation on a DataBound GridView
Is it possible to validate an already bounded gridview?

```<code>A | B | C | D
2 | 3 | a | 5
</code>```

For example, I wanted to check if the data inside the columns are non-letters.
In this case, I wanted to highlight or something to tell that there's a letter in Column 2 Row 2.

答:
Something like this would do the trick.</p>

```<code>Regex numeric = new Regex(@"^\d+$");

void GridView_RowDataBound(Object sender, GridViewRowEventArgs e) {
    // check out all cells in the current row
    foreach(var cell in e.Row.Cells) {
        // do some validation thingy
        if(!numeric.Match(cell.Text).Success) {
             cell.CssClass = "error"; // put error class on the cell
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to validate an already bounded gridview?

A | B | C | D
2 | 3 | a | 5

For example, I wanted to check if the data inside the columns are non-letters.
In this case, I wanted to highlight or something to tell that there's a letter in Column 2 Row 2.

Body:
Something like this would do the trick.

Regex numeric = new Regex(@"^\d+$");

void GridView_RowDataBound(Object sender, GridViewRowEventArgs e) {
    // check out all cells in the current row
    foreach(var cell in e.Row.Cells) {
        // do some validation thingy
        if(!numeric.Match(cell.Text).Success) {
             cell.CssClass = "error"; // put error class on the cell
        }
    }
}


问:
Pass pyfiles and arguments to DataProcPySparkOperator
I am trying to pass arguments and zipped pyfiles to a temporary Dataproc Cluster in Composer

```<code>spark_args = {
    'conn_id': 'spark_default',
    'num_executors': 2,
    'executor_cores': 2,
    'executor_memory': '2G',
    'driver_memory': '2G',
}

task = dataproc_operator.DataProcPySparkOperator(
                task_id='spark_preprocess_{}'.format(name),
                project_id=PROJECT_ID,
                cluster_name=CLUSTER_NAME,
                region='europe-west4',
                main='gs://my-bucket/dist/main.py',
                pyfiles='gs://my-bucket/dist/jobs.zip',
                dataproc_pyspark_properties=spark_args,
                arguments=['--name', 'test', '--date', self.date_exec],
                dag=subdag
            )
</code>```

But I get the following error, any idea how to correctly format the arguments?

Invalid value at 'job.pyspark_job.properties[1].value' (TYPE_STRING)

答:
As pointed out in the comment, the issues is that spark_args has non-string values, but it should contain only strings per error message:

```<code>Invalid value at 'job.pyspark_job.properties[1].value' (TYPE_STRING)
</code>```

Body:
I am trying to pass arguments and zipped pyfiles to a temporary Dataproc Cluster in Composer

spark_args = {
    'conn_id': 'spark_default',
    'num_executors': 2,
    'executor_cores': 2,
    'executor_memory': '2G',
    'driver_memory': '2G',
}

task = dataproc_operator.DataProcPySparkOperator(
                task_id='spark_preprocess_{}'.format(name),
                project_id=PROJECT_ID,
                cluster_name=CLUSTER_NAME,
                region='europe-west4',
                main='gs://my-bucket/dist/main.py',
                pyfiles='gs://my-bucket/dist/jobs.zip',
                dataproc_pyspark_properties=spark_args,
                arguments=['--name', 'test', '--date', self.date_exec],
                dag=subdag
            )

But I get the following error, any idea how to correctly format the arguments?

Invalid value at 'job.pyspark_job.properties[1].value' (TYPE_STRING)

Body:
As pointed out in the comment, the issues is that spark_args has non-string values, but it should contain only strings per error message:

Invalid value at 'job.pyspark_job.properties[1].value' (TYPE_STRING)


问:
WordPress get_template_part pass variable
Is there a way of passing a variable to get_template_part() in wordpress:

```<code><?php get_template_part( 'element-templates/front', 'top' ); ?>
<?php get_template_part( 'element-templates/front', 'main' ); ?>
</code>```

In the front-top.php and front-main.php (which the above is calling) I need to access numeric variables (a different one for each section). Is there a way of passing a variable to each of the calls above?

Thank you

答:
The core get_template_part() function doesn't support the passing of variables. It only accepts two parameters, slug and name. While there is no built-in solution to this problem, the best approach is to create a function that closely mimics get_template_part() to handle it.

Normally I would create a function that just takes the name of the template file and the variables I want to pass in as an array. In your example however, you're using both arguments for get_template_part() already which means you'll need a slightly more complex function. I'm going to post both versions below.

Simplified Version - Name (slug) and Data

```<code>function wpse_get_partial($template_name, $data = []) {
    $template = locate_template($template_name . '.php', false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}
</code>```

Usage example: wpse_get_partial('header-promotion', ['message' => 'Example message']);

This would load up a file named header-promotion.php with $message available inside of it. Since the second parameter is an array, you can pass in as many variables as you need.

Copy of get_template_part - adding a third parameter

If you don't need both $slug and $name when you call get_template_part(), you probably want the simplified version. For those that do, here's the more complex option.

```<code>function wpse_get_template_part($slug, $name = null, $data = []) {
    // here we're copying more of what get_template_part is doing.
    $templates = [];
    $name = (string) $name;

    if ('' !== $name) {
        $templates[] = "{$slug}-{$name}.php";
    }

    $templates[] = "{$slug}.php";

    $template = locate_template($templates, false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}
</code>```

Usage example: wpse_get_template_part('header-promotion', 'top', [$message => 'Example message']);

Neither function is a perfect copy of get_template_part(). I've skipped all of the extra filters the core function uses for the sake of simplicity.

What about globals or query vars

Globals are pretty commonplace in WordPress but are generally best avoided. They will work but start to get messy when you use the same template part more than once on a single page.

Query vars (get_query_var() / set_query_var()) aren't made for that purpose. It's a hacky workaround that can introduce unintended side-effects.

Body:
Is there a way of passing a variable to get_template_part() in wordpress:

<?php get_template_part( 'element-templates/front', 'top' ); ?>
<?php get_template_part( 'element-templates/front', 'main' ); ?>

In the front-top.php and front-main.php (which the above is calling) I need to access numeric variables (a different one for each section). Is there a way of passing a variable to each of the calls above?

Thank you

Body:
The core get_template_part() function doesn't support the passing of variables. It only accepts two parameters, slug and name. While there is no built-in solution to this problem, the best approach is to create a function that closely mimics get_template_part() to handle it.

Normally I would create a function that just takes the name of the template file and the variables I want to pass in as an array. In your example however, you're using both arguments for get_template_part() already which means you'll need a slightly more complex function. I'm going to post both versions below.

Simplified Version - Name (slug) and Data

function wpse_get_partial($template_name, $data = []) {
    $template = locate_template($template_name . '.php', false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}

Usage example: wpse_get_partial('header-promotion', ['message' => 'Example message']);

This would load up a file named header-promotion.php with $message available inside of it. Since the second parameter is an array, you can pass in as many variables as you need.

Copy of get_template_part - adding a third parameter

If you don't need both $slug and $name when you call get_template_part(), you probably want the simplified version. For those that do, here's the more complex option.

function wpse_get_template_part($slug, $name = null, $data = []) {
    // here we're copying more of what get_template_part is doing.
    $templates = [];
    $name = (string) $name;

    if ('' !== $name) {
        $templates[] = "{$slug}-{$name}.php";
    }

    $templates[] = "{$slug}.php";

    $template = locate_template($templates, false);

    if (!$template) {
        return;
    }

    if ($data) {
        extract($data);
    }

    include($template);
}

Usage example: wpse_get_template_part('header-promotion', 'top', [$message => 'Example message']);

Neither function is a perfect copy of get_template_part(). I've skipped all of the extra filters the core function uses for the sake of simplicity.

What about globals or query vars

Globals are pretty commonplace in WordPress but are generally best avoided. They will work but start to get messy when you use the same template part more than once on a single page.

Query vars (get_query_var() / set_query_var()) aren't made for that purpose. It's a hacky workaround that can introduce unintended side-effects.


问:
How to kill a running Spark application?
I have a running Spark application where it occupies all the cores where my other applications won't be allocated any resource.

I did some quick research and people suggested using YARN kill or /bin/spark-class to kill the command. However, I am using CDH version and /bin/spark-class doesn't even exist at all, YARN kill application doesn't work either.

Can anyone with me with this?

答:
This might not be an ethical and preferred solution but it helps in environments where you can't access the console to kill the job using yarn application command.

Steps are

Go to application master page of spark job.
Click on the jobs section.
Click on the active job's active stage.
You will see "kill" button right next to the active stage.

This works if the succeeding stages are dependent on the currently running stage. Though it marks job as " Killed By User"


问:
Laravel: Mailgun dynamic sending domain with queue
I need to change the sending domain on some emails sent from Laravel. To do so, I have set up a queued job, and the in handle method configure the Swift_SmtpTransport object as described here: Laravel Mail Queue: change transport on fly

```<code>public function handle(Mailer $mailer)
{
    $transport = new \Swift_SmtpTransport(config('mail.host'), config('mail.port'), config('mail.encryption'));

    $transport->setUsername(config('mail.username'));
    $transport->setPassword(config('mail.password'));
    $transport->setLocalDomain(env('MAILGUN_EMAIL_DOMAIN'));

    $smtp = new \Swift_Mailer($transport);

    $mailer->setSwiftMailer($smtp);

    $mailer->send('emails.email', ['data'], function ($m) {
        $m->setTo($this->to)
          ->setBody($this->email->emailResponse)
          ->setSubject(sprintf('%s [Ref: #%s]', $this->email->emailThread->subject, $this->email->emailThread->slug));
    });
}
</code>```

For some reason Mailgun doesn't like my login details.

When I send an email via the Mail facade, it works, so my logins are correct.

```<code>Failed to authenticate on SMTP server with username "xxx" using 2 possible authenticators. Authenticator LOGIN returned Swift_TransportException: Expected response code 235 but got code "535", with message "535 5.7.0 Mailgun is not loving your login or password
" in /home/vagrant/code/myapp/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:457
</code>```

In mail.php I have:

```<code>'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),
</code>```

What gives?

答:
if you have the same key for 2 domains on MAILGUN

```<code> $transport = (new TransportManager(app()))->driver('mailgun');
 $transport->setDomain('yourdomain.com');
 FacadeMail::setSwiftMailer(new Swift_Mailer($transport));
 parent::send($mailer);
</code>```

you can put this before sending your mail.
it works also on queues

Body:
I need to change the sending domain on some emails sent from Laravel. To do so, I have set up a queued job, and the in handle method configure the Swift_SmtpTransport object as described here: Laravel Mail Queue: change transport on fly

public function handle(Mailer $mailer)
{
    $transport = new \Swift_SmtpTransport(config('mail.host'), config('mail.port'), config('mail.encryption'));

    $transport->setUsername(config('mail.username'));
    $transport->setPassword(config('mail.password'));
    $transport->setLocalDomain(env('MAILGUN_EMAIL_DOMAIN'));

    $smtp = new \Swift_Mailer($transport);

    $mailer->setSwiftMailer($smtp);

    $mailer->send('emails.email', ['data'], function ($m) {
        $m->setTo($this->to)
          ->setBody($this->email->emailResponse)
          ->setSubject(sprintf('%s [Ref: #%s]', $this->email->emailThread->subject, $this->email->emailThread->slug));
    });
}

For some reason Mailgun doesn't like my login details.

When I send an email via the Mail facade, it works, so my logins are correct.

Failed to authenticate on SMTP server with username "xxx" using 2 possible authenticators. Authenticator LOGIN returned Swift_TransportException: Expected response code 235 but got code "535", with message "535 5.7.0 Mailgun is not loving your login or password
" in /home/vagrant/code/myapp/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:457

In mail.php I have:

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

What gives?

Body:
if you have the same key for 2 domains on MAILGUN

 $transport = (new TransportManager(app()))->driver('mailgun');
 $transport->setDomain('yourdomain.com');
 FacadeMail::setSwiftMailer(new Swift_Mailer($transport));
 parent::send($mailer);

you can put this before sending your mail.
it works also on queues


问:
Image Swap -- Uncaught TypeError: Cannot set property 'src' of null
I'm working through the textbook for a class as I usually do for practice.  I'm currently working on an image swapping page where clicking on a thumbnail "swaps" out the main image.  The images when clicked become enlarged as if it were a link to another web page.  My code is exactly as it is in the book but I get an error.  The code is:

```<code>var $ = function(id){
return document.getElementById(id);
};

window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");

var imageLinks = listNode.getElementsByTagName("a");

// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
    linkNode = imageLinks[i];

    // preload image
    image = new Image();
    image.src = linkNode.getAttribute("href");

    // attach event handler
    linkNode.onclick = function(evt){
        link = this;  // "this" is the link that was clicked

        // set new image and caption
        // the image selected is the "href" and the caption is the title of each image link
        imageNode.src = link.getAttribute("href");
        captionNode.firstChild.nodeValue = link.getAttribute("title");

        // cancel the default action of the event
        if (!evt){
            evt = window.event;
        }
        if (evt.preventDefault){
            evt.preventDefault();
        }else{
            evt.returnFalse = false;
        }
    };
}
// set focus on first image link
imageLinks[0].focus();
</code>```

};`

The error is thrown at imageNode.src = link.getAttribute("href");
My HTML is:

```<code><body>
        <h1>Image Swap With JavaScript</h1>
        <p>Click on an image to enlarge.</p>
        <ul id="image_list">
            <li><a href="images/photo1.jpg" title="Golden Gate">
                <img src="thumbnails/thumb1.jpg" alt=""></a></li>
            <li><a href="images/photo2.jpg" title="Rocky Coast">
                <img src="thumbnails/thumb2.jpg" alt=""></a></li>
            <li><a href="images/photo3.jpg" title="Ocean Side">
                <img src="thumbnails/thumb3.jpg" alt=""></a></li>
        </ul>
        <h2 id="caption">Ocean Side</h2>
        <p><img id="main-image" src="images/photo3.jpg" alt=""></p>
    </body>
</code>```

Why am I getting this error?

答:
Answer first,then lecture... the mistake in your code is,

 // from html
var imageNode = $("main_image"); // from javascript

id's don't match, its a simple typo, main_image (never equals) main-image

either use

 // from html
var imageNode = $("main-image"); // from javascript

or

 // from html
var imageNode = $("main_image"); // from javascript

Now to understand such typos, pay attention to your code and variables... happy coding  :)

Body:
I'm working through the textbook for a class as I usually do for practice.  I'm currently working on an image swapping page where clicking on a thumbnail "swaps" out the main image.  The images when clicked become enlarged as if it were a link to another web page.  My code is exactly as it is in the book but I get an error.  The code is:

var $ = function(id){
return document.getElementById(id);
};

window.onload = function(){
var listNode = $("image_list");
var captionNode = $("caption");
var imageNode = $("main_image");

var imageLinks = listNode.getElementsByTagName("a");

// process image links
var i, image, linkNode, link;
for (i = 0; i < imageLinks.length; i++){
    linkNode = imageLinks[i];

    // preload image
    image = new Image();
    image.src = linkNode.getAttribute("href");

    // attach event handler
    linkNode.onclick = function(evt){
        link = this;  // "this" is the link that was clicked

        // set new image and caption
        // the image selected is the "href" and the caption is the title of each image link
        imageNode.src = link.getAttribute("href");
        captionNode.firstChild.nodeValue = link.getAttribute("title");

        // cancel the default action of the event
        if (!evt){
            evt = window.event;
        }
        if (evt.preventDefault){
            evt.preventDefault();
        }else{
            evt.returnFalse = false;
        }
    };
}
// set focus on first image link
imageLinks[0].focus();

};`

The error is thrown at imageNode.src = link.getAttribute("href");
My HTML is:

Image Swap With JavaScript

Click on an image to enlarge.

Ocean Side

Why am I getting this error?

Body:
Answer first,then lecture... the mistake in your code is,

<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript

id's don't match, its a simple typo, main_image (never equals) main-image

either use
<p><img id="main-image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main-image"); // from javascript

or

<p><img id="main_image" src="images/photo3.jpg" alt=""></p> // from html
var imageNode = $("main_image"); // from javascript

Now to understand such typos, pay attention to your code and variables... happy coding  :)


问:
Is it possible to prevent a child method from running by using 'return' in the base class method when overriding?
It must be a weird question, but why this logic below doesn't work?

```<code>public class Base
{
    public virtual void Method()
    {
        return;
    }
}

public class Child : Base
{
    public override void Method()
    {
        base.Method();        // If this calls 'return;' here,
        print("still here");  // then why this is still running?
    }
}
</code>```

What happens to the 'return' here? Why the program skips it?

答:
There is no return there. simple as that

A method will execute until it hits a return, the end of the method, or throw's an exception. In your case there is no return

```<code>base.Method();         // do something
print("still here");   // do something else
// end of method, stop doing stuff
</code>```

Additional Resources

Methods (C# Programming Guide)

A method is a code block that contains a series of statements. A
  program causes the statements to be executed by calling the method and
  specifying any required method arguments. In C#, every executed
  instruction is performed in the context of a method.

Return values

The return keyword also stops the execution of the method. If the
  return type is void, a return statement without a value is still
  useful to stop the execution of the method. Without the return
  keyword, the method will stop executing when it reaches the end of the
  code block.

A great clarifying comment from Dave S

The return just returns from the function / method you called back to the caller. Return in a called function / method does not make the caller itself return. The fact that the method is in the base class is irrelevant.

Body:
It must be a weird question, but why this logic below doesn't work?

public class Base
{
    public virtual void Method()
    {
        return;
    }
}

public class Child : Base
{
    public override void Method()
    {
        base.Method();        // If this calls 'return;' here,
        print("still here");  // then why this is still running?
    }
}

What happens to the 'return' here? Why the program skips it?

Body:
There is no return there. simple as that

A method will execute until it hits a return, the end of the method, or throw's an exception. In your case there is no return

base.Method();         // do something
print("still here");   // do something else
// end of method, stop doing stuff

Additional Resources

Methods (C# Programming Guide)

A method is a code block that contains a series of statements. A
  program causes the statements to be executed by calling the method and
  specifying any required method arguments. In C#, every executed
  instruction is performed in the context of a method.

Return values

The return keyword also stops the execution of the method. If the
  return type is void, a return statement without a value is still
  useful to stop the execution of the method. Without the return
  keyword, the method will stop executing when it reaches the end of the
  code block.

A great clarifying comment from Dave S

The return just returns from the function / method you called back to the caller. Return in a called function / method does not make the caller itself return. The fact that the method is in the base class is irrelevant.


问:
Connection to DB2 through JDBC in Shell Script
I want to connect DB2 Database through JDBC in Shell Script on Linux Server

I have the jdbc details
jdbc:db2://10.XXX.XXX.XX:/

I know we can connect using "Db2 Connect" command but DBA  is not recommending that. They are asking to use jdbc only.

Appreciate your help of you can point to any sample script.

thanks,
Rajesh

答:
One way to script with jdbc only, is to use the IBM supplied CLPPlus command. That is a java application. It tries to emulate many of the functions of the Oracle SQL*Plus tool.  This is well explained in the Db2 Knowledge Center.

CLPPlus has some restrictions and may not be available in smaller footprint clients , refer to documentation.

However, almost all legacy Db2 environments use the regular db2 command when scripting in shell , because it is the most secure, most flexible , most mature, and smallest footprint tool for that purpose. But it is native code (C/C++) and not java.  So you should ask that DBA to explain the rationale for not recommending that method.


问:
How "ORDER BY" ordered if they are same value?
Let's say there's table:

```<code>name | score
A      100
B      98
C      99
D      99
E      99
F      98
</code>```

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

答:
SQLite stores row in a table in an unspecified order. It means that the rows in the table may or may not be in the order that they were inserted.

If you use the  SELECT statement to query data from a table, the order of rows in the result set is unspecified. To sort the result set, you add the ORDER BY clause in the  SELECT statement as follows:

```<code>SELECT
   select_list
FROM
   table
ORDER BY
    column_1 ASC,
    column_2 DESC;
</code>```

I hope this link may help you.

Body:
Let's say there's table:

name | score
A      100
B      98
C      99
D      99
E      99
F      98

and request sql = 'select * from table order by score desc'

I know order's gonna be 100, 99, 99, 99, 98, 98 but there are several values in 99 and 98.

I'm using MyIsam and want to make sure the order in the 99 and 98 is not changed even though I delete some element.
 For example, if the order was C->D->E and I delete D, then I expect to be C->E but no E->C.
Is there any logic it works when there's same order value?

Body:
SQLite stores row in a table in an unspecified order. It means that the rows in the table may or may not be in the order that they were inserted.

If you use the  SELECT statement to query data from a table, the order of rows in the result set is unspecified. To sort the result set, you add the ORDER BY clause in the  SELECT statement as follows:

SELECT
   select_list
FROM
   table
ORDER BY
    column_1 ASC,
    column_2 DESC;

I hope this link may help you.


问:
Elastic Search Date Range Query
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

```<code>                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",
</code>```

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

```<code>{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}
</code>```

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

```<code>PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}
</code>```

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

```<code>  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '
</code>```

答:
As @jzzfs suggested the idea is to add a date sub-field to the starttime field. You first need to modify the mapping like this:

```<code>PUT meetings/_mapping
{
  "properties": {
     "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          },
          "date": {
            "type" : "date",
            "format" : "yyyy-MM-dd HH:mm:ss",
          }
        }
     }
  }
}
</code>```

When done, you need to reindex your data using the update by query API so that the starttime.date field gets populated and index:

```<code>POST meetings/_update_by_query
</code>```

When the update is done, you'll be able to leverage the starttime.date sub-field in your query:

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "starttime.date": {
              "gte": "2020-01-02 12:30:00",
              "lte": "2020-01-10 12:30:00"
            }
          }
        }
      ]
    }
  }
}
</code>```

Title: Elastic Search Date Range Query

Body:
I am new to elastic search and I am struggling with date range query. I have to query the records which fall between some particular dates.The JSON records pushed into elastic search database are as follows:

                "messageid": "Some message id",
                "subject": "subject",
                "emaildate": "2020-01-01 21:09:24",
                "starttime": "2020-01-02 12:30:00",
                "endtime": "2020-01-02 13:00:00",
                "meetinglocation": "some location",
                "duration": "00:30:00",
                "employeename": "Name",
                "emailid": "abc@xyz.com",
                "employeecode": "141479",
                "username": "username",
                "organizer": "Some name",
                "organizer_email": "cde@xyz.com",

I have to query the records which has start time between "2020-01-02 12:30:00" to "2020-01-10 12:30:00". I have written a query like this :

{
   "query":
      {
        "bool":
           {

              "filter": [
                {
                    "range" : {
                        "starttime": {
                             "gte": "2020-01-02 12:30:00",
                             "lte": "2020-01-10 12:30:00"
                         }
                    }
                }
              ]
           }
      }
}

This query is not giving results as expected. I assume that the person who has pushed the data into elastic search database at my office has not set the mapping and Elastic Search is dynamically deciding the data type of "starttime" as "text". Hence I am getting inconsistent results.
I can set the mapping like this :

PUT /meetings
{
  "mappings": {
    "dynamic": false,
    "properties": {
        .
        .
        .
        .
      "starttime": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
        .
        .
        .
    }
  }
}

And the query will work but I am not allowed to do so (office policies). What alternatives do I have so that I can achieve my task.

Update :

I assumed the data type to be "Text" but by default Elastic Search applies both "Text" and "Keyword" so that we can implement both Full Text and Keyword based searches. If it is also set as "Keyword" . Will this benefit me in any case. I do not have access to lots of stuff in the office that's why I am unable to debug the query.I only have the search API for which I have to build the query.

GET /meetings/_mapping output :

  '
  '
  '
 "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
  }

    '
    '
    '

Body:
As @jzzfs suggested the idea is to add a date sub-field to the starttime field. You first need to modify the mapping like this:

PUT meetings/_mapping
{
  "properties": {
     "starttime" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          },
          "date": {
            "type" : "date",
            "format" : "yyyy-MM-dd HH:mm:ss",
          }
        }
     }
  }
}

When done, you need to reindex your data using the update by query API so that the starttime.date field gets populated and index:

POST meetings/_update_by_query

When the update is done, you'll be able to leverage the starttime.date sub-field in your query:

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "starttime.date": {
              "gte": "2020-01-02 12:30:00",
              "lte": "2020-01-10 12:30:00"
            }
          }
        }
      ]
    }
  }
}


问:
301 redirection in opencart
I am using OpenCart 1.5.6 and I recently moved my store from a subdomain to the main domain. Now I'm trying to redirect some of the old static category pages to the actual opencart category/product pages.

Here is my .htaccess line:

```<code>Redirect 301 /old-category.html http://www.mydomain.com/my-new-category
</code>```

This rule works fine for most of my URLs but for some of them it takes me to:

http://www.mydomain.com/my-new-category?route=old-category.html

Some people suggested to use RewriteRule instead or add a question mark in the end, I did try all that but nothing works !

I also tried putting my rules before and after the following block:

```<code>RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
</code>```

Anyone has any idea ?

答:
I hope it's work for you

```<code>RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Redirect 301 /old-category.html http://www.example.com/my-new-category?
</code>```

Title: 301 redirection in opencart

Body:
I am using OpenCart 1.5.6 and I recently moved my store from a subdomain to the main domain. Now I'm trying to redirect some of the old static category pages to the actual opencart category/product pages.

Here is my .htaccess line:

Redirect 301 /old-category.html http://www.mydomain.com/my-new-category

This rule works fine for most of my URLs but for some of them it takes me to:

http://www.mydomain.com/my-new-category?route=old-category.html

Some people suggested to use RewriteRule instead or add a question mark in the end, I did try all that but nothing works !

I also tried putting my rules before and after the following block:

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Anyone has any idea ?

Body:
I hope it's work for you

RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Redirect 301 /old-category.html http://www.example.com/my-new-category?


问:
Catalyst Sidebar
I'm working through this tutorial from apple. I am getting stuck on the shown below, I keep getting an error, Use of unresolved identifier 'window'

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let splitViewController = window!.rootViewController as! UISplitViewController
    let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
    navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem

    // Add a translucent background to the primary view controller.
    splitViewController.primaryBackgroundStyle = .sidebar

    splitViewController.delegate = self

    return true
}
</code>```

any suggestions?

答:
It is simple. Catalyst apps are by default Window Scene-based. You don’t have a window here. Apple tutorials are outdated.

The solution is to create your own window and fill it in didFinish...

The more correct way is to add your code to delegate of scenes.

Title: Catalyst Sidebar

Body:
I'm working through this tutorial from apple. I am getting stuck on the shown below, I keep getting an error, Use of unresolved identifier 'window'

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let splitViewController = window!.rootViewController as! UISplitViewController
    let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
    navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem

    // Add a translucent background to the primary view controller.
    splitViewController.primaryBackgroundStyle = .sidebar

    splitViewController.delegate = self

    return true
}

any suggestions?


问:
Listing class APIs with parameters and return types
I want to list all the APIs of the given jar ( for which I don't have javadoc) in following fashion any help on that?</p>

```<code>PackageName, ClassName, API Name, ParamName:type;ParameterName:type,ReturnType
</code>```

答:
You can try classdoc, which attempts to generate a javadoc from compiled files and jar archives.

http://classdoc.sourceforge.net/classdoc10/classdoc.html

Body:
I want to list all the APIs of the given jar ( for which I don't have javadoc) in following fashion any help on that?

PackageName, ClassName, API Name, ParamName:type;ParameterName:type,ReturnType


问:
Get the Max and Min value and if values are same then print only one value, Laravel Blade
Fetch the Max and Min Value from the array and if the values are same then print only one value.
Error: I am getting all Price Value in foreach
Eg, Rs 120 120 120 120 120 120</p>

```<code><?php
$maxprice = $product_attributes->max('price');
$minprice = $product_attributes->min('price'); ?>
  @foreach($product_attributes->sortBy('price') as $attribute)
    @if($maxprice === $minprice )
        {{ $attribute->price }}
    @endif
  @endforeach
</code>```

答:
Use groupBy

```<code>@foreach($product_attributes->groupBy('price')->sortBy('price')->values()->all() as $attribute)
{{ $attribute->price }} Rs
@endforeach
</code>```

Body:
Fetch the Max and Min Value from the array and if the values are same then print only one value.
Error: I am getting all Price Value in foreach
Eg, Rs 120 120 120 120 120 120

<?php
$maxprice = $product_attributes->max('price');
$minprice = $product_attributes->min('price'); ?>
  @foreach($product_attributes->sortBy('price') as $attribute)
    @if($maxprice === $minprice )
        {{ $attribute->price }}
    @endif
  @endforeach

Body:
Use groupBy

@foreach($product_attributes->groupBy('price')->sortBy('price')->values()->all() as $attribute)
{{ $attribute->price }} Rs
@endforeach


问:
pixel level multiclass segmentation, issues about training all zero pixel images
I am trying to implement a multiclass semantic segmentation model with 5 different classes.
some of the images have all 5 class ground truth masks, some are not. For example, the image below has all 5 different-class ground truth masks.
enter image description here

My question is, what if I had this image like below to be trained but has no classes in the image. Should I still train this image with 5 channel filled with all zeros?
Does it train the model efficiently, making it reduces false positives?
enter image description here

Thank you in advance!

答:
Your intuition is good.

It is likely that your model will reduce the false positives if you train with all your data; at the same time it may also increase the number of false negatives, as it will be less certain about the important class your want to predict in your CT-scans.

In order to test your assumptions, you must train the same neural network with two different datasets:

One with all the data. Here the imbalance will be much greater. In the end, every medical segmentation problem is by definition highly imbalanced, the more if you have masks with no classes of interest marked. In your case, it is even more imbalanced: depending on the nature of your problem, there can be imbalance even between your 5 classes together with the background/classes of interest one.

One with data where masks are marked with the class you are trying to predict.

Then, test these models on your test set, and see which one does better with FP/FN.


问:
Openpyxl: Concatenation of several columns into one cell per row (Multi-row)
This question is a follow up to: Openpyxl: TypeError - Concatenation of several columns into one cell per row

What I want to do:
I want to concatenate the cells from columns F to M per row and put the concatenated value into column E like below. This needs to be done for all rows at the same time.

Input:

```<code>A B C D E F   G   H  .. M
.......   E1  90  2A .. 26
.......   0   80  F8 ..
</code>```

Output:

```<code>A B C D E         F   G   H  .. M
....... E1902A..26
....... 080F8..
</code>```

Code:

```<code>def concat_f_to_m():
    for row_value in range(1, sheet.max_row+1):
        values=[]
        del values[:]
        for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
            for cell in row:
                if cell.value != None:
                    values.append(str(cell.value))

                else:
                    del values[:]
                    pass

            sheet[f'E{row_value}'].value= ''.join(values)

concat_f_to_m()
</code>```

Also I have set the max column to column N (14) as the longest code goes until column M and I want to stop the loop once there is no entry found in order to go out and join the list's items. I cannot overcome the issue that despite a print of the values list shows only the row's items, it does not write it down into the cell.
Could you give me a hint how to concatenate through all rows by joining the values list at the certain row? Thank you!

答:
Correct implementation:</p>

```<code>def concat_f_to_m():
for row_value in range(1, sheet.max_row+1):
    values=[]
    del values[:]
    for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
        for cell in row:
            if cell.value != None:

                values.append(str(cell.value))
                sheet[f'E{row_value}'].value= ''.join(values)
            else:
                del values[:]
                break

concat_f_to_m()
</code>```

Body:
This question is a follow up to: Openpyxl: TypeError - Concatenation of several columns into one cell per row

What I want to do:
I want to concatenate the cells from columns F to M per row and put the concatenated value into column E like below. This needs to be done for all rows at the same time.

Input:

A B C D E F   G   H  .. M
.......   E1  90  2A .. 26
.......   0   80  F8 ..

Output:

A B C D E         F   G   H  .. M
....... E1902A..26
....... 080F8..

Code:

def concat_f_to_m():
    for row_value in range(1, sheet.max_row+1):
        values=[]
        del values[:]
        for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
            for cell in row:
                if cell.value != None:
                    values.append(str(cell.value))

                else:
                    del values[:]
                    pass

            sheet[f'E{row_value}'].value= ''.join(values)

concat_f_to_m()

Also I have set the max column to column N (14) as the longest code goes until column M and I want to stop the loop once there is no entry found in order to go out and join the list's items. I cannot overcome the issue that despite a print of the values list shows only the row's items, it does not write it down into the cell.
Could you give me a hint how to concatenate through all rows by joining the values list at the certain row? Thank you!

Body:
Correct implementation:

def concat_f_to_m():
for row_value in range(1, sheet.max_row+1):
    values=[]
    del values[:]
    for row in sheet.iter_rows(min_col=6, max_col=14, min_row=row_value, max_row=row_value):
        for cell in row:
            if cell.value != None:

                values.append(str(cell.value))
                sheet[f'E{row_value}'].value= ''.join(values)
            else:
                del values[:]
                break

concat_f_to_m()


问:
Problem assigning probabilities in sample function
I have generated a bunch of variables through the following :

```<code>max_no=10
list2env(setNames(as.list(c(0.2, 0.25,0.15, 0.1, 0.1, 0.05, 0.03, 0.06, 0.03, 0.02, 0.01)), paste0("proportion", 0:max_no)), envir = .GlobalEnv)
</code>```

These generate objects like "proportion0", "proportion1",..., "proportion10" with values 0.2, 0.25.... etc.

I want to plug these proportion values as a vector of probabilities into the sample function like the following:

```<code>sample(seq.int(0, max_no, 1), size=10000, replace=TRUE, prob=c(paste0("proportion", 0:max_no)))
</code>```

But I get the error message: Error in sample.int(length(x), size, replace, prob) : NA in probability vector

What would be a simple way of feeding in the probabilities?

答:
I am not sure what is the use-case for this but you can use mget and unlist

```<code>sample(seq.int(0, max_no, 1), size=10000, replace=TRUE,
       prob=unlist(mget(c(paste0("proportion", 0:max_no)))))
</code>```

Why not pass probability directly instead of storing each number in a different variable?

```<code>sample(seq.int(0, max_no, 1), size=10000, replace=TRUE,
       prob=c(0.2, 0.25,0.15, 0.1, 0.1, 0.05, 0.03, 0.06, 0.03, 0.02, 0.01))
</code>```

Body:
I have generated a bunch of variables through the following :

max_no=10
list2env(setNames(as.list(c(0.2, 0.25,0.15, 0.1, 0.1, 0.05, 0.03, 0.06, 0.03, 0.02, 0.01)), paste0("proportion", 0:max_no)), envir = .GlobalEnv)

These generate objects like "proportion0", "proportion1",..., "proportion10" with values 0.2, 0.25.... etc.

I want to plug these proportion values as a vector of probabilities into the sample function like the following:

sample(seq.int(0, max_no, 1), size=10000, replace=TRUE, prob=c(paste0("proportion", 0:max_no)))

But I get the error message: Error in sample.int(length(x), size, replace, prob) : NA in probability vector

What would be a simple way of feeding in the probabilities?

Body:
I am not sure what is the use-case for this but you can use mget and unlist

sample(seq.int(0, max_no, 1), size=10000, replace=TRUE,
       prob=unlist(mget(c(paste0("proportion", 0:max_no)))))

Why not pass probability directly instead of storing each number in a different variable?

sample(seq.int(0, max_no, 1), size=10000, replace=TRUE,
       prob=c(0.2, 0.25,0.15, 0.1, 0.1, 0.05, 0.03, 0.06, 0.03, 0.02, 0.01))


答:
You can do:</p>

```<code>def func(x):
    d = {}
    ele = x['A'] + x['B']
    for i in x["Distinct Values"]:
        d[i] = ele.count(i)/len(x["Distinct Values"])
    return d

df["Distinct_Values_with_scoring"] = df.apply(func, axis=1)

print(df)
</code>```

Title: How to solve this obscure and excessively localised problem with pandas?

Body:
I have this data frame wherein I want to give a score to each of the element in a distinct values column.

+-------------------------------+-------------------------------+------------------------------+
|            A                  |             B                 |      Distinct Values         |
+-------------------------------+-------------------------------+------------------------------+
| ['a', 'b', 'c']               |   ['a', 'b']                  |  ['a', 'b', 'c']             |
| ['c', 'b', 'e', 'a']          |   ['b', 'e', 'a']             |  ['a', 'b', 'e', 'c']        |
| ['a', 'b', 'd', 'e']          |   ['a', 'b', 'c']             |  ['a', 'b', 'd', 'e', 'c']   |
| ['a', 'b', 'c']               |   ['a', 'd', 'c']             |  ['a', 'b', 'c', 'd']        |
|                               |                               |                              |
+-- ----------------------------+-------------------------------+------------------------------+

           ( NO. of times that element has occurred in A and B)
Scoring =  ----------------------------------------------------
               (Total number of elements(Distinct Values))

This is how it would look like after scoring:

+------------------------+--------------------+-----------------------------------------------+
|            A           |         B          |      Distinct_Values_with_scoring             |
+------------------------+--------------------+-----------------------------------------------+
| ['a', 'b', 'c']        |   ['a', 'b']       |['a':2/3, 'b':2/3, 'c':1/3]                    |
| ['c', 'b', 'e', 'a']   |   ['b', 'e', 'a']  |['a':2/4, 'b':2/4, 'e':2/4, 'c':1/4]           |
| ['a', 'b', 'd', 'e']   |   ['a', 'b', 'c']  |['a':2/5, 'b':2/5, 'd':1/5, 'e':1/5, 'c':1/5]  |
| ['a', 'b', 'c']        |   ['a', 'd', 'c']  |['a':2/4, 'b':1/4, 'c':2/4, 'd':1/4]           |
|                        |                    |                                               |
+-- ---------------------+--------------------+-----------------------------------------------+

How can I go about solving this problem in pandas?

d = {"A":[['a', 'b', 'c'], ['c', 'b', 'e', 'a'],
          ['a', 'b', 'd', 'e'], ['a', 'b', 'c']],
     "B": [['a', 'b'],['b', 'e', 'a'],['a', 'b', 'c'],
           ['a', 'd', 'c']],
     "Distinct Values": [['a', 'b', 'c'], ['a', 'b', 'e', 'c'],
           ['a', 'b', 'd', 'e', 'c'], ['a', 'b', 'c', 'd']]}
data = pd.DataFrame(d)

Body:
You can do:

def func(x):
    d = {}
    ele = x['A'] + x['B']
    for i in x["Distinct Values"]:
        d[i] = ele.count(i)/len(x["Distinct Values"])
    return d

df["Distinct_Values_with_scoring"] = df.apply(func, axis=1)

print(df)


答:
First you can find distinct length and all values. Then you can apply value counts on all_values divide by distinct length </p>

```<code>data['all_values'] = data['A'] + data['B']
data['distinct len'] = data['Distinct Values'].apply(len)

data[['all_values', 'distinct len']].apply(lambda x: pd.Series.value_counts(x[0])/x[1], axis = 1)
</code>```

Body:
First you can find distinct length and all values. Then you can apply value counts on all_values divide by distinct length

data['all_values'] = data['A'] + data['B']
data['distinct len'] = data['Distinct Values'].apply(len)

data[['all_values', 'distinct len']].apply(lambda x: pd.Series.value_counts(x[0])/x[1], axis = 1)


问:
Flip (mirror) any object with Three.js

Update 2019

Since r89 three.js will also adjust the faces and normals. To flip/mirror an object simply use:

```<code>object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
</code>```

No other adjustments as shown in the original solution are required. Link to the ticket: Support reflection matrices. #12787

Original question

I'm trying to create an utility that would flip any object in Three.js scene. The flipping itself is the easy bit:

```<code>object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
</code>```

What is proving difficult is fixing faces and normals after the flip. The result looks quite messed up. Images of the source and flipped object: https://dl.dropboxusercontent.com/u/20925853/Flipped.png

I have seen a number of threads where this and similar issues were discussed but did not find anything usable. Does anybody know what I'm missing there? - Thanks!

Sample code on Js fiddle:
https://jsfiddle.net/7dwh084w/

```<code>var renderer;
var scene;
var camera;

function render() {

    renderer.render(scene, camera);
};

function load(callback) {

    new THREE.ColladaLoader().load("https://dl.dropboxusercontent.com/u/20925853/Kitchen.dae", function (result) {

        var mesh = result.scene.children[0].children[0].clone();
        if (callback) callback(mesh);
    });
}

function init() {

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
    camera.position.z = 1000;

    var light = new THREE.DirectionalLight(0xffffff);
    light.position.set(2, 1, 1).normalize();
    scene.add(light);
    var ambient = new THREE.AmbientLight(0x777777);
    scene.add(ambient);

    var controls = new THREE.OrbitControls(camera);
    controls.damping = 0.2;
    controls.addEventListener('change', render);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    load(function (mesh) {

        flipMesh(mesh);

        scene.add(mesh);
        render();
    });

    render();
}

function flipMesh(object3D) {

    object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
    reverseWindingOrder(object3D);
}

function reverseWindingOrder(object3D) {

    // TODO: Something is missing, the objects are flipped alright but the light reflection on them is somehow broken

    if (object3D.type === "Mesh") {

        var geometry = object3D.geometry;

        for (var i = 0, l = geometry.faces.length; i < l; i++) {

            var face = geometry.faces[i];
            var temp = face.a;
            face.a = face.c;
            face.c = temp;

        }

        var faceVertexUvs = geometry.faceVertexUvs[0];
        for (i = 0, l = faceVertexUvs.length; i < l; i++) {

            var vector2 = faceVertexUvs[i][0];
            faceVertexUvs[i][0] = faceVertexUvs[i][2];
            faceVertexUvs[i][2] = vector2;
        }

        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
    }

    if (object3D.children) {

        for (var j = 0, jl = object3D.children.length; j < jl; j++) {

            reverseWindingOrder(object3D.children[j]);
        }
    }
}

init();
</code>```

答:
I use this code in my project to flip objects:

```<code>    const scale = new THREE.Vector3(1, 1, 1);
    if (flipX) {
        scale.x *= -1;
    }
    if (flipY) {
        scale.z *= -1;
    }
    object.scale.multiply(scale);
</code>```

Hope this helps.

Title: Flip (mirror) any object with Three.js

Body:
Update 2019

Since r89 three.js will also adjust the faces and normals. To flip/mirror an object simply use:

object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));

No other adjustments as shown in the original solution are required. Link to the ticket: Support reflection matrices. #12787

Original question

I'm trying to create an utility that would flip any object in Three.js scene. The flipping itself is the easy bit:

object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));

What is proving difficult is fixing faces and normals after the flip. The result looks quite messed up. Images of the source and flipped object: https://dl.dropboxusercontent.com/u/20925853/Flipped.png

I have seen a number of threads where this and similar issues were discussed but did not find anything usable. Does anybody know what I'm missing there? - Thanks!

Sample code on Js fiddle:
https://jsfiddle.net/7dwh084w/

var renderer;
var scene;
var camera;

function render() {

    renderer.render(scene, camera);
};

function load(callback) {

    new THREE.ColladaLoader().load("https://dl.dropboxusercontent.com/u/20925853/Kitchen.dae", function (result) {

        var mesh = result.scene.children[0].children[0].clone();
        if (callback) callback(mesh);
    });
}

function init() {

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
    camera.position.z = 1000;

    var light = new THREE.DirectionalLight(0xffffff);
    light.position.set(2, 1, 1).normalize();
    scene.add(light);
    var ambient = new THREE.AmbientLight(0x777777);
    scene.add(ambient);

    var controls = new THREE.OrbitControls(camera);
    controls.damping = 0.2;
    controls.addEventListener('change', render);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    load(function (mesh) {

        flipMesh(mesh);

        scene.add(mesh);
        render();
    });

    render();
}

function flipMesh(object3D) {

    object3D.applyMatrix(new THREE.Matrix4().makeScale(-1, 1, 1));
    reverseWindingOrder(object3D);
}

function reverseWindingOrder(object3D) {

    // TODO: Something is missing, the objects are flipped alright but the light reflection on them is somehow broken

    if (object3D.type === "Mesh") {

        var geometry = object3D.geometry;

        for (var i = 0, l = geometry.faces.length; i < l; i++) {

            var face = geometry.faces[i];
            var temp = face.a;
            face.a = face.c;
            face.c = temp;

        }

        var faceVertexUvs = geometry.faceVertexUvs[0];
        for (i = 0, l = faceVertexUvs.length; i < l; i++) {

            var vector2 = faceVertexUvs[i][0];
            faceVertexUvs[i][0] = faceVertexUvs[i][2];
            faceVertexUvs[i][2] = vector2;
        }

        geometry.computeFaceNormals();
        geometry.computeVertexNormals();
    }

    if (object3D.children) {

        for (var j = 0, jl = object3D.children.length; j < jl; j++) {

            reverseWindingOrder(object3D.children[j]);
        }
    }
}

init();

Body:
I use this code in my project to flip objects:

    const scale = new THREE.Vector3(1, 1, 1);
    if (flipX) {
        scale.x *= -1;
    }
    if (flipY) {
        scale.z *= -1;
    }
    object.scale.multiply(scale);

Hope this helps.


问:
Why the loop becomes infinite?
How to get out of an infinite loop?

```<code>unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}
</code>```

Help, please.

Thank you!

答:
Make your loop variable an int.

unsigned char can't exceed 255, so incrementing i past that will wrap it to 0.

2*130 is 260, because the type of literal 2 is int, and multiplying an int by unsigned char you get an int.

Thus, when i is an unsigned char, your loop termination condition will never be satisfied since i will always be less than 260, hence the infinite looping.

Title: Why the loop becomes infinite?

Body:
How to get out of an infinite loop?

unsigned char half_limit = 130;

for (unsigned char i = 0; i < 2 * half_limit; ++i)
{
    //smth is happening;
}

Help, please.

Thank you!


问:
WSO2 API User Mangement
I have my own MySql database with users and roles.

How to integrate with WSO2 so that a token can be generated from my MySql database?

答:
If your database schema is not as wos2 IS schemas, you cannot integrate your DB directly. (you can check the DB scripts in the product to see the schema)

If your DB schema is compliant with wso2 IS then follow doc

1.https://is.docs.wso2.com/en/next/setup/changing-to-mysql/#! [IS 5.9 & upwards]
2.https://docs.wso2.com/display/IS570/Configuring+a+JDBC+User+Store [IS5.7]

If it is not compliant then you have two options

Write custom userstore manager and connect your existing DB : https://docs.wso2.com/display/IS570/Writing+a+Custom+User+Store+Manager

Export you users from your current DB to wso2 IS compliant DB. To export user wso2 provide options to use soap endpoint: https://is.docs.wso2.com/en/next/develop/managing-users-and-roles-with-apis/#adduser or rest endpoint: https://is.docs.wso2.com/en/next/develop/scim2-rest-apis/#/Users%20Endpoint/createUser.

Title: WSO2 API User Mangement


问:
How can I perform math operations on binary numbers?
How can I add, subtract, and compare binary numbers in Python without converting them to decimal?</p>

答:
```<code>'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''

def compare(bin1, bin2):
    return bin1.lstrip('0') == bin2.lstrip('0')

def add(bin1, bin2):
    result = ''
    blen = max((len(bin1), len(bin2))) + 1
    bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
    carry_s = '0'
    for b1, b2 in list(zip(bin1, bin2))[::-1]:
        count = (carry_s, b1, b2).count('1')
        carry_s = '1' if count >= 2 else '0'
        result += '1' if count % 2 else '0'
    return result[::-1]

if __name__ == '__main__':
    print(add('101', '100'))
</code>```

I leave the subtraction func as an exercise for the reader.

OwnerDisplayName: EkSwaim

Body:
'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''

def compare(bin1, bin2):
    return bin1.lstrip('0') == bin2.lstrip('0')

def add(bin1, bin2):
    result = ''
    blen = max((len(bin1), len(bin2))) + 1
    bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
    carry_s = '0'
    for b1, b2 in list(zip(bin1, bin2))[::-1]:
        count = (carry_s, b1, b2).count('1')
        carry_s = '1' if count >= 2 else '0'
        result += '1' if count % 2 else '0'
    return result[::-1]

if __name__ == '__main__':
    print(add('101', '100'))

I leave the subtraction func as an exercise for the reader.


问:
How to access last element in a web page when everything has the same class?
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

```<code>message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")
</code>```

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

答:
Use find_elements_by_xpath to do this.It will return a list of matching WebElements.After this you can access the last element by using list[-1]

```<code>message = self.driver.find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")
print(message[-1].text)
</code>```

Docs

Body:
I doubt I made myself clear on the question, but I want to get the last message sent by a person on Discord (via web). The problem is that, when using web inspector for trying to get a unique attribute of the message, I noticed that every other single message has the same class, and there is no other attribute (like class, id, etc) that I can use. I'm new to Selenium and HTML, so I don't know much.

Let's say I have 2 messages. The first says "hello", and the second one "bye". When I type this:

message = self.driver.find_element_by_xpath("//div[contains(concat(' ', normalize-space(@class), ' '), ' markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN ')]")

I get "hello", because both messages share the same class markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN, and apparently the method picks the first one that matches.

I've looked through other similar questions, but the message is unknown so I can't use contains, nor [position()=2] at the end of the find_element_by_xpath method because I don't know the number of the message.

Is there a way of doing that?

Body:
Use find_elements_by_xpath to do this.It will return a list of matching WebElements.After this you can access the last element by using list[-1]

message = self.driver.find_elements_by_xpath("//div[@class='markup-2BOw-j containerCozy-336-Cz markupRtl-3M0hmN']")
print(message[-1].text)

Docs


问:
Webreferences sharing classes
I wrote a few SOAP Webservices in Java, running on a JBoss 5.1.
Two of them share a class, AddressTO. The Webservices are deploying correctly on my ApplycationServer and all went well until I try to use the class addressTO in my C#-client. There are two types in the client application, addressTO and addressTO1. This is a problem because this causes errors like:

```<code>    Fehler  1   Eine implizite Konvertierung vom Typ
    "acsysteme.i4workspace.client.webservices.addressTO1[]" in
    "acsysteme.i4workspace.client.webservices.addressTO[]" ist nicht möglich.
    [...]
</code>```

This means that it is impossible to cast the to types implicitly.
AddressTo is something like a core class which can be used by other webservices.

The webreferences for the C#-client are created by the command

```<code>    wsdl.exe /parameters:CreateWebService.xml
</code>```

The xml-file contains the urls to the differend .wsdl-files of my webservices.

Does someone know how to handle this problem?

答:
Use the /sharetypes option when calling wsdl.exe:

/sharetypes
      Turns on type sharing feature. This feature creates one code file
  with
      a single type definition for identical types shared between
  different
      services (namespace, name and wire signature must be identical).
      Reference the services with http:// URLs as command-line
  parameters
      or create a discomap document for local files.

If the classes match exactly, they should only be generated once if you generate code for both services in a single command. Both services will be using the same class, so no conversion will be necessary.

Edit:

If the XML namespaces do not match (which is a common occurrence), .NET will consider them to be different types, and rightly so. You will either have to fix the web services so the types are exactly the same (recommended), or do conversion between the two generated types. This will result in a lot of boring property assignment code, so you might want to consider using something like AutoMapper to handle the conversion for you.

wsdl.exe should generate partial classes, so if you want, you can define implicit conversions between the different types:

```<code>public static implicit operator addressTO1(addressTO source)
{
    addressTO1 result = new addressTO1();
    // Assign properties, etc.
    return result;
}
</code>```

I'm not usually a big fan of implicit conversions myself, but in this case it might be warranted.

Title: Webreferences sharing classes

Body:
I wrote a few SOAP Webservices in Java, running on a JBoss 5.1.
Two of them share a class, AddressTO. The Webservices are deploying correctly on my ApplycationServer and all went well until I try to use the class addressTO in my C#-client. There are two types in the client application, addressTO and addressTO1. This is a problem because this causes errors like:

    Fehler  1   Eine implizite Konvertierung vom Typ
    "acsysteme.i4workspace.client.webservices.addressTO1[]" in
    "acsysteme.i4workspace.client.webservices.addressTO[]" ist nicht möglich.
    [...]

This means that it is impossible to cast the to types implicitly.
AddressTo is something like a core class which can be used by other webservices.

The webreferences for the C#-client are created by the command

    wsdl.exe /parameters:CreateWebService.xml

The xml-file contains the urls to the differend .wsdl-files of my webservices.

Does someone know how to handle this problem?

Body:
Use the /sharetypes option when calling wsdl.exe:

/sharetypes
      Turns on type sharing feature. This feature creates one code file
  with
      a single type definition for identical types shared between
  different
      services (namespace, name and wire signature must be identical).
      Reference the services with http:// URLs as command-line
  parameters
      or create a discomap document for local files.

If the classes match exactly, they should only be generated once if you generate code for both services in a single command. Both services will be using the same class, so no conversion will be necessary.

Edit:

If the XML namespaces do not match (which is a common occurrence), .NET will consider them to be different types, and rightly so. You will either have to fix the web services so the types are exactly the same (recommended), or do conversion between the two generated types. This will result in a lot of boring property assignment code, so you might want to consider using something like AutoMapper to handle the conversion for you.

wsdl.exe should generate partial classes, so if you want, you can define implicit conversions between the different types:

public static implicit operator addressTO1(addressTO source)
{
    addressTO1 result = new addressTO1();
    // Assign properties, etc.
    return result;
}

I'm not usually a big fan of implicit conversions myself, but in this case it might be warranted.


问:
How to connect react to html using jsx phrase
Thanks for reading this.

In React,

const name = 'test';
const element =
Hello, {name}
;
ReactDOM.render(element, document.getElementById('test'));
```

<p>Meanwhile in html,  </p>

<pre class="lang-html prettyprint-override"><code>...
<div class="article-body">
    <!-- We will put our React component inside this div. -->
    <div id="test"></div>
    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="test.js"></script>
    ...
</code>```

I changed codes from ReactJS

It doesn't work but returning 'Hello' works fine,

which is

const element = 'Hello';
ReactDOM.render(element, domContainer);
```

<p>What's wrong with jsx????
Did I miss something when using jsx?  </p>

<p>Edit :<br>
I've tried  </p>

<pre class="lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
</code>```

but not working either it's "Hello" or
Hello
.

The react code is in test.jsx.

答:
React does not come with JSX transpiler. You will have to explicitly add it to your project. Babel is one such transpiler which can help in understanding JSX syntax.

Add below babel script to your html file

And surround your code with type text/babel like below -

```<code> <script type="text/babel">
    const name = 'test';
    const element = <h1>Hello, {name}</h1>;
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
 </script>
</code>```

This gives a sample example - https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html

Body:
Thanks for reading this.

In React,

const name = 'test';
const element =
Hello, {name}
;
ReactDOM.render(element, document.getElementById('test'));

Meanwhile in html,

...

    ...

I changed codes from ReactJS

It doesn't work but returning 'Hello' works fine,

which is

const element = 'Hello';
ReactDOM.render(element, domContainer);

What's wrong with jsx????
Did I miss something when using jsx?

Edit :

I've tried

but not working either it's "Hello" or
Hello
.

The react code is in test.jsx.

Body:
React does not come with JSX transpiler. You will have to explicitly add it to your project. Babel is one such transpiler which can help in understanding JSX syntax.

Add below babel script to your html file

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

And surround your code with type text/babel like below -

 <script type="text/babel">
    const name = 'test';
    const element = <h1>Hello, {name}</h1>;
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
 </script>

This gives a sample example - https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html


问:
window.open not opening link
I'm trying to open a new window with a share link using the code below:

```<code>        $content .= "<div class='container-after-post'>

        <div class='sharing'>
        <a
        href='$sswc_fb_share_link'
        target='popup'
        rel='noopener noreferrer'
        onclick=window.open($sswc_fb_share_link, popup, width=600, height=600);
      >
        <i class='fab fa-facebook-f'></i>
      </a>
        </div>
    </div>"
</code>```

But it gives me Uncaught SyntaxError: missing ) after argument list whenver I click the link, how do I properly escape the window.open part in my code so it works? Please help!

答:
```<code>See below code helpful.

$content .="<div class='container-after-post'>

        <div class='sharing'>
        <a
        href='$sswc_fb_share_link'
        target='popup'
        rel='noopener noreferrer'
        onclick=\"window.open('$sswc_fb_share_link', popup, width=600, height=600);\">
        <i class='fab fa-facebook-f'></i>
      </a>
        </div>
    </div>";
</code>```

Title: window.open not opening link

Body:
I'm trying to open a new window with a share link using the code below:

        $content .= "

"

But it gives me Uncaught SyntaxError: missing ) after argument list whenver I click the link, how do I properly escape the window.open part in my code so it works? Please help!


问:
How to correct access Hadoop 3.2.1 with Java API?
I installed Hadoop 3.2.1 on remote centos server in a pseudo-distributed mode and and has checked firewall config. I exposed the ports 9000 and 9800-9900。Local environment is windows and a not started hadoop，I must install it or the application will throw an Exception that can't find HADOOP_HOME it also confuse me.

My maven dependencies as follows：

```<code>            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs-client</artifactId>
                <version>3.2.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
                <version>3.2.0</version>
            </dependency>
</code>```

My test as follows:

    @Test
    public void testHDFSRepository() throws IOException {
        Configuration conf= new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        conf.set("fs.defaultFS", "hdfs://remoteip:9000");
        FileSystem fs = FileSystem.get(conf);
        fs.copyFromLocalFile(new Path("C:\\Users\\admin\\Desktop\\111.txt"), new Path("/demo/111.txt"));

    }
```

<p>then it throws an Exception and upload a 0B file toHadoop </p>

```org.apache.hadoop.ipc.RemoteException(java.io.IOException): File /demo/111.txt could only be written to 0 of the 1 minReplication nodes. There are 1 datanode(s) running and 1 node(s) are excluded in this operation.
    at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock(BlockManager.java:2219)
    at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock(FSDirWriteFileOp.java:294)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:2789)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock(NameNodeRpcServer.java:892)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock(ClientNamenodeProtocolServerSideTranslatorPB.java:574)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:528)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:1070)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:999)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:927)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2915)
```

<p>the nameNode logs as follows:</p>

```2020-02-18 19:41:09,526 WARN org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicy: Failed to place enough replicas, still in need of 1 to reach 1 (unavailableStorages=[DISK], storagePolicy=BlockStoragePolicy{HOT:7, storageTypes=[DISK], creationFallbacks=[], replicationFallbacks=[ARCHIVE]}, newBlock=true) All required storage types are unavailable:  unavailableStorages=[DISK], storagePolicy=BlockStoragePolicy{HOT:7, storageTypes=[DISK], creationFallbacks=[], replicationFallbacks=[ARCHIVE]}
2020-02-18 19:41:09,526 INFO org.apache.hadoop.ipc.Server: IPC Server handler 9 on default port 9000, call Call#4 Retry#0 org.apache.hadoop.hdfs.protocol.ClientProtocol.addBlock from xx.xx.xx.xx:13049
java.io.IOException: File /demo/111.txt could only be written to 0 of the 1 minReplication nodes. There are 1 datanode(s) running and 1 node(s) are excluded in this operation.
    at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock(BlockManager.java:2219)
    at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock(FSDirWriteFileOp.java:294)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:2789)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock(NameNodeRpcServer.java:892)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock(ClientNamenodeProtocolServerSideTranslatorPB.java:574)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:528)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:1070)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:999)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:927)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2915)

```

on the other hand, I can use bin/hdfs dfs -put on the remote server successfully。

Look at the error info I only have one dataNode indeed, should I add some datanode?

答:
Your datanode process is not healthy

1 node(s) are excluded in this operation.

You'll need to inspect its logs or the namenode UI to determine the issue

I can use bin/hdfs dfs -put on the remote server successfully

Then download the CLI tools locally and configure it for the remote server

Body:
I installed Hadoop 3.2.1 on remote centos server in a pseudo-distributed mode and and has checked firewall config. I exposed the ports 9000 and 9800-9900。Local environment is windows and a not started hadoop，I must install it or the application will throw an Exception that can't find HADOOP_HOME it also confuse me.

My maven dependencies as follows：

            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs-client</artifactId>
                <version>3.2.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-hdfs</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
                <version>3.2.0</version>
            </dependency>

My test as follows:

    @Test
    public void testHDFSRepository() throws IOException {
        Configuration conf= new Configuration();
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        conf.set("fs.defaultFS", "hdfs://remoteip:9000");
        FileSystem fs = FileSystem.get(conf);
        fs.copyFromLocalFile(new Path("C:\\Users\\admin\\Desktop\\111.txt"), new Path("/demo/111.txt"));

    }

then it throws an Exception and upload a 0B file toHadoop

org.apache.hadoop.ipc.RemoteException(java.io.IOException): File /demo/111.txt could only be written to 0 of the 1 minReplication nodes. There are 1 datanode(s) running and 1 node(s) are excluded in this operation.
    at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock(BlockManager.java:2219)
    at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock(FSDirWriteFileOp.java:294)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:2789)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock(NameNodeRpcServer.java:892)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock(ClientNamenodeProtocolServerSideTranslatorPB.java:574)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:528)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:1070)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:999)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:927)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2915)

the nameNode logs as follows:

2020-02-18 19:41:09,526 WARN org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicy: Failed to place enough replicas, still in need of 1 to reach 1 (unavailableStorages=[DISK], storagePolicy=BlockStoragePolicy{HOT:7, storageTypes=[DISK], creationFallbacks=[], replicationFallbacks=[ARCHIVE]}, newBlock=true) All required storage types are unavailable:  unavailableStorages=[DISK], storagePolicy=BlockStoragePolicy{HOT:7, storageTypes=[DISK], creationFallbacks=[], replicationFallbacks=[ARCHIVE]}
2020-02-18 19:41:09,526 INFO org.apache.hadoop.ipc.Server: IPC Server handler 9 on default port 9000, call Call#4 Retry#0 org.apache.hadoop.hdfs.protocol.ClientProtocol.addBlock from xx.xx.xx.xx:13049
java.io.IOException: File /demo/111.txt could only be written to 0 of the 1 minReplication nodes. There are 1 datanode(s) running and 1 node(s) are excluded in this operation.
    at org.apache.hadoop.hdfs.server.blockmanagement.BlockManager.chooseTarget4NewBlock(BlockManager.java:2219)
    at org.apache.hadoop.hdfs.server.namenode.FSDirWriteFileOp.chooseTargetForNewBlock(FSDirWriteFileOp.java:294)
    at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getAdditionalBlock(FSNamesystem.java:2789)
    at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.addBlock(NameNodeRpcServer.java:892)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.addBlock(ClientNamenodeProtocolServerSideTranslatorPB.java:574)
    at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:528)
    at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:1070)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:999)
    at org.apache.hadoop.ipc.Server$RpcCall.run(Server.java:927)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1730)
    at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2915)

on the other hand, I can use bin/hdfs dfs -put on the remote server successfully。

Look at the error info I only have one dataNode indeed, should I add some datanode?