问:
When Ubuntu 18.04 deploys zabbix4.0, the database type is PostgreSQL instead of MySQL. How can I set this to support MySQL?
In Ubuntu 18.04 server, I use binary file to install zabbix4.0 according to the official website document of zabbix4.0, and I use MySQL 5.7.30 database. After installation, when I configure the front end of zabbix4.0,In the database configuration page, I only see one option of PostgreSQL, not mysql, as shown in the following figure:

In my server, I have installed MySQL version 5.7.30, and imported the data of ZABBIX 4.0 into the ZABBIX database, without any PostgreSQL installed

Excuse me, how can I make zabbix4.0 support MySQL 5.7.30 that I have installed? Thank you!

I installed zabbix4.0 according to the official documents:
https://www.zabbix.com/documentation/4.0/zh/manual/installation/install_from_packages/debian_ubuntu

This is my installation method:

```<code># install zabbix
cd ~/download
wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-
release/zabbix-release_ 4.0-2+bionic_ all.deb
sudo dpkg -i zabbix-release_ 4.0-2+bionic_ all.deb
sudo apt-get update

#install Server/proxy/
sudo apt-get install -y zabbix-server-mysql
sudo apt-get install -y zabbix-frontend-php
</code>```

答:
The current version of the package is 4.0-3, so instead, you must do this :

Install repository

```<code># wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.0-3+bionic_all.deb
# sudo dpkg -i zabbix-release_4.0-3+bionic_all.deb
# sudo apt update
</code>```

Install server, frontend, agent

```<code># sudo apt install zabbix-server-mysql zabbix-frontend-php zabbix-agent
</code>```

Body:
In Ubuntu 18.04 server, I use binary file to install zabbix4.0 according to the official website document of zabbix4.0, and I use MySQL 5.7.30 database. After installation, when I configure the front end of zabbix4.0,In the database configuration page, I only see one option of PostgreSQL, not mysql, as shown in the following figure:

In my server, I have installed MySQL version 5.7.30, and imported the data of ZABBIX 4.0 into the ZABBIX database, without any PostgreSQL installed

Excuse me, how can I make zabbix4.0 support MySQL 5.7.30 that I have installed? Thank you!

I installed zabbix4.0 according to the official documents:
https://www.zabbix.com/documentation/4.0/zh/manual/installation/install_from_packages/debian_ubuntu

This is my installation method:

# install zabbix
cd ~/download
wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-
release/zabbix-release_ 4.0-2+bionic_ all.deb
sudo dpkg -i zabbix-release_ 4.0-2+bionic_ all.deb
sudo apt-get update

#install Server/proxy/
sudo apt-get install -y zabbix-server-mysql
sudo apt-get install -y zabbix-frontend-php

Body:
The current version of the package is 4.0-3, so instead, you must do this :

Install repository

# wget https://repo.zabbix.com/zabbix/4.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_4.0-3+bionic_all.deb
# sudo dpkg -i zabbix-release_4.0-3+bionic_all.deb
# sudo apt update

Install server, frontend, agent

# sudo apt install zabbix-server-mysql zabbix-frontend-php zabbix-agent


来源: stackexchange

问:
How to make tkinter counter when click on botton
i'm beginner for python i try to make counter when click on button but its not working as i expect

what i really need when i click on button its will add number like 1,2,3 but this result is 1111111

```<code>from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")

def count():
    c = 0
    c += 1
    entry.insert(0,c)

button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()
</code>```

答:
This work, try it:</p>

```<code>from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")
global c

def count():
    global c
    c += 1
    entry.delete(0, 'end')
    entry.insert(0,c)

c=0
button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i'm beginner for python i try to make counter when click on button but its not working as i expect

what i really need when i click on button its will add number like 1,2,3 but this result is 1111111

from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")

def count():
    c = 0
    c += 1
    entry.insert(0,c)

button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()

Body:
This work, try it:

from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")
global c

def count():
    global c
    c += 1
    entry.delete(0, 'end')
    entry.insert(0,c)

c=0
button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()


问:
How to set property in Textfield?
I want to set a property for a textField element in the jrxml file.

I have read the answer here and I would like to set the net.sf.jasperreports.text.save.line.breaks property in TextField as mentioned in the comments.

I have tried:

```<code><textField isStretchWithOverflow="true" isBlankWhenNull="true">
    <reportElementx="409" y="170" width="300" height="14"/>
    <textElement>
        <font fontName="Courier New" size="8"/>
    </textElement>
    <property name="net.sf.jasperreports.text.save.line.breaks" value="true"/>
    <textFieldExpression class="java.lang.String"><![CDATA[$F{field}]]></textFieldExpression>
</textField>
</code>```

But the compiler says:

Invalid content was found starting with element 'property'

What is the correct way?

答:
The property element needs to go in reportElement

```<code>        <textField isStretchWithOverflow="true" isBlankWhenNull="true">
            <reportElement key="textField-2" positionType="Float" x="409" y="170" width="300" height="14" stretchType="RelativeToTallestObject" isPrintWhenDetailOverflows="true">
                <property name="net.sf.jasperreports.text.save.line.breaks" value="true"/>
            </reportElement>
            ...
</code>```

Title: How to set property in Textfield?

Body:
I want to set a property for a textField element in the jrxml file.

I have read the answer here and I would like to set the net.sf.jasperreports.text.save.line.breaks property in TextField as mentioned in the comments.

I have tried:

<textField isStretchWithOverflow="true" isBlankWhenNull="true">
    <reportElementx="409" y="170" width="300" height="14"/>
    <textElement>

    </textElement>
    <property name="net.sf.jasperreports.text.save.line.breaks" value="true"/>
    <textFieldExpression class="java.lang.String"><![CDATA[$F{field}]]></textFieldExpression>
</textField>

But the compiler says:

Invalid content was found starting with element 'property'

What is the correct way?

Body:
The property element needs to go in reportElement

        <textField isStretchWithOverflow="true" isBlankWhenNull="true">
            <reportElement key="textField-2" positionType="Float" x="409" y="170" width="300" height="14" stretchType="RelativeToTallestObject" isPrintWhenDetailOverflows="true">
                <property name="net.sf.jasperreports.text.save.line.breaks" value="true"/>
            </reportElement>
            ...


问:
how to detect logout of asp.net 4 session
How do you detect when a user logs out using the ASP.Net 4 session management?  I have a site that is using the <LoginTemplate> with a <LoginStatus> control.  When the user clicks the "Log out" link, it should fire the LoggingOut event of the LoginStatus, but I cannot get it to do so.  Is there another way to detect when the user logs out of the application?  Session_End isn't being fired because the session itself is still valid, just that the user isn't logged in.</p>

答: OK, I found my problem. The LoginTemplate control obliterates the LoginStatus's LoggingOut event. Once I created my own header it works</p>

ContentLicense: CC BY-SA 3.0


问:
`tf.function` decorator causes batch shape to be `NoneType` (Tensorflow2, Python)
In the following code:

@tf.function
def get_x_y(dataset,count=1):
  X = tf.TensorArray(tf.float32,count)
  Y = tf.TensorArray(tf.float32,count)
  idx = tf.Variable(0,dtype=tf.int32)
  for batch in dataset.take(count):
    max_x,max_y,max_z = batch.shape
    x = tf.slice(batch,[0,0,0],[-1,max_y-1,-1])
    y = tf.slice(batch,[0,1,0],[-1,-1,-1 ])
    y = tf.argmax(y,-1)
    y = tf.cast(y,tf.float32)
    X = X.write(idx.numpy(),x)
    Y = Y.write(idx.numpy(),y)
    idx.assign_add(1)
  return X.stack(),Y.stack()
```

<p>Output when using wihtout <code>tf.function</code> decorator is as expected, however with the <code>tf.function</code> decorator, the following error occurs:</p>

<pre class="lang-py prettyprint-override"><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-2306b6173e70> in <module>()
----> 1 print(get_x_y(dataset))nt

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

TypeError: in user code:

    <ipython-input-55-4a32428fa07d>:8 get_x_y  *
        x = tf.slice(batch,[0,0,0],[-1,max_y-1,-1])

    TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
</code>```

Expected output is a 2-tuple of(tensorA,tensorB) of shapes (count,batch_size,batch_seq_len,vocab_size) and (count,batch_size,batch_seq_len) respectively, with

count = argument provided to the function
batch_size = 128
batch_seq_len = ?, max_len(seq_i) for all seq in batch
vocab_size = 78
```

<p>For example, an expected output when the function is not decorated with <code>tf.function</code>:</p>

<pre class="lang-py prettyprint-override"><code>(<tf.Tensor: shape=(1, 128, 262, 78), dtype=float32, numpy=
array([[[[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]]]], dtype=float32)>, <tf.Tensor: shape=(1, 128, 262), dtype=float32, numpy=
array([[[ 7., 53., 69., ...,  0.,  0.,  0.],
        [15., 21.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.],
        ...,
        [15., 77.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.]]], dtype=float32)>)
</code>```

Does anyone have any clue as to why? I suspect it is because the dataset is of the shape <MapDataset shapes: (128, None, 78), types: tf.float32>, however I do not understand why max_y is None because the batch shape is known before looping?

答:
I hope I understood you well:
You have a problem with max_y as none and it is as part of size parameter to tf.slice throw an exception.

strided_slice() requires 4 arguments input_, begin, end, strides.

The functionality of the method is quite simple:
It works like iterating over a loop, where begin is the location of the element in the tensor from where the loop initiates and end is where it stops.

So please try:
Here steps or strides can be dataset.take(count)

```<code>tf.strided_slice(input, [start1, start2, ..., startN],
    [end1, end2, ..., endN], [step1, step2, ..., stepN])

max_y = tf.Variable(np.array(batch)
s = tf.strided_slice(max_y, begin, end, max_y, name='var_slice')
</code>```

Body:
In the following code:

@tf.function
def get_x_y(dataset,count=1):
  X = tf.TensorArray(tf.float32,count)
  Y = tf.TensorArray(tf.float32,count)
  idx = tf.Variable(0,dtype=tf.int32)
  for batch in dataset.take(count):
    max_x,max_y,max_z = batch.shape
    x = tf.slice(batch,[0,0,0],[-1,max_y-1,-1])
    y = tf.slice(batch,[0,1,0],[-1,-1,-1 ])
    y = tf.argmax(y,-1)
    y = tf.cast(y,tf.float32)
    X = X.write(idx.numpy(),x)
    Y = Y.write(idx.numpy(),y)
    idx.assign_add(1)
  return X.stack(),Y.stack()

Output when using wihtout tf.function decorator is as expected, however with the tf.function decorator, the following error occurs:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-2306b6173e70> in <module>()
----> 1 print(get_x_y(dataset))nt

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    966           except Exception as e:  # pylint:disable=broad-except
    967             if hasattr(e, "ag_error_metadata"):
--> 968               raise e.ag_error_metadata.to_exception(e)
    969             else:
    970               raise

TypeError: in user code:

    <ipython-input-55-4a32428fa07d>:8 get_x_y  *
        x = tf.slice(batch,[0,0,0],[-1,max_y-1,-1])

    TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

Expected output is a 2-tuple of(tensorA,tensorB) of shapes (count,batch_size,batch_seq_len,vocab_size) and (count,batch_size,batch_seq_len) respectively, with

count = argument provided to the function
batch_size = 128
batch_seq_len = ?, max_len(seq_i) for all seq in batch
vocab_size = 78

For example, an expected output when the function is not decorated with tf.function:

(<tf.Tensor: shape=(1, 128, 262, 78), dtype=float32, numpy=
array([[[[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        ...,

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]],

        [[0., 1., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 0.],
         [0., 0., 0., ..., 0., 0., 1.],
         ...,
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.],
         [1., 0., 0., ..., 0., 0., 0.]]]], dtype=float32)>, <tf.Tensor: shape=(1, 128, 262), dtype=float32, numpy=
array([[[ 7., 53., 69., ...,  0.,  0.,  0.],
        [15., 21.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.],
        ...,
        [15., 77.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.],
        [15., 77.,  5., ...,  0.,  0.,  0.]]], dtype=float32)>)

Does anyone have any clue as to why? I suspect it is because the dataset is of the shape <MapDataset shapes: (128, None, 78), types: tf.float32>, however I do not understand why max_y is None because the batch shape is known before looping?

Body:
I hope I understood you well:
You have a problem with max_y as none and it is as part of size parameter to tf.slice throw an exception.

strided_slice() requires 4 arguments input_, begin, end, strides.

The functionality of the method is quite simple:
It works like iterating over a loop, where begin is the location of the element in the tensor from where the loop initiates and end is where it stops.

So please try:
Here steps or strides can be dataset.take(count)

tf.strided_slice(input, [start1, start2, ..., startN],
    [end1, end2, ..., endN], [step1, step2, ..., stepN])

max_y = tf.Variable(np.array(batch)
s = tf.strided_slice(max_y, begin, end, max_y, name='var_slice')


问:
How to download latest file or recently added file from Aws S3 using PHP. (Yii2)
I have a non-versioned S3 bucket (VersionId is null for all files), files have different names.
My current code is:

```<code>        $path = $this->key.'/primary/pdfs/'.$id.'/';

        $result = $this->s3->listObjects(['Bucket' => $this->bucket,"Prefix" => $path])->toArray();
       //get the last object from s3
        $object = end($result['Contents']);
        $key = $object['Key'];
        $file = $this->s3->getObject([
            'Bucket' => $this->bucket,
            'Key' => $key
        ]);
       //download the file
        header('Content-Type: application/pdf');
        echo $file['Body'];
</code>```

The above is incorrect as it is giving the end file which is not the latest file.
Do I  need to use the below api call ? if so, how to use it ?

```<code>        $result = $this->s3->listObjectVersions(['Bucket' => $this->bucket,"Prefix" => $path])->toArray();
</code>```

答: Since the VersionId of all files is null, there should be only one version of the files in the bucket</p>

Body:
I have a non-versioned S3 bucket (VersionId is null for all files), files have different names.
My current code is:

        $path = $this->key.'/primary/pdfs/'.$id.'/';

        $result = $this->s3->listObjects(['Bucket' => $this->bucket,"Prefix" => $path])->toArray();
       //get the last object from s3
        $object = end($result['Contents']);
        $key = $object['Key'];
        $file = $this->s3->getObject([
            'Bucket' => $this->bucket,
            'Key' => $key
        ]);
       //download the file
        header('Content-Type: application/pdf');
        echo $file['Body'];

The above is incorrect as it is giving the end file which is not the latest file.
Do I  need to use the below api call ? if so, how to use it ?

        $result = $this->s3->listObjectVersions(['Bucket' => $this->bucket,"Prefix" => $path])->toArray();


问:
NSNumber Formatting (Round to 1000's place)
I currently have a series of NSNumber objects with values between 0 and 500,000. They are randomly generated values with many decimal places.

How can I print these values, but round them to the nearest 1000? For example 32143.8472 would round to 32000. For simplicity, lets assume I want them in a NSLog...

eg.

```<code>NSLog(@"The number is: %@", WHATGOESHERE??)
</code>```

答:
NSNumber objects are suitable for storing values, for numeric operations you should use plain numeric types (e.g. int)

Try the following code:

```<code>int rounded = 1000*(([number intValue]+500)/1000);
</code>```

What happens there:

[number intValue]

That gets integer part of our number

add 500 and divide by 1000 - get the nearest number of thousands in our number

Multiply by 1000 - compensate for previous division to get a number actually rounded to the thousands

And log it if you want:

```<code>NSLog(@"The number is: %d", rounded)
</code>```

Body:
I currently have a series of NSNumber objects with values between 0 and 500,000. They are randomly generated values with many decimal places.

How can I print these values, but round them to the nearest 1000? For example 32143.8472 would round to 32000. For simplicity, lets assume I want them in a NSLog...

eg.

NSLog(@"The number is: %@", WHATGOESHERE??)

Body:
NSNumber objects are suitable for storing values, for numeric operations you should use plain numeric types (e.g. int)

Try the following code:

int rounded = 1000*(([number intValue]+500)/1000);

What happens there:

[number intValue]

That gets integer part of our number

add 500 and divide by 1000 - get the nearest number of thousands in our number

Multiply by 1000 - compensate for previous division to get a number actually rounded to the thousands

And log it if you want:

NSLog(@"The number is: %d", rounded)


问:
Turn a col into rownames in a list of dataframes
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

```<code>DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs
</code>```

Thanks!

Sebastian

答:
Return the changed dataframe in the last line of the function. </p>

```<code>col_to_rownames_andDel <- function(df){
   rownames(df) <- df$A
   df$A <- NULL
   return(df)
}

TheList_namedRows <- purrr::map(TheList, col_to_rownames_andDel)
#Using lapply
#TheList_namedRows <- lapply(TheList, col_to_rownames_andDel)

TheList_namedRows
#$DF1
#  B
#A 1
#B 2
#C 3

#$DF2
#  B
#A 1
#B 2
#C 3
</code>```

Body:
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs

Thanks!

Sebastian

Body:
Return the changed dataframe in the last line of the function.

col_to_rownames_andDel <- function(df){
   rownames(df) <- df$A
   df$A <- NULL
   return(df)
}

TheList_namedRows <- purrr::map(TheList, col_to_rownames_andDel)
#Using lapply
#TheList_namedRows <- lapply(TheList, col_to_rownames_andDel)

TheList_namedRows
#$DF1
#  B
#A 1
#B 2
#C 3

#$DF2
#  B
#A 1
#B 2
#C 3


问:
How to unlock a excel VBA project? the known methods are not working
we have an excel file that we were working but unfortunately, the guy who was working has left. we have no way to find the VBA password.

I have tried all the methods that are there on the web that talks about changing the DBP text with hex, but none have worked.

if any great soul wants to have a look at the file, here it is.
https://mega.nz/file/TMwDXZKR#pUQF3HeRm3JIbu1kvOUO6bsU8ConD50A8Tk6F_ny0vY

答:
Take a look at, it provides several methods depending what has been locked actually
https://exceloffthegrid.com/removing-cracking-excel-passwords-with-vba/</p>


问:
Can we place JavaScript Code along c# in .NetCore WebApi
I have a method in my asp.net Core web Api that has for role sending Emails  , using SmtpClient.
the Body of the message is this html string:

```<code>  @"<html>
         <head>
              <style>
                   #modalHeader{
                        background-color:#6495ED;
                        color:white;
                        text-align: center;
                        height:80px;
                       }
                        .example_b {
                                      color: #fff !important;
                                      text-transform: uppercase;
                                      text-decoration: none;
                                      background: #60a3bc;
                                      padding: 20px;
                                      border-radius: 50px;
                                      display: inline-block;
                                      border: none;
                                      transition: all 0.4s ease 0s;
                                     }
                                    .example_b:hover {
                                            text-shadow: 0px 0px 6px rgba(255, 255, 255, 1);
                                            -webkit-box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
                                            -moz-box-shadow: 0px 5px 40px -10px rgba(0,0,0,0.57);
                                            transition: all 0.4s ease 0s;
                                            }
                                </style>
                            </head>
                      <body>
                        <p>Bonjour,<br>
                            Afin d’authentifier votre connexion sur le système de prise de rendez-vous à distance de la " + Structure + @" Nous vous invitons à  confirmer votre mail en cliquant sur ce lien
                         </p>
                    <div style='border:1px solid black'>
                          //<div id='modalHeader'>Confirmation d'Email</div>
                            //<br>
                                //<br>
                            <div id='modalBody'>
                              <div class='button_cont' align='center'>
                                <a class='example_b' href='" + url + "' target='_blank' rel='nofollow noopener'>Confirmer Votre Email</a>" +
                                "</div> </div> <br/> </div> </body> </html>";
</code>```

as you see i m using a href to trigger a call to another method in service , the problem with that is that it opens to me a blank page each time i click the button , so the solution would be to add an event instead to the button using javascript.

My question is how can i add Js to c# code in asp.net core 2.1 ?
is adding just script tag inside the html tag would make the work of letting JS doing the work ?

答:
If you inspect the element in the email are you sure you see the correct url?
If yes maybe it would be worth giving a try to inspect an href link in one email. I checked at the moment and I saw something like that:
It could be worth the try...

Body:
I have a method in my asp.net Core web Api that has for role sending Emails  , using SmtpClient.
the Body of the message is this html string:

  @"

Bonjour,

                            Afin d’authentifier votre connexion sur le système de prise de rendez-vous à distance de la " + Structure + @" Nous vous invitons à  confirmer votre mail en cliquant sur ce lien

                          //
Confirmation d'Email

                            //

                                //

                                Confirmer Votre Email" +
                                "

  ";

as you see i m using a href to trigger a call to another method in service , the problem with that is that it opens to me a blank page each time i click the button , so the solution would be to add an event instead to the button using javascript.

My question is how can i add Js to c# code in asp.net core 2.1 ?
is adding just script tag inside the html tag would make the work of letting JS doing the work ?


问:
How to remove the radio buttons saying "I am a customer " and "I am a vendor" in woocommerce account page?
I have my website built upon wordpress and woocommerce. At the login page of woocommerce there is two radio buttons to select "I am a customer" and another "I am a vendor". I want to remove those two radio buttons with texts too. https://www.osdoc.in/my-account/ : This is the link , under the register section and just below the "login with social ids" icons.</p>

答:
In your child theme, create a folder as "dokan" and inside it create a folder with the name "global".

In "global" folder, create a file as seller-registration-form.php to override default template which you can find from wp-content\plugins\dokan-lite\templates\global

Put the following code in this file. There is no option to ask user type and it will create a seller only.

```<code><?php
/**
 * Dokan Seller registration form
 *
 * @since 2.4
 *
 * @package dokan
 */
$role = 'seller';
$role_style = '';
?>

<div class="show_if_seller" style="<?php echo esc_attr( $role_style ); ?>">

    <div class="split-row form-row-wide">
        <p class="form-row form-group">
            <label for="first-name"><?php esc_html_e( 'First Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
            <input type="text" class="input-text form-control" name="fname" id="first-name" value="<?php if ( ! empty( $postdata['fname'] ) ) echo esc_attr($postdata['fname']); ?>" required="required" />
        </p>

        <p class="form-row form-group">
            <label for="last-name"><?php esc_html_e( 'Last Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
            <input type="text" class="input-text form-control" name="lname" id="last-name" value="<?php if ( ! empty( $postdata['lname'] ) ) echo esc_attr($postdata['lname']); ?>" required="required" />
        </p>
    </div>

    <p class="form-row form-group form-row-wide">
        <label for="company-name"><?php esc_html_e( 'Shop Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
        <input type="text" class="input-text form-control" name="shopname" id="company-name" value="<?php if ( ! empty( $postdata['shopname'] ) ) echo esc_attr($postdata['shopname']); ?>" required="required" />
    </p>

    <p class="form-row form-group form-row-wide">
        <label for="seller-url" class="pull-left"><?php esc_html_e( 'Shop URL', 'dokan-lite' ); ?> <span class="required">*</span></label>
        <strong id="url-alart-mgs" class="pull-right"></strong>
        <input type="text" class="input-text form-control" name="shopurl" id="seller-url" value="<?php if ( ! empty( $postdata['shopurl'] ) ) echo esc_attr($postdata['shopurl']); ?>" required="required" />
        <small><?php echo esc_url( home_url() . '/' . dokan_get_option( 'custom_store_url', 'dokan_general', 'store' ) ); ?>/<strong id="url-alart"></strong></small>
    </p>

    <p class="form-row form-group form-row-wide">
        <label for="shop-phone"><?php esc_html_e( 'Phone Number', 'dokan-lite' ); ?><span class="required">*</span></label>
        <input type="text" class="input-text form-control" name="phone" id="shop-phone" value="<?php if ( ! empty( $postdata['phone'] ) ) echo esc_attr($postdata['phone']); ?>" required="required" />
    </p>

    <?php
    $show_terms_condition = dokan_get_option( 'enable_tc_on_reg', 'dokan_general' );
    $terms_condition_url  = dokan_get_terms_condition_url();

    if ( 'on' === $show_terms_condition && $terms_condition_url ) { ?>
        <p class="form-row form-group form-row-wide">
            <input class="tc_check_box" type="checkbox" id="tc_agree" name="tc_agree" required="required">
            <label style="display: inline" for="tc_agree"><?php echo wp_kses_post( sprintf( __( 'I have read and agree to the <a target="_blank" href="%s">Terms & Conditions</a>.', 'dokan-lite' ), esc_url( $terms_condition_url ) ) ); ?></label>
        </p>
    <?php }

    do_action( 'dokan_seller_registration_field_after' );
    ?>
</div>

<?php do_action( 'dokan_reg_form_field' ); ?>

<p class="form-row form-group user-role" style="display:none;">
    <label class="radio">
        <input type="radio" name="role" value="customer"<?php checked( $role, 'customer' ); ?>>
        <?php esc_html_e( 'I am a customer', 'dokan-lite' ); ?>
    </label>

    <label class="radio">
        <input type="radio" name="role" value="seller"<?php checked( $role, 'seller' ); ?> >
        <?php esc_html_e( 'I am a vendor', 'dokan-lite' ); ?>
    </label>
    <?php do_action( 'dokan_registration_form_role', $role ); ?>
</p>
<script>
jQuery(window).on('load', function() {
    jQuery("#tc_agree").removeAttr("disabled");
    jQuery("#first-name").removeAttr("disabled");
    jQuery("#last-name").removeAttr("disabled");
    jQuery("#shop-phone").removeAttr("disabled");
    jQuery("#company-name").removeAttr("disabled");
    jQuery("#seller-url").removeAttr("disabled");
 });
</script>
</code>```

Body:
In your child theme, create a folder as "dokan" and inside it create a folder with the name "global".

In "global" folder, create a file as seller-registration-form.php to override default template which you can find from wp-content\plugins\dokan-lite\templates\global

Put the following code in this file. There is no option to ask user type and it will create a seller only.

<?php
/**
 * Dokan Seller registration form
 *
 * @since 2.4
 *
 * @package dokan
 */
$role = 'seller';
$role_style = '';
?>

<div class="show_if_seller" style="<?php echo esc_attr( $role_style ); ?>">

    <div class="split-row form-row-wide">
        <p class="form-row form-group">
            <label for="first-name"><?php esc_html_e( 'First Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
            <input type="text" class="input-text form-control" name="fname" id="first-name" value="<?php if ( ! empty( $postdata['fname'] ) ) echo esc_attr($postdata['fname']); ?>" required="required" />
        </p>

        <p class="form-row form-group">
            <label for="last-name"><?php esc_html_e( 'Last Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
            <input type="text" class="input-text form-control" name="lname" id="last-name" value="<?php if ( ! empty( $postdata['lname'] ) ) echo esc_attr($postdata['lname']); ?>" required="required" />
        </p>
    </div>

    <p class="form-row form-group form-row-wide">
        <label for="company-name"><?php esc_html_e( 'Shop Name', 'dokan-lite' ); ?> <span class="required">*</span></label>
        <input type="text" class="input-text form-control" name="shopname" id="company-name" value="<?php if ( ! empty( $postdata['shopname'] ) ) echo esc_attr($postdata['shopname']); ?>" required="required" />
    </p>

    <p class="form-row form-group form-row-wide">
        <label for="seller-url" class="pull-left"><?php esc_html_e( 'Shop URL', 'dokan-lite' ); ?> <span class="required">*</span></label>
        <strong id="url-alart-mgs" class="pull-right"></strong>
        <input type="text" class="input-text form-control" name="shopurl" id="seller-url" value="<?php if ( ! empty( $postdata['shopurl'] ) ) echo esc_attr($postdata['shopurl']); ?>" required="required" />
        <small><?php echo esc_url( home_url() . '/' . dokan_get_option( 'custom_store_url', 'dokan_general', 'store' ) ); ?>/<strong id="url-alart"></strong></small>
    </p>

    <p class="form-row form-group form-row-wide">
        <label for="shop-phone"><?php esc_html_e( 'Phone Number', 'dokan-lite' ); ?><span class="required">*</span></label>
        <input type="text" class="input-text form-control" name="phone" id="shop-phone" value="<?php if ( ! empty( $postdata['phone'] ) ) echo esc_attr($postdata['phone']); ?>" required="required" />
    </p>

    <?php
    $show_terms_condition = dokan_get_option( 'enable_tc_on_reg', 'dokan_general' );
    $terms_condition_url  = dokan_get_terms_condition_url();

    if ( 'on' === $show_terms_condition && $terms_condition_url ) { ?>
        <p class="form-row form-group form-row-wide">
            <input class="tc_check_box" type="checkbox" id="tc_agree" name="tc_agree" required="required">
            <label style="display: inline" for="tc_agree"><?php echo wp_kses_post( sprintf( __( 'I have read and agree to the <a target="_blank" href="%s">Terms &amp; Conditions</a>.', 'dokan-lite' ), esc_url( $terms_condition_url ) ) ); ?></label>
        </p>
    <?php }

    do_action( 'dokan_seller_registration_field_after' );
    ?>
</div>

<?php do_action( 'dokan_reg_form_field' ); ?>

<p class="form-row form-group user-role" style="display:none;">
    <label class="radio">
        <input type="radio" name="role" value="customer"<?php checked( $role, 'customer' ); ?>>
        <?php esc_html_e( 'I am a customer', 'dokan-lite' ); ?>
    </label>

    <label class="radio">
        <input type="radio" name="role" value="seller"<?php checked( $role, 'seller' ); ?> >
        <?php esc_html_e( 'I am a vendor', 'dokan-lite' ); ?>
    </label>
    <?php do_action( 'dokan_registration_form_role', $role ); ?>
</p>
<script>
jQuery(window).on('load', function() {
    jQuery("#tc_agree").removeAttr("disabled");
    jQuery("#first-name").removeAttr("disabled");
    jQuery("#last-name").removeAttr("disabled");
    jQuery("#shop-phone").removeAttr("disabled");
    jQuery("#company-name").removeAttr("disabled");
    jQuery("#seller-url").removeAttr("disabled");
 });
</script>


问:
How to fetch data from custom table in Corda
We are trying to fetch data from the our custom tables using the vault query with state as query criteria. But we get a state with a model class which contains the old values and not the new ones from the database. Can someone point out to an example of fetching the data from a custom table and mapping it to the model class in corda.</p>

答:
Mapping from the schema to state's properties can be provided in the state class by overriding the method generateMappedObject from the QueryableState class. Make sure your state implements QueryableState class.

```<code>@Override public PersistentState generateMappedObject(MappedSchema schema) {
        if (schema instanceof IOUSchemaV1) {
            return new IOUSchemaV1.PersistentIOU(
                    this.lender.getName().toString(),
                    this.borrower.getName().toString(),
                    this.value,
                    this.linearId.getId());
        } else {
            throw new IllegalArgumentException("Unrecognised schema $schema");
        }
    }
</code>```

You can then query the database using vault query like

```<code>QueryCriteria queryCriteria = new QueryCriteria.VaultQueryCriteria().withStatus(Vault.StateStatus.UNCONSUMED);

List<StateAndRef<IOUState>> iouStates = getServiceHub().getVaultService()
                .queryBy(IOUState, queryCriteria).getStates();
</code>```

Body:
Mapping from the schema to state's properties can be provided in the state class by overriding the method generateMappedObject from the QueryableState class. Make sure your state implements QueryableState class.

@Override public PersistentState generateMappedObject(MappedSchema schema) {
        if (schema instanceof IOUSchemaV1) {
            return new IOUSchemaV1.PersistentIOU(
                    this.lender.getName().toString(),
                    this.borrower.getName().toString(),
                    this.value,
                    this.linearId.getId());
        } else {
            throw new IllegalArgumentException("Unrecognised schema $schema");
        }
    }

You can then query the database using vault query like

QueryCriteria queryCriteria = new QueryCriteria.VaultQueryCriteria().withStatus(Vault.StateStatus.UNCONSUMED);

List<StateAndRef<IOUState>> iouStates = getServiceHub().getVaultService()
                .queryBy(IOUState, queryCriteria).getStates();


问:
Storing the active class data in localStorage of browser
I'm trying to store the active class of the clicked link in localStorage when i navigate to other page. How to do it?

A

P

S

```

答:
Assuming that every a has an id, you can set it with Storage.setItem:

```<code>localStorage.setItem(
  'activeListGroupItem',
  $('#collapse2 .list-group-item.active a').attr('id')
);
</code>```

Then you can get it and apply it back with Storage.getItem:

```<code>$('#' + localStorage.getItem('activeListGroupItem'))
  .parent().addClass('active');
</code>```

Body:
Assuming that every a has an id, you can set it with Storage.setItem:

localStorage.setItem(
  'activeListGroupItem',
  $('#collapse2 .list-group-item.active a').attr('id')
);

Then you can get it and apply it back with Storage.getItem:

$('#' + localStorage.getItem('activeListGroupItem'))
  .parent().addClass('active');


问:
Can this unexpected behavior of PrepareConstrainedRegions and Thread.Abort be explained?
I was playing around with Constrained Execution Regions tonight to better round out my understanding of the finer details. I have used them on occasion before, but in those cases I mostly adhered strictly to established patterns. Anyway, I noticed something peculiar that I cannot quite explain.

Consider the following code. Note, I targeted .NET 4.5 and I tested it with a Release build without the debugger attached.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        bool toggle = false;
        bool didfinally = false;
        var thread = new Thread(
            () =>
            {
                Console.WriteLine("running");
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    while (true)
                    {
                      toggle = !toggle;
                    }
                }
                finally
                {
                    didfinally = true;
                }
            });
        thread.Start();
        Console.WriteLine("sleeping");
        Thread.Sleep(1000);
        Console.WriteLine("aborting");
        thread.Abort();
        Console.WriteLine("aborted");
        thread.Join();
        Console.WriteLine("joined");
        Console.WriteLine("didfinally=" + didfinally);
        Console.Read();
    }
}
</code>```

What would you think the output of this program would be?

didfinally=True

didfinally=False

Before you guess read the documentation. I include the pertinent sections below.

A constrained execution region (CER) is part of a mechanism for
  authoring reliable managed code. A CER defines an area in which the
  common language runtime (CLR) is constrained from throwing out-of-band
  exceptions that would prevent the code in the area from executing in
  its entirety. Within that region, user code is constrained from
  executing code that would result in the throwing of out-of-band
  exceptions. The PrepareConstrainedRegions method must immediately
  precede a try block and marks catch, finally, and fault blocks as
  constrained execution regions. Once marked as a constrained region,
  code must only call other code with strong reliability contracts, and
  code should not allocate or make virtual calls to unprepared or
  unreliable methods unless the code is prepared to handle failures. The
  CLR delays thread aborts for code that is executing in a CER.

and

The reliability try/catch/finally is an exception handling mechanism
  with the same level of predictability guarantees as the unmanaged
  version. The catch/finally block is the CER. Methods in the block
  require advance preparation and must be noninterruptible.

My particular concern right now is guarding against thread aborts. There are two kinds: your normal variety via Thread.Abort and then the one where a CLR host can go all medieval on you and do a forced abort. finally blocks are already protected against Thread.Abort to some degree. Then if you declare that finally block as a CER then you get added protection from CLR host aborts as well...at least I think that is the theory.

So based on what I think I know I guessed #1. It should print didfinally=True. The ThreadAbortException gets injected while the code is still in the try block and then the CLR allows the finally block to run as would be expected even without a CER right?

Well, this is not the result I got. I got a totally unexpected result. Neither #1 or #2 happened for me. Instead, my program hung at Thread.Abort. Here is what I observe.

The presence of PrepareConstrainedRegions delays thread aborts inside try blocks.

The absence of PrepareConstrainedRegions allows them in try blocks.

So the million dollar question is why? The documentation does not mention this behavior anywhere that I can see. In fact, most of the stuff I am reading is actually suggesting that you put critical uninterruptable code in the finally block specifically to guard against thread aborts.

Perhaps, PrepareConstrainedRegions delays normal aborts in a try block in addition to the finally block. But CLR host aborts are only delayed in the finally block of a CER? Can anyone provide more clarity on this?

答:
Your unexpected behavior is due to the fact that your code has the maximum reliability.

Define the following methods:

```<code>private static bool SwitchToggle(bool toggle) => !toggle;

[ReliabilityContract(Consistency.WillNotCorruptState,Cer.Success)]
private static bool SafeSwitchToggle(bool toggle) => !toggle;
</code>```

And use them instead of the body of your while cycle. You will notice that when calling SwitchToggle the cycle becomes abortable and when calling SafeSwitchToggle it is no more abortable.

The same goes if you add whichever other methods inside the try block that is not having a Consistency.WillNotCorruptState or Consistency.MayCorruptInstance.

Body:
I was playing around with Constrained Execution Regions tonight to better round out my understanding of the finer details. I have used them on occasion before, but in those cases I mostly adhered strictly to established patterns. Anyway, I noticed something peculiar that I cannot quite explain.

Consider the following code. Note, I targeted .NET 4.5 and I tested it with a Release build without the debugger attached.

public class Program
{
    public static void Main(string[] args)
    {
        bool toggle = false;
        bool didfinally = false;
        var thread = new Thread(
            () =>
            {
                Console.WriteLine("running");
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    while (true)
                    {
                      toggle = !toggle;
                    }
                }
                finally
                {
                    didfinally = true;
                }
            });
        thread.Start();
        Console.WriteLine("sleeping");
        Thread.Sleep(1000);
        Console.WriteLine("aborting");
        thread.Abort();
        Console.WriteLine("aborted");
        thread.Join();
        Console.WriteLine("joined");
        Console.WriteLine("didfinally=" + didfinally);
        Console.Read();
    }
}

What would you think the output of this program would be?

didfinally=True

didfinally=False

Before you guess read the documentation. I include the pertinent sections below.

A constrained execution region (CER) is part of a mechanism for
  authoring reliable managed code. A CER defines an area in which the
  common language runtime (CLR) is constrained from throwing out-of-band
  exceptions that would prevent the code in the area from executing in
  its entirety. Within that region, user code is constrained from
  executing code that would result in the throwing of out-of-band
  exceptions. The PrepareConstrainedRegions method must immediately
  precede a try block and marks catch, finally, and fault blocks as
  constrained execution regions. Once marked as a constrained region,
  code must only call other code with strong reliability contracts, and
  code should not allocate or make virtual calls to unprepared or
  unreliable methods unless the code is prepared to handle failures. The
  CLR delays thread aborts for code that is executing in a CER.

and

The reliability try/catch/finally is an exception handling mechanism
  with the same level of predictability guarantees as the unmanaged
  version. The catch/finally block is the CER. Methods in the block
  require advance preparation and must be noninterruptible.

My particular concern right now is guarding against thread aborts. There are two kinds: your normal variety via Thread.Abort and then the one where a CLR host can go all medieval on you and do a forced abort. finally blocks are already protected against Thread.Abort to some degree. Then if you declare that finally block as a CER then you get added protection from CLR host aborts as well...at least I think that is the theory.

So based on what I think I know I guessed #1. It should print didfinally=True. The ThreadAbortException gets injected while the code is still in the try block and then the CLR allows the finally block to run as would be expected even without a CER right?

Well, this is not the result I got. I got a totally unexpected result. Neither #1 or #2 happened for me. Instead, my program hung at Thread.Abort. Here is what I observe.

The presence of PrepareConstrainedRegions delays thread aborts inside try blocks.

The absence of PrepareConstrainedRegions allows them in try blocks.

So the million dollar question is why? The documentation does not mention this behavior anywhere that I can see. In fact, most of the stuff I am reading is actually suggesting that you put critical uninterruptable code in the finally block specifically to guard against thread aborts.

Perhaps, PrepareConstrainedRegions delays normal aborts in a try block in addition to the finally block. But CLR host aborts are only delayed in the finally block of a CER? Can anyone provide more clarity on this?

Body:
Your unexpected behavior is due to the fact that your code has the maximum reliability.

Define the following methods:

private static bool SwitchToggle(bool toggle) => !toggle;

[ReliabilityContract(Consistency.WillNotCorruptState,Cer.Success)]
private static bool SafeSwitchToggle(bool toggle) => !toggle;

And use them instead of the body of your while cycle. You will notice that when calling SwitchToggle the cycle becomes abortable and when calling SafeSwitchToggle it is no more abortable.

The same goes if you add whichever other methods inside the try block that is not having a Consistency.WillNotCorruptState or Consistency.MayCorruptInstance.


问:
Avoid writing of NULL fields present in pyspark dataframe
I have a spark dataframe having the following entries

column1 | column2
   "a"  |   "b"
   "x"  |   "c"
   null |   "a"
   null |   "b"
    "x" |   null

So when I convert it to a glue dynamic frame and write to an S3 bucket in json format the null values are also written.
I don't want to convert the null field to an empty string or number etc. Basically if a field value is null it should not be written. How can I avoid writing the null fields?

答:
You can do something like to .na.fill('') default your values to empty string

```<code>df = spark.createDataFrame([("a",), ("b",), ("c",), (None,)], ['col'])
df.show()
+----+
| col|
+----+
|   a|
|   b|
|   c|
|null|
+----+

df.na.fill('').show()
+---+
|col|
+---+
|  a|
|  b|
|  c|
|   |
+---+
</code>```

Body:
You can do something like to .na.fill('') default your values to empty string

df = spark.createDataFrame([("a",), ("b",), ("c",), (None,)], ['col'])
df.show()
+----+
| col|
+----+
|   a|
|   b|
|   c|
|null|
+----+

df.na.fill('').show()
+---+
|col|
+---+
|  a|
|  b|
|  c|
|   |
+---+


问:
How can I remove underline and purple text color after the link is visited in html
I have a box with an image and some text. I want the whole box to be a link to a new page. When I hover I want the opacity to decrease and the background color to change, as I managed. However, when I go back to the page after visiting the link the text becomes purple and gets an underline.

I tried to use a:visited but it does not work.

I appreciate all the help I can get

.one {
    margin: 10px;
    background-color: rgb(231, 231, 231);
    width: 29%;
    padding: 10px;
    display: inline-flex;
    text-decoration: none;
    color: black;
    }
.one img {
    margin: 0 15px 0 0;
    object-position: 0% -90px;
    width: 230px; /* width of container */
    height: 230px; /* height of container */
    object-fit: cover;
    border-radius: 50%;
    }
.one:visited{
    text-decoration: none;
    color: black;
    }
.one:hover {
    opacity: 90%;
    background-color: rgb(238, 238, 238);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
        <img src="surf.jpg" alt="">
        <div>
            <h1>Surfing</h1>
            <p>Come and surf in the worlds most beautiful places</p>
        </div>
    </code>```

!

答:
did you try this :</p>

```<code>a {color:#FF0000;}         /* Unvisited link  */
a:visited {color:#00FF00;} /* Visited link    */
a:hover {color:#FF00FF;}   /* Mouse over link */
a:active {color:#0000FF;}  /* Selected link   */
</code>```

Body:
I have a box with an image and some text. I want the whole box to be a link to a new page. When I hover I want the opacity to decrease and the background color to change, as I managed. However, when I go back to the page after visiting the link the text becomes purple and gets an underline.

I tried to use a:visited but it does not work.

I appreciate all the help I can get

.one {
    margin: 10px;
    background-color: rgb(231, 231, 231);
    width: 29%;
    padding: 10px;
    display: inline-flex;
    text-decoration: none;
    color: black;
    }
.one img {
    margin: 0 15px 0 0;
    object-position: 0% -90px;
    width: 230px; /* width of container */
    height: 230px; /* height of container */
    object-fit: cover;
    border-radius: 50%;
    }
.one:visited{
    text-decoration: none;
    color: black;
    }
.one:hover {
    opacity: 90%;
    background-color: rgb(238, 238, 238);
    }

Surfing

Come and surf in the worlds most beautiful places

!

Body:
did you try this :

a {color:#FF0000;}         /* Unvisited link  */
a:visited {color:#00FF00;} /* Visited link    */
a:hover {color:#FF00FF;}   /* Mouse over link */
a:active {color:#0000FF;}  /* Selected link   */


问:
Priority Queue using heap, values with same key don't follow FIFO (first in first out)
So I'm trying to create this priority queue to handle my "Order" objects, I'm running into a problem where an object containing the same key/priority will be placed at an early earlier position than others initialized first. I have provided the expected and received output alongside the 83 lines of code of how I constructed my heap with notes</p>

```<code>#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    bool operator <(Order const& RHS) { return priority < RHS.priority; }
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});

    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}
</code>```

```<code>
/*
        Expected Output

    Value           key(priority)
    1                   3
    3                   3
    8                   3
    23                  3
    2                   2
    6                   2
    7                   2
    5                   1
    9                   1

    Recieved/wrong Output

    value            key(priority)
    1                   3
    23                  3
    3                   3
    8                   3
    2                   2
    6                   2
    7                   2
    5                   1

*/
</code>```

答:
Fixed code from answered information above </p>

```<code>#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    int FIFO;
    bool operator <(Order const& RHS) {
        if (priority == RHS.priority)
            return FIFO > RHS.FIFO;
        else
            return priority < RHS.priority;
    } //compares keys for larger presidence
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});
    new_entry.FIFO = size + 1;
    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}

</code>```

Body:
So I'm trying to create this priority queue to handle my "Order" objects, I'm running into a problem where an object containing the same key/priority will be placed at an early earlier position than others initialized first. I have provided the expected and received output alongside the 83 lines of code of how I constructed my heap with notes

#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    bool operator <(Order const& RHS) { return priority < RHS.priority; }
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});

    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}

/*
        Expected Output

    Value           key(priority)
    1                   3
    3                   3
    8                   3
    23                  3
    2                   2
    6                   2
    7                   2
    5                   1
    9                   1

    Recieved/wrong Output

    value            key(priority)
    1                   3
    23                  3
    3                   3
    8                   3
    2                   2
    6                   2
    7                   2
    5                   1

*/

Body:
Fixed code from answered information above

#include <iostream>
#include <vector>

struct Order {
    int value = -1;
    int priority = -1;
    int FIFO;
    bool operator <(Order const& RHS) {
        if (priority == RHS.priority)
            return FIFO > RHS.FIFO;
        else
            return priority < RHS.priority;
    } //compares keys for larger presidence
};

class heap {
private:
    std::vector<Order> orders{ Order{} };
    int size{}; //initalizes it at 0
    int p(int index) { return index >> 1; }
    int l(int index) { return index << 1; }
    int r(int index) { return (index << 1) + 1; }
public:
    bool isEmpty() const { return size == 0; }
    void shiftUp(int position);
    void shiftDown(int position);
    void add(Order new_entry);
    Order removeTop();
    Order& getTop() { return orders[1]; }
};

template <typename T>
void mySwap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    heap h;
    h.add(Order{1,3}); h.add(Order{2,2});
    h.add(Order{3,3}); h.add(Order{5,1});
    h.add(Order{6,2}); h.add(Order{7,2});
    h.add(Order{8,3}); h.add(Order{9,1});
    h.add(Order{23,3});
    std::cout << "value" << "     key(priority)" << "\n";
    for (int i = 0; i < 8; i++) {
        Order temp = h.removeTop();
        std::cout << temp.value << "\t    " << temp.priority << "\n";
    }
}

void heap::shiftUp(int position) {
    if (position > size) return;
    if (position == 1) return;
    if (orders[p(position)] < orders[position]) {
        mySwap(orders[position], orders[p(position)]);
        shiftUp(p(position));
    }
}

void heap::shiftDown(int position) {
    if (position > size) return;
    int greaterPosition = position;
    if (l(position) <= size && orders[position] < orders[l(position)])
        greaterPosition = l(position);
    if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
        greaterPosition = r(position);
    if (greaterPosition != position) {
        mySwap(orders[position], orders[greaterPosition]);
        shiftDown(greaterPosition);
    }
}

void heap::add(Order new_entry) {
    if (size + 1 >= orders.size()) orders.push_back(Order{});
    new_entry.FIFO = size + 1;
    orders[++size] = new_entry;
    shiftUp(size);
}

Order heap::removeTop() {
    Order temp = orders[1];
    mySwap(orders[1],orders[orders.size() - 1]); size--;
    orders.pop_back();
    shiftDown(1);
    return temp;
}


问:
Regex, match one character that is not in a pattern
im parsing a csv file with javascript, that file styles the cells with commas in the numbered values.
when parsing it to javascript i get the entire row as one string where the cells are divided by commas, as such:

```<code>2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020
</code>```

in order to parse the files and create an object from every row i need to match the commas that are Not part of a number, so the end result is:

```<code>2
some text
9740127
₪ 38,850.00
₪ 5,550.00
₪ 28,305
₪ 4,995
22/05/2020
</code>```

i tried matching the commas inside the numbers in hopes to negate it afterwards with that regex:(".\s\d+,\d+[.]?[\d]+")
but i cant seem to target the other commas instead afterwards.

i feel like im close but i cant seem to figure it out, would appreciate the help!
Thanks

答:
You can use Javascript's .split() method for your use-case.

var mystring = '2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020';
var splitStringArray = mystring.split(",");

for(var i = 0; i < splitStringArray.length; i++) {
  console.log(splitStringArray[i]);
}```

Body:
im parsing a csv file with javascript, that file styles the cells with commas in the numbered values.
when parsing it to javascript i get the entire row as one string where the cells are divided by commas, as such:

2, some text,9740127,"₪ 38,850.00","₪ 5,550.00","₪ 28,305","₪ 4,995",22/05/2020

in order to parse the files and create an object from every row i need to match the commas that are Not part of a number, so the end result is:

2
some text
9740127
₪ 38,850.00
₪ 5,550.00
₪ 28,305
₪ 4,995
22/05/2020

i tried matching the commas inside the numbers in hopes to negate it afterwards with that regex:(".\s\d+,\d+[.]?[\d]+")
but i cant seem to target the other commas instead afterwards.

i feel like im close but i cant seem to figure it out, would appreciate the help!
Thanks


问:
switch while won't loop
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).</p>

```<code>static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }
</code>```

答:
This is broken code.
You have a switch() {} statement (without default and those breaks cause you to fall out of its scope) and a while (condition) /*do nothing*/; statement.

The intention is do{switch(){}}while() ?

Time to do some reading...

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/while

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/do

Title: switch while won't loop

Body:
This is part of a program I'm writting. My main porblem is that once it goes trough one of the cases, tit won't loop so it's useless as it is. Any help? (Sorry for the variables in Spanish, also a couple of functions i created appear in the cose which are in the program and work just fine so I don't thin they have anything to do with the problem).

static void Main(string[] args)
    {
        int minutos_restantes = 480;
        int opcion;
        int valorComercial = 0;
        Tarea[] listado_tareas = new Tarea[10];

        CrearTareas(ref listado_tareas);

        Console.WriteLine("1. Mostrar tareas. \n2. Asignar tarea \n3. Salir, \n Elige opción: ");
        opcion = Convert.ToInt32(Console.ReadLine());

        switch (opcion)
        {
            case 1:
                Imprimirtareas(listado_tareas);
                break;

            case 2:
                Console.WriteLine("Seleccionar número de tarea: ");
                int n = Convert.ToInt32(Console.ReadLine())-1;

                if (n < 0 || n > 10)
                {
                    Console.WriteLine("TAREA INEXISTENTE");
                }

                else if (listado_tareas[n].realizada == true)
                {
                    Console.WriteLine("TAREA YA REALIZADA");
                }

                else if((minutos_restantes - listado_tareas[n].tiempo) <= 0)
                {
                    Console.WriteLine("TIEMPO INSUFICIENTE");
                }

                else
                {
                    listado_tareas[n].realizada = true;
                    minutos_restantes -= listado_tareas[n].tiempo;
                }

                break;
        } while (opcion != 3) ;

    }


问:
Why is whoosh commit so slow
I wonder why whoosh is kinda slow with the following code. Especially the commit takes quite a long time.

I tried to use limitmb=2048 with the writer instead of the default 128, but it makes almost no difference. As per suggestions I tried procs=3 for the writer, which makes the indexing a little faster, but the commit even slower. Also commit(merge=False) doesn't help here, since the index is empty.

I get results like this:

```<code>index_documents 12.41 seconds
commit 22.79 seconds
run 35.34 seconds
</code>```

Which for such a small schema and roughly 45000 objects seems a bit much.

I tested with whoosh 2.5.7 and Python 2.7.

Is that normal and I just expect too much, or am I doing something wrong?

I also profiled a little and it seems like whoosh is writing out and then reading in lots of pickles. It seems to be related to how the transactions are handled.

```<code>from contextlib import contextmanager
from whoosh import fields
from whoosh.analysis import NgramWordAnalyzer
from whoosh.index import create_in
import functools
import itertools
import tempfile
import shutil
import time

def timecall(f):
    @functools.wraps(f)
    def wrapper(*args, **kw):
        start = time.time()
        result = f(*args, **kw)
        end = time.time()
        print "%s %.2f seconds" % (f.__name__, end - start)
        return result
    return wrapper

def schema():
    return fields.Schema(
        path=fields.ID(stored=True, unique=True),
        text=fields.TEXT(analyzer=NgramWordAnalyzer(2, 4), stored=False, phrase=False))

@contextmanager
def create_index():
    directory = tempfile.mkdtemp()
    try:
        yield create_in(directory, schema())
    finally:
        shutil.rmtree(directory)

def iter_documents():
    for root in ('egg', 'ham', 'spam'):
        for i in range(1000, 16000):
            yield {
                u"path": u"/%s/%s" % (root, i),
                u"text": u"%s %s" % (root, i)}

@timecall
def index_documents(writer):
    start = time.time()
    counter = itertools.count()
    for doc in iter_documents():
        count = counter.next()
        current = time.time()
        if (current - start) > 1:
            print count
            start = current
        writer.add_document(**doc)

@timecall
def commit(writer):
    writer.commit()

@timecall
def run():
    with create_index() as ix:
        writer = ix.writer()
        index_documents(writer)
        commit(writer)

if __name__ == '__main__':
    run()
</code>```

答:
There is some sort of merging of segments happening in the commit; this also explain why procs=3 makes things even slower (more segments to merge!).

For me the solution was to set the multisegment=True, as suggested here.

```<code>writer = ix.writer(procs=4, limitmb=256, multisegment=True)
</code>```

You can adjust your procs and limitmb as you wish, but consider that limitmb is per procs! (i.e. they get multiplied)

Caveat: there has a penalty regarding the search speed. For example:

10000 documents:
~200ms (w/o multisegment) vs 1.1secs (with multisegment)

50000 documents:
~60ms (w/o multisegment) vs ~100ms (with multisegment)

Very roughly 40% slower on my system on the commit only. I didn't measure indexing times, but multisegment is also way faster.

This might be the solution for prototyping. Once you know you have the desired Schema  and parameters, then you can set the multisegment back to False, and run it again.

so just to give a rough idea of th

Title: Why is whoosh commit so slow

Body:
I wonder why whoosh is kinda slow with the following code. Especially the commit takes quite a long time.

I tried to use limitmb=2048 with the writer instead of the default 128, but it makes almost no difference. As per suggestions I tried procs=3 for the writer, which makes the indexing a little faster, but the commit even slower. Also commit(merge=False) doesn't help here, since the index is empty.

I get results like this:

index_documents 12.41 seconds
commit 22.79 seconds
run 35.34 seconds

Which for such a small schema and roughly 45000 objects seems a bit much.

I tested with whoosh 2.5.7 and Python 2.7.

Is that normal and I just expect too much, or am I doing something wrong?

I also profiled a little and it seems like whoosh is writing out and then reading in lots of pickles. It seems to be related to how the transactions are handled.

from contextlib import contextmanager
from whoosh import fields
from whoosh.analysis import NgramWordAnalyzer
from whoosh.index import create_in
import functools
import itertools
import tempfile
import shutil
import time

def timecall(f):
    @functools.wraps(f)
    def wrapper(*args, **kw):
        start = time.time()
        result = f(*args, **kw)
        end = time.time()
        print "%s %.2f seconds" % (f.__name__, end - start)
        return result
    return wrapper

def schema():
    return fields.Schema(
        path=fields.ID(stored=True, unique=True),
        text=fields.TEXT(analyzer=NgramWordAnalyzer(2, 4), stored=False, phrase=False))

@contextmanager
def create_index():
    directory = tempfile.mkdtemp()
    try:
        yield create_in(directory, schema())
    finally:
        shutil.rmtree(directory)

def iter_documents():
    for root in ('egg', 'ham', 'spam'):
        for i in range(1000, 16000):
            yield {
                u"path": u"/%s/%s" % (root, i),
                u"text": u"%s %s" % (root, i)}

@timecall
def index_documents(writer):
    start = time.time()
    counter = itertools.count()
    for doc in iter_documents():
        count = counter.next()
        current = time.time()
        if (current - start) > 1:
            print count
            start = current
        writer.add_document(**doc)

@timecall
def commit(writer):
    writer.commit()

@timecall
def run():
    with create_index() as ix:
        writer = ix.writer()
        index_documents(writer)
        commit(writer)

if __name__ == '__main__':
    run()

Body:
There is some sort of merging of segments happening in the commit; this also explain why procs=3 makes things even slower (more segments to merge!).

For me the solution was to set the multisegment=True, as suggested here.

writer = ix.writer(procs=4, limitmb=256, multisegment=True)

You can adjust your procs and limitmb as you wish, but consider that limitmb is per procs! (i.e. they get multiplied)

Caveat: there has a penalty regarding the search speed. For example:

10000 documents:
~200ms (w/o multisegment) vs 1.1secs (with multisegment)

50000 documents:
~60ms (w/o multisegment) vs ~100ms (with multisegment)

Very roughly 40% slower on my system on the commit only. I didn't measure indexing times, but multisegment is also way faster.

This might be the solution for prototyping. Once you know you have the desired Schema  and parameters, then you can set the multisegment back to False, and run it again.

so just to give a rough idea of th


问:
How to solve mlogit Error in solve.default(H, g[!fixed]) : system is computationally singular: reciprocal condition number = 3.03549e-18?
I have a wide format data, I'm calling mlogit.data And I tried implementing a mixed logit model using mlogit package, I have one hot encoded the categorical columns (color,size_group ) is that causing the below error?

numerical features in model_data are log1p transformed.

```<code>Complete.choice <- mlogit.data(model_data, choice = "y",
                                 varying = 2:79, shape = "wide", sep = "__", id = "customer_id")
formula <- as.formula("y ~ price + weight + length + height + width + color_white +
                    color_red + color_black + size_group_1 + size_group_3 + size_group_5 +
                     size_group_4 + size_group_2 | -1")

# rpar
 features <- c("price","weight","length","height","width","color_white",
              "color_red","color_black" ,"size_group_1",
              "size_group_3","size_group_5","size_group_4","size_group_2" )
random_parameter <- rep("n", 1:length(features))
names(random_parameter) <- features

sample.mxl <- mlogit(formula, Complete.choice , rpar = random_parameter,
                       R = 40, halton = NA, panel = TRUE, seed = 123, print.level = 0)

Error in solve.default(H, g[!fixed]) :
  system is computationally singular: reciprocal condition number = 3.23485e-18
</code>```

答:
The error means that the Hessian matrix is singular, i.e. the determinant is zero, and the inverse doesn't exist. Effectively, you cannot obtain the variance-covariance matrix.

There are several reasons why this might happen:

You don't have enough variation in your data to identify the model. You are trying to estimate one that is very complex and it would require a lot from your data (variation and observations).

The model is over-specified (have you made the correct normalizations?)

You are estimating 13 random parameters, which asks a lot from your data. I would start with a single random parameter and gradually increase to see when your model fails. Also with more than 4-5 random parameters, you shouldn't be using Halton draws, but would need some type of scrambling procedure. I would recommend scrambled Sobol draws, MLHS draws or scrambled Halton draws.

You are only using R=40. This is a very low number. It will give a poor approximation to the multidimensional integral that is the mixed logit probability. The number of draws needed is increasing in complexity of the model, available alternatives etc. Many people think 500-1000 is good, whereas others tend to use 5000 or higher. Me, I start at a 1000 and gradually increase to where my parameters stabilize. Too few draws could also cause the error you are seeing.

It is impossible to diagnose the reason without testing on the actual data, but these are at least some pointers to get you started.

Body:
I have a wide format data, I'm calling mlogit.data And I tried implementing a mixed logit model using mlogit package, I have one hot encoded the categorical columns (color,size_group ) is that causing the below error?

numerical features in model_data are log1p transformed.

Complete.choice <- mlogit.data(model_data, choice = "y",
                                 varying = 2:79, shape = "wide", sep = "__", id = "customer_id")
formula <- as.formula("y ~ price + weight + length + height + width + color_white +
                    color_red + color_black + size_group_1 + size_group_3 + size_group_5 +
                     size_group_4 + size_group_2 | -1")

# rpar
 features <- c("price","weight","length","height","width","color_white",
              "color_red","color_black" ,"size_group_1",
              "size_group_3","size_group_5","size_group_4","size_group_2" )
random_parameter <- rep("n", 1:length(features))
names(random_parameter) <- features

sample.mxl <- mlogit(formula, Complete.choice , rpar = random_parameter,
                       R = 40, halton = NA, panel = TRUE, seed = 123, print.level = 0)

Error in solve.default(H, g[!fixed]) :
  system is computationally singular: reciprocal condition number = 3.23485e-18


答:
Ah well... seems I simply forgot the return argument in the function.
It might be useful for others so I keep it here.

```<code>col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
  return(df)
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel)
</code>```

Rubber duck debugging at its best.

Title: Turn a col into rownames in a list of dataframes

Body:
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs

Thanks!

Sebastian

Body:
Ah well... seems I simply forgot the return argument in the function.
It might be useful for others so I keep it here.

col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
  return(df)
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel)

Rubber duck debugging at its best.


问:
Trigger cloud firestore
I need help in Cloud Functions.
I previously deployed micro-services written with Python and so, got URL address to execute the script.
Now, I would like to execute this URL when a document is written in my Cloud Firestore. If I understood, I need Cloud Functions to do it but someone can help me ?

For example, every time I add a document in "temp" collection, I would like to execute my URL.

Thanks

答:
You should call your URL from the Cloud Function, for example with the Axios library.

You will find a lot of examples on SO: https://stackoverflow.com/search?q=axios+cloud+function

If you encounter any problem, update your question with all the details.

Important (if you are using Cloud Functions for Firebase):

You need to be on the "Blaze" pricing plan.

As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)

Title: Trigger cloud firestore


问:
I have a function in excel VBA which takes input from user using textbox
I have written a macro that takes input from user and returns a cell data.
Is there any way that triggers the process to run from macro
That is the the inputbox opens up directly with one click without having to go to VBA and run it?</p>

答:
Put this in Worksheet code:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call showMsg
End Sub
</code>```

Put this in your module:

```<code>Sub showMsg()
Dim data As String
data = InputBox("Hello", "Title")
End Sub
</code>```

You can use other worksheet or workbooks events as well e.g
(It will run macro whenever you open file)

```<code>  Private Sub Workbook_Open()
    Call showMsg
  End Sub
</code>```

Body:
Put this in Worksheet code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call showMsg
End Sub

Put this in your module:

Sub showMsg()
Dim data As String
data = InputBox("Hello", "Title")
End Sub

You can use other worksheet or workbooks events as well e.g
(It will run macro whenever you open file)

  Private Sub Workbook_Open()
    Call showMsg
  End Sub


问:
Can I append a img to a img
So I tried out if I can append using jquery a image to an image and it works, but the image seems to be gone or visibility is hidden and display none or so it seems.

So my question is can this be done and can I use this image. Its for a project I am working on.

```<code><img src="img/map.png" style="width: 600px; height: 400px; z-index: -100;">

    <img src="img/dot.png" style="position: relative; width: 20px;
         height:34px; top: 200px; left: 200px; z-index: 100;
        display: block; visibility: visible;">

</img>
</code>```

thats what my code looks like after I use the append. and if you look at it in firebug you see that the child img looks like it is not displayed so I tried changing the visibility but still not luck.

so my question is can this be done or am I after the unattainable.

答: Don't use append, use after so that the second image goes after the first, not inside it.</p>

Title: Can I append a img to a img

Body:
So I tried out if I can append using jquery a image to an image and it works, but the image seems to be gone or visibility is hidden and display none or so it seems.

So my question is can this be done and can I use this image. Its for a project I am working on.

thats what my code looks like after I use the append. and if you look at it in firebug you see that the child img looks like it is not displayed so I tried changing the visibility but still not luck.

so my question is can this be done or am I after the unattainable.


问:
Display Back Arrow on Toolbar
I'm migrating from ActionBar to Toolbar in my application.
But I don't know how to display and set click event on Back Arrow on Toolbar like I did on Actionbar.

With ActionBar, I call mActionbar.setDisplayHomeAsUpEnabled(true).
But there is no the similar method like this.

Has anyone ever faced this situation and somehow found a way to solve it?

答:
If your are using the androidx.appcompat.app.AppCompatActivity just use:

```<code>Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Then just define in the Manifest.xml the parent Activity.

```<code><activity
    android:name=".MyActivity"
    ...>
  <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".ParentActivity" />
</activity>
</code>```

Instead if you are using a Toolbar and you want a custom behavior just use:

```<code><androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    app:navigationIcon="?attr/homeAsUpIndicator"
    .../>
</code>```

and in your Activity:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //....
    }
});
</code>```

Title: Display Back Arrow on Toolbar

Body:
If your are using the androidx.appcompat.app.AppCompatActivity just use:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Then just define in the Manifest.xml the parent Activity.

<activity
    android:name=".MyActivity"
    ...>
  <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".ParentActivity" />
</activity>

Instead if you are using a Toolbar and you want a custom behavior just use:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    app:navigationIcon="?attr/homeAsUpIndicator"
    .../>

and in your Activity:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //....
    }
});


问:
Turn a col into rownames in a list of dataframes
I have a list of dataframes for which I would like to turn one of their cols into the rownames.
(instead of doing this for every df individually).

Unfortunatly I cant get it to work, maybe someone can help?

```<code>DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs
</code>```

Thanks!

Sebastian

答:
You can also do:</p>

```<code>map(.x = TheList,
    ~ .x %>%
    column_to_rownames("A"))

$DF1
  B
A 1
B 2
C 3

$DF2
  B
A 1
B 2
C 3
</code>```

Body:
You can also do:

map(.x = TheList,
    ~ .x %>%
    column_to_rownames("A"))

$DF1
  B
A 1
B 2
C 3

$DF2
  B
A 1
B 2
C 3


问:
Opening of first option navigation bar as soon as application starts java
I am making an android project and i am a using bottom navigation bar with activities.While I click on the navigation bar buttons it works perfectly fine but when i start the application it shows me just a navigation bar .I want the first navigation bar option should show up as soon as I start the application but it is not happening .Please help me with this.</p>

答:
If you are using fragments to instantiate in the bottom navigation bar, you just need to instantiate the fragment in the onCreate Method and use the bottom navigation bar listener to use it to handle click listeners.

In this demo, I have a navigation bar which is being initialized using the listeners and after that, in the onCreate I instantiate the fragment to display when the fragment when created.

```<code>public class MainActivity extends AppCompatActivity {
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
    bottomNav.setOnNavigationItemSelectedListener(navListener);
    viewPager = findViewById(R.id.view_pager);

    PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(pagerAdapter);
    private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {@Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;

            switch (item.getItemId()) {
            case R.id.home_nav:
                selectedFragment = new HomeFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();

                break;
            case R.id.explore_nav:
                selectedFragment = new ExploreFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
                break;
            }
            return true;
        }
    };

    selectedFragment = new HomeFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
</code>```

Body:
If you are using fragments to instantiate in the bottom navigation bar, you just need to instantiate the fragment in the onCreate Method and use the bottom navigation bar listener to use it to handle click listeners.

In this demo, I have a navigation bar which is being initialized using the listeners and after that, in the onCreate I instantiate the fragment to display when the fragment when created.

public class MainActivity extends AppCompatActivity {
ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
    bottomNav.setOnNavigationItemSelectedListener(navListener);
    viewPager = findViewById(R.id.view_pager);

    PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(pagerAdapter);
    private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {@Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;

            switch (item.getItemId()) {
            case R.id.home_nav:
                selectedFragment = new HomeFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();

                break;
            case R.id.explore_nav:
                selectedFragment = new ExploreFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
                break;
            }
            return true;
        }
    };

    selectedFragment = new HomeFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();


问:
Rails 6: How to add jquery-ui through webpacker?
I'm currently trying to implement a datepicker into my application, the problem is that there is no documentation on how to add the jquery-ui-rails gem through webpacker.

Probably there is another way to add gems or another gem that would fit my needs?

答:
```<code>$ yarn add webpack-jquery-ui
</code>```

and in application.js

```<code>require('webpack-jquery-ui');
require('webpack-jquery-ui/css');
</code>```

did the job for me.
(I had setup jquery before which might need some additional config)

Weblink: https://www.npmjs.com/package/webpack-jquery-ui

(This is the same process as in Tushar Patil's answer yet with another package).

Body:
$ yarn add webpack-jquery-ui

and in application.js

require('webpack-jquery-ui');
require('webpack-jquery-ui/css');

did the job for me.
(I had setup jquery before which might need some additional config)

Weblink: https://www.npmjs.com/package/webpack-jquery-ui

(This is the same process as in Tushar Patil's answer yet with another package).


问:
List of some number ([1,1,1,1,1,1]) in haskell
Is it possible in Haskell to create list of some element by provided length?
In Python, I can write:

```<code>l = [1] * 10
</code>```

How can I do it in Haskell?

答:
Thanks to Krzysztof Atłasik</p>

```<code>replicate 10 1
</code>```

Body:
Is it possible in Haskell to create list of some element by provided length?
In Python, I can write:

l = [1] * 10

How can I do it in Haskell?

Body:
Thanks to Krzysztof Atłasik

replicate 10 1