问:
Show full line of a CSV file C++
I am making a program that reads a .CSV file and loads it into binary search trees to sort its content, since I managed to load the .CSV and implement the tree however the content of the file is:

1, Peter, 230151515

5, Merrick, 25551561

7, Lucky, 4301616199

2, luis, 2589191919

16, Alfredo, 25891919

8, Linda, 129616919

I am using the first data of each row as a key and with the code that I carry, it orders it correctly, however I want it to show the rest of the row, not just the key, someone could tell me how I could do that, to show all the data of each key ordered.

output:

1

2

5

7

8

16

What I want to print would be something like:

1 Peter 230151515

2 Luis 2589191919

5 Merrick 25551561

7 Lucky 4301616199

8 Linda 129616919

16 Alfredo 25891919

Someone to help me correct my mistake please.

```<code>#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node {
    int key;
    string name;
    int num;
    struct node *left, *right;
};

vector<node> persons;

struct node *newNode(int item)
{
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

void inorder(struct node *root)
{
    if (root != NULL)
    {
        //cout<<"\t";

        inorder(root->left);
        printf("\t%d\n", root->key);
        inorder(root->right);
    }
}

struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);

    /* return the (unchanged) node pointer */
    return node;
}

struct node * minValueNode(struct node* node)
{
    struct node* current = node;

    /* loop down to find the leftmost leaf */
    while (current && current->left != NULL)
        current = current->left;

    return current;
}

int main()
{
    struct node *root = NULL;
    ifstream fin("data.txt");
    if (!fin)
    {
        cout << "File not open\n";
        return 1;
    }

    string line;
    const char delim = ',';

    while (getline(fin, line))
    {
        istringstream ss(line);
        node person;
        ss >> person.key; ss.ignore(10, delim);
        getline(ss, person.name,delim);
        ss >> person.num;
        if (ss)
            persons.push_back(person);
    }

   for (unsigned int i=0; i< persons.size(); i++)
   {
         cout << setw(5)  << persons[i].key<< setw(20) << persons[i].name<< setw(15)  << persons[i].num << '\n';

             root = insert(root, persons[i].key);
            insert(root, persons[i].key);

   }

    cout << "\n\nInorder:\n";
//    cout<<node.name;

    inorder(root);

    /*/cout<<"\nDelete 50\n";
    root = deleteNode(root, 50);
    cout<<"Inorder traversal of the modified tree \n";
    inorder(root);/*/

    /*
    insert(root, 80);*/

    return 0;
}
</code>```

答:
When you are printing out the key, you can also print out the other information of each node. Here's a solution using cout:

```<code>void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        std::cout << root->key << " " << root->name << " " << root->num << "\n";
        inorder(root->right);
    }
}
</code>```

Title: Show full line of a CSV file C++

Body:
I am making a program that reads a .CSV file and loads it into binary search trees to sort its content, since I managed to load the .CSV and implement the tree however the content of the file is:

1, Peter, 230151515

5, Merrick, 25551561

7, Lucky, 4301616199

2, luis, 2589191919

16, Alfredo, 25891919

8, Linda, 129616919

I am using the first data of each row as a key and with the code that I carry, it orders it correctly, however I want it to show the rest of the row, not just the key, someone could tell me how I could do that, to show all the data of each key ordered.

output:

1

2

5

7

8

16

What I want to print would be something like:

1 Peter 230151515

2 Luis 2589191919

5 Merrick 25551561

7 Lucky 4301616199

8 Linda 129616919

16 Alfredo 25891919

Someone to help me correct my mistake please.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

struct node {
    int key;
    string name;
    int num;
    struct node *left, *right;
};

vector<node> persons;

struct node *newNode(int item)
{
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}

void inorder(struct node *root)
{
    if (root != NULL)
    {
        //cout<<"\t";

        inorder(root->left);
        printf("\t%d\n", root->key);
        inorder(root->right);
    }
}

struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);

    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);

    /* return the (unchanged) node pointer */
    return node;
}

struct node * minValueNode(struct node* node)
{
    struct node* current = node;

    /* loop down to find the leftmost leaf */
    while (current && current->left != NULL)
        current = current->left;

    return current;
}

int main()
{
    struct node *root = NULL;
    ifstream fin("data.txt");
    if (!fin)
    {
        cout << "File not open\n";
        return 1;
    }

    string line;
    const char delim = ',';

    while (getline(fin, line))
    {
        istringstream ss(line);
        node person;
        ss >> person.key; ss.ignore(10, delim);
        getline(ss, person.name,delim);
        ss >> person.num;
        if (ss)
            persons.push_back(person);
    }

   for (unsigned int i=0; i< persons.size(); i++)
   {
         cout << setw(5)  << persons[i].key<< setw(20) << persons[i].name<< setw(15)  << persons[i].num << '\n';

             root = insert(root, persons[i].key);
            insert(root, persons[i].key);

   }

    cout << "\n\nInorder:\n";
//    cout<<node.name;

    inorder(root);

    /*/cout<<"\nDelete 50\n";
    root = deleteNode(root, 50);
    cout<<"Inorder traversal of the modified tree \n";
    inorder(root);/*/

    /*
    insert(root, 80);*/

    return 0;
}

Body:
When you are printing out the key, you can also print out the other information of each node. Here's a solution using cout:

void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        std::cout << root->key << " " << root->name << " " << root->num << "\n";
        inorder(root->right);
    }
}


来源: stackexchange

问:
pubDate to unixtime in javascript
Does anyone have a function which can covert an RSS feeds pubDate to a unix timestamp? I tired using a javascript version of strtotime() but it never worked correctly.</p>

答:
Can be done easier using Date.parse:</p>

```<code>var pubDate = "Sun, 27 Mar 2011 20:17:21 +0100";
alert(Math.round(Date.parse(pubDate)/1000));
</code>```

ContentLicense: CC BY-SA 3.0

Title: pubDate to unixtime in javascript

Body:
Can be done easier using Date.parse:

var pubDate = "Sun, 27 Mar 2011 20:17:21 +0100";
alert(Math.round(Date.parse(pubDate)/1000));


问:
Can I customize individuals items in a ggplot legend?
Is it possible to make guides with different fonts, regarding a factor? I'm trying to plot my multivariate data and, in addition to the colour code, I'd like to make some of the guides bold.
Here's a reproducible example

```<code>  library("ggpubr")
  library("reshape2")

iris.melt <- melt(iris)

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = "italic")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom"))
</code>```

Which produces

I tried highlighting only one species

```<code>ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = c("plain","italic","plain")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom"))
</code>```

but "Vectorized input to element_text() is not officially supported."

Is there a way to customize individuals items in the legend?

答:
I don't think there's a way to set the theme components separately, but there is a workaround, which is to use expressions for labels. That way you can make any single label bold:

library("ggpubr")
library("reshape2")

iris.melt <- melt(iris)

one_bold_label <- expression("Setosa", bold(paste("Versicolor")), "Virginica")

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
  theme(legend.text = element_text(face = "italic")) +
  scale_colour_manual(labels = one_bold_label, values = c("#F8766D", "#00BA38", "#619CFF")) +
  scale_fill_manual(labels = one_bold_label, values = c("white", "white", "white"))
```

Created on 2020-05-31 by the reprex package (v0.3.0)

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to make guides with different fonts, regarding a factor? I'm trying to plot my multivariate data and, in addition to the colour code, I'd like to make some of the guides bold.
Here's a reproducible example

  library("ggpubr")
  library("reshape2")

iris.melt <- melt(iris)

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = "italic")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom"))

Which produces

I tried highlighting only one species

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
theme(legend.text = element_text(face = c("plain","italic","plain")) +
guides(col = guide_legend(override.aes = list(size=2), label.position = "bottom"))

but "Vectorized input to element_text() is not officially supported."

Is there a way to customize individuals items in the legend?

Body:
I don't think there's a way to set the theme components separately, but there is a workaround, which is to use expressions for labels. That way you can make any single label bold:

library("ggpubr")
library("reshape2")

iris.melt <- melt(iris)

one_bold_label <- expression("Setosa", bold(paste("Versicolor")), "Virginica")

ggboxplot(data = iris.melt, x = "variable", y= "value", add = "jitter",
          add.params = list(color = "Species"), legend = "bottom") +
  theme(legend.text = element_text(face = "italic")) +
  scale_colour_manual(labels = one_bold_label, values = c("#F8766D", "#00BA38", "#619CFF")) +
  scale_fill_manual(labels = one_bold_label, values = c("white", "white", "white"))

Created on 2020-05-31 by the reprex package (v0.3.0)


问:
Find the lists that share common values
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

```<code>a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
</code>```

The expected output is:

```<code>[a, c]
</code>```

Ideally, I also want the fastest method. Thanks in advance,

答:
Using my limited knowledge on Python lists, I came up with this:

```<code>class countedList:
    def __init__(self,listt):
        self.listt = listt
        self.sharedNum = 0

def mostCommon(*lists):
    for item in lists:
        for listItem in item.listt:
            for item2 in lists:
                item2.sharedNum+=item2.listt.count(listItem)

    new = sorted(lists,key=lambda clist: clist.sharedNum,reverse=True)
    return new[:2]

test = mostCommon(countedList([1, 2, 3, 4]),countedList([5, 6, 7, 8]),countedList([9, 10, 11, 1]))
</code>```

Well yeah, I had to make up a custom class for it. In the test run it gave:

```<code>>>> test[0].listt
[1, 2, 3, 4]
>>> test[1].listt
[9, 10, 11, 1]
</code>```

Title: Find the lists that share common values

Body:
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]

The expected output is:

[a, c]

Ideally, I also want the fastest method. Thanks in advance,

Body:
Using my limited knowledge on Python lists, I came up with this:

class countedList:
    def __init__(self,listt):
        self.listt = listt
        self.sharedNum = 0

def mostCommon(*lists):
    for item in lists:
        for listItem in item.listt:
            for item2 in lists:
                item2.sharedNum+=item2.listt.count(listItem)

    new = sorted(lists,key=lambda clist: clist.sharedNum,reverse=True)
    return new[:2]

test = mostCommon(countedList([1, 2, 3, 4]),countedList([5, 6, 7, 8]),countedList([9, 10, 11, 1]))

Well yeah, I had to make up a custom class for it. In the test run it gave:

>>> test[0].listt
[1, 2, 3, 4]
>>> test[1].listt
[9, 10, 11, 1]


问:
Check if an array element is a sum of two earlier elements using recursion
I was solving practice questions from a book when I stumbled upon this one :

*Describe a recursive algorithm that will check if an array A of
integers contains an integer A[i] that is the sum of two integers
that appear earlier in A, that is, such that

```<code> A[i] = A[j] +A[k] for j,k < i.
</code>```

*

I have been thinking about this for a few hours but haven't been able to come up with a good recursive algorithm.

答:
<pre class="lang-java prettyprint-override"><code>  /**
   * Describe a recursive algorithm that will check if an array A of integers contains
   * an integer A[i] that is the sum of two integers that appear earlier in A,
   * that is, such that A[i] = A[j]+A[k] for j,k < i.
   * @param A - array
   * @param i - initial starting index (0)
   * @param j - initival value for j (0)
   * @param k - initial value for k (0)
   * @param n - length of A - 1
   * @return - true if combination of previous 2 elements , false otherwise
   */
  public boolean checkIfPreviousTwo(int[] A, int i, int j, int k, int n){
    if(i >= n) return false;
    if(j < i && k < i){
      if(A[j] + A[k] == A[i]) return true;
      return(
        checkIfPreviousTwo(A, i, j + 1, k, n) ||
        checkIfPreviousTwo(A, i, j, k + 1, n)
      );
    }
    return checkIfPreviousTwo(A, i + 1, j, k, n);
  }
</code>```

Body:
I was solving practice questions from a book when I stumbled upon this one :

*Describe a recursive algorithm that will check if an array A of
integers contains an integer A[i] that is the sum of two integers
that appear earlier in A, that is, such that

 A[i] = A[j] +A[k] for j,k < i.

*

I have been thinking about this for a few hours but haven't been able to come up with a good recursive algorithm.


问:
Convert from timestamp (Epoch time) to Proper Pandas DateTime colimn
Trying to convert a column from timestamps to datetime, desired result printed last.
The source is a Unix epoch timestamp. I can convert a single value, but am not able to do it on a full column of data.
Thank you!!</p>

```<code>import pandas as pd
import numpy as np
from datetime import datetime
thd = pd.DataFrame(data=data["candles"])
data={'candles': [{'open': 1417.5,
   'high': 1417.52,
   'low': 1416.95,
   'close': 1416.95,
   'volume': 508,
   'datetime': 1590758940},
  {'open': 1416.95,
   'high': 1420.18,
   'low': 1415.06,
   'close': 1416.64,
   'volume': 32934,
   'datetime': 1590759000},]
}

thd["Time"]=pd.to_datetime(thd["datetime"])
display(thd)
datetime.fromtimestamp(1590759060) #<---this is the result I want to get on dataframe
</code>```

Body:
Trying to convert a column from timestamps to datetime, desired result printed last.
The source is a Unix epoch timestamp. I can convert a single value, but am not able to do it on a full column of data.
Thank you!!

import pandas as pd
import numpy as np
from datetime import datetime
thd = pd.DataFrame(data=data["candles"])
data={'candles': [{'open': 1417.5,
   'high': 1417.52,
   'low': 1416.95,
   'close': 1416.95,
   'volume': 508,
   'datetime': 1590758940},
  {'open': 1416.95,
   'high': 1420.18,
   'low': 1415.06,
   'close': 1416.64,
   'volume': 32934,
   'datetime': 1590759000},]
}

thd["Time"]=pd.to_datetime(thd["datetime"])
display(thd)
datetime.fromtimestamp(1590759060) #<---this is the result I want to get on dataframe

Body:
Use pd.to_datetime with unit='s':

In [731]: thd['datetime'] = pd.to_datetime(thd['datetime'], unit='s')

In [732]: thd
Out[732]:
      open     high      low    close  volume            datetime
0 1,417.50 1,417.52 1,416.95 1,416.95     508 2020-05-29 13:29:00
1 1,416.95 1,420.18 1,415.06 1,416.64   32934 2020-05-29 13:30:00


问:
Python Tensorflow - Running model.fit multiple times without reinstantiating the model

Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

```<code>model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)
</code>```

Is this equivalent to running:

```<code>model.fit(train_images, train_labels, epochs=18)
</code>```

Or:

```<code>model.fit(train_images, train_labels, epochs=8)
</code>```

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?

答:
To avoid overfitting, you can add Dropout layers, it will dropout % of connections, you just need to add it to your model between Dense layers.

from keras.layers import Dropout
Dropout(0.2)  # droping 20% only in training
```

Body:
Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)

Is this equivalent to running:

model.fit(train_images, train_labels, epochs=18)

Or:

model.fit(train_images, train_labels, epochs=8)

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?


问:
Adding environment variables to Spring's application.properties
I want to run two Amazon S3's SDK information from the application.properties, but instead of putting it in the file, I want to add them when running ./mvnw spring-boot:run. I saw something like this could be done:

```<code>./mvnw spring-boot:run -Dspring-boot.run.arguments="--srp.storage.s3.access-key=FOOBARFOOBAR,--srp.storage.s3.secret-key=foobarfoobarfoobarfoobarfoobar"
</code>```

I tried running the command above with quotes around the arguments and with/without whitespace between them. Also, I tried leaving blank values in the properties files as well as removing them at all.

```<code># srp.storage.s3.access-key=
# srp.storage.s3.secret-key=
</code>```

```<code>srp.storage.s3.access-key=
srp.storage.s3.secret-key=
</code>```

I have a class annotated with @ConfigurationProperties("srp.storage"). The results of these attempts varied from application failing to start because no property was found by the class, to actually running but taking no effect. The variations of the command that caused the server not to start was not specifying any property in application.properties and attempting to run the command with and without quotes and no whitespace. The scenario that it ran but did not take effect was putting whitespace.

I know about running it using the built JAR file, but I want to be able, if possible, to run it like that just to prevent building every time I change something.

Also attempted to specify placeholder as shown here, but again no success. Can I even do what I want using ./mvnw? Or must it be with a JAR file?

```<code>srp.storage.s3.access-key=${access-key}
srp.storage.s3.secret-key=${secret-key}
</code>```

```<code>./mvnw spring-boot:run -Dspring-boot.run.arguments="--access-key=FOOBARFOOBAR,--secret-key=foobarfoobarfoobarfoobarfoobar"
</code>```

答:
If you are using gradle and have bootRun task available then you can configure the task to read the args passed while running the task.

Add the following to your build file.

```<code>bootRun {
    if (project.hasProperty('params')) {
        args project.params.split(",")
    }
}
</code>```

Then you can run the following command.

```<code>.\gradlew.bat bootRun -Pparams=--demo.prop=commandlinearg
</code>```

I had a field annotated as the following

```<code>@Value("${demo.prop}")
private String prop;
</code>```

Body:
I want to run two Amazon S3's SDK information from the application.properties, but instead of putting it in the file, I want to add them when running ./mvnw spring-boot:run. I saw something like this could be done:

./mvnw spring-boot:run -Dspring-boot.run.arguments="--srp.storage.s3.access-key=FOOBARFOOBAR,--srp.storage.s3.secret-key=foobarfoobarfoobarfoobarfoobar"

I tried running the command above with quotes around the arguments and with/without whitespace between them. Also, I tried leaving blank values in the properties files as well as removing them at all.

# srp.storage.s3.access-key=
# srp.storage.s3.secret-key=

srp.storage.s3.access-key=
srp.storage.s3.secret-key=

I have a class annotated with @ConfigurationProperties("srp.storage"). The results of these attempts varied from application failing to start because no property was found by the class, to actually running but taking no effect. The variations of the command that caused the server not to start was not specifying any property in application.properties and attempting to run the command with and without quotes and no whitespace. The scenario that it ran but did not take effect was putting whitespace.

I know about running it using the built JAR file, but I want to be able, if possible, to run it like that just to prevent building every time I change something.

Also attempted to specify placeholder as shown here, but again no success. Can I even do what I want using ./mvnw? Or must it be with a JAR file?

srp.storage.s3.access-key=${access-key}
srp.storage.s3.secret-key=${secret-key}

./mvnw spring-boot:run -Dspring-boot.run.arguments="--access-key=FOOBARFOOBAR,--secret-key=foobarfoobarfoobarfoobarfoobar"

Body:
If you are using gradle and have bootRun task available then you can configure the task to read the args passed while running the task.

Add the following to your build file.

bootRun {
    if (project.hasProperty('params')) {
        args project.params.split(",")
    }
}

Then you can run the following command.

.\gradlew.bat bootRun -Pparams=--demo.prop=commandlinearg

I had a field annotated as the following

@Value("${demo.prop}")
private String prop;


问:
Are variables declared with let or const hoisted?
I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...

```<code>console.log(typeof name); // undefined
var name = "John";
</code>```

...variables declared with let or const seem to have some problems with hoisting:

```<code>console.log(typeof name); // ReferenceError
let name = "John";
</code>```

and

```<code>console.log(typeof name); // ReferenceError
const name = "John";
</code>```

Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?

答:
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -

```<code>// this will work
u = 10;
var u;

// this will give an error
k = 10;
let k;  // ReferenceError: Cannot access 'k' before initialization.
</code>```

eg. 2-

```<code>// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
</code>```

Body:
I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...

console.log(typeof name); // undefined
var name = "John";

...variables declared with let or const seem to have some problems with hoisting:

console.log(typeof name); // ReferenceError
let name = "John";

and

console.log(typeof name); // ReferenceError
const name = "John";

Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?

Body:
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -

// this will work
u = 10;
var u;

// this will give an error
k = 10;
let k;  // ReferenceError: Cannot access 'k' before initialization.

eg. 2-

// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9


问:
CSS or SASS How to change style of ::after, ::before effects of parent element when child element is active
html

```<code>   <div class="styled-select-box">
     <select class="styled-select">
       <option value="20">20</option>
       <option value="30">30</option>
     </select>
    </div>
</code>```

css, I should change the style of .styled-select-box::after when .styled-select is :active or :focus

```<code>.styled-select-box::after {
  cursor: pointer;
  display: block;
  content: ' ';
  background-image: url(/custom-icons/arrow-down.svg);
  background-size: 12px 12px;
  height: 25px;
  width: 16px;
  opacity: 0.5;
  background-position-y: 6px;
  background-repeat: no-repeat;
}
.styled-select:active *parentElement* {
  transform: rotateX(180deg);
  transition: all 0.5s ease;
}
</code>```

I tried with :has() but it not supported by browsers

答: As far as I know, this is not possible with CSS alone.</p>

Body:
html

     <select class="styled-select">
       <option value="20">20</option>
       <option value="30">30</option>
     </select>

css, I should change the style of .styled-select-box::after when .styled-select is :active or :focus

.styled-select-box::after {
  cursor: pointer;
  display: block;
  content: ' ';
  background-image: url(/custom-icons/arrow-down.svg);
  background-size: 12px 12px;
  height: 25px;
  width: 16px;
  opacity: 0.5;
  background-position-y: 6px;
  background-repeat: no-repeat;
}
.styled-select:active *parentElement* {
  transform: rotateX(180deg);
  transition: all 0.5s ease;
}

I tried with :has() but it not supported by browsers


问:
Angular 9 - js scripts not working (e.g. foundations or bootstrap)
First steps in Angular (doing an online course) and I keep thinking that my JS is not working. Because when I ng serve the below project is see the foundation styling (css), but the hamburger Icon is not opening/closing when I click it. The code is a sample from the foundation website.

app.component.html looks like this

```<code><h1>This is the app</h1>

<div class="title-bar" data-responsive-toggle="main-nav" data-hide-for="medium">
  <button class="menu-icon" type="button" data-toggle="main-nav"></button>
  <div class="title-bar-title">Menu</div>
</div>

<div class="top-bar" id="main-nav">
  <div class="top-bar-left">
    <ul class="dropdown vertical medium-horizontal menu" data-dropdown-menu>
      <li class="menu-text">Site title</li>
      <li><a href="#">One</a></li>
      <li><a href="#">Two</a></li>
      <li><a href="#">Two</a></li>
    </ul>
  </div>
</div>
</code>```

Through numerous topics in ended up with the following:

In styles.css I added

```<code>@import "../node_modules/foundation-sites/dist/css/foundation.min.css";
</code>```

In angular.json I added

```<code> "styles": [
              "src/styles.css",
              "node_modules/foundation-sites/dist/css/foundation.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/foundation-sites/dist/js/foundation.min.js"
            ]
</code>```

My own thoughts on it:

Hamburger Icon and styling is there but its not opening/closing

My angular.json file is not named angular-cli.json (like in other examples...WHY!?)

I did not needed to ../ the scripts, they only compile like above (else error)

working on Unix (ubuntu)

Jquery version 3.5.1 and foundation-sites 6.6.3

答:
It's probably possible to get this to work, but plain-old Bootstrap uses jQuery to manipulate the DOM (e.g. open/close your toolbar when you click the hamburger menu icon).

jQuery really should not be used with Angular, because it could interfere with Angular's maintenance of the DOM. (jQuery would change the DOM, and Angular wouldn't know about it).

For this reason, there are a couple of other projects, including ngx-bootstrap, that either use Bootstrap's css but implement the js functionality in terms of Angular directives, or which look and operate like Bootstrap and re-implement (at least partially) the css and the js.

Body:
First steps in Angular (doing an online course) and I keep thinking that my JS is not working. Because when I ng serve the below project is see the foundation styling (css), but the hamburger Icon is not opening/closing when I click it. The code is a sample from the foundation website.

app.component.html looks like this

This is the app

  <button class="menu-icon" type="button" data-toggle="main-nav"></button>

Menu

Site title

One

Two

Two

Through numerous topics in ended up with the following:

In styles.css I added

@import "../node_modules/foundation-sites/dist/css/foundation.min.css";

In angular.json I added

 "styles": [
              "src/styles.css",
              "node_modules/foundation-sites/dist/css/foundation.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/foundation-sites/dist/js/foundation.min.js"
            ]

My own thoughts on it:

Hamburger Icon and styling is there but its not opening/closing

My angular.json file is not named angular-cli.json (like in other examples...WHY!?)

I did not needed to ../ the scripts, they only compile like above (else error)

working on Unix (ubuntu)

Jquery version 3.5.1 and foundation-sites 6.6.3


问:
Check which columns in DataFrame are Categorical
I am new to Pandas... I want to a simple and generic way to find which columns are categorical in my DataFrame, when I don't manually specify each column type, unlike in this SO question. The df is created with:

```<code>import pandas as pd
df = pd.read_csv("test.csv", header=None)
</code>```

e.g.

```<code>           0         1         2         3        4
0   1.539240  0.423437 -0.687014   Chicago   Safari
1   0.815336  0.913623  1.800160    Boston   Safari
2   0.821214 -0.824839  0.483724  New York   Safari
</code>```

.

UPDATE (2018/02/04) The question assumes numerical columns are NOT categorical, @Zero's accepted answer solves this.

BE CAREFUL - As @Sagarkar's comment points out that's not always true. The difficulty is that Data Types and Categorical/Ordinal/Nominal types are orthogonal concepts, thus mapping between them isn't straightforward. @Jeff's answer below specifies the precise manner to achieve the manual mapping.

答:
```<code>`categorical_values  = (df.dtypes == 'object')
categorical_variables = categorical_variables =[categorical_values.index[ind]
for ind, val in enumerate(categorical_values) if val == True]
</code>```

In the first line of code, we obtain a series which gives information regarding all the columns. The series gives information on which column is an object type and which column is not of the object type by representing it with a Boolean value.

In the second line, we use a list comprehension using enumeration(iterating through index and value), so that we could easily find the column which is of categorical type and append it to the categorical_variables list

Body:
I am new to Pandas... I want to a simple and generic way to find which columns are categorical in my DataFrame, when I don't manually specify each column type, unlike in this SO question. The df is created with:

import pandas as pd
df = pd.read_csv("test.csv", header=None)

e.g.

           0         1         2         3        4
0   1.539240  0.423437 -0.687014   Chicago   Safari
1   0.815336  0.913623  1.800160    Boston   Safari
2   0.821214 -0.824839  0.483724  New York   Safari

.

UPDATE (2018/02/04) The question assumes numerical columns are NOT categorical, @Zero's accepted answer solves this.

BE CAREFUL - As @Sagarkar's comment points out that's not always true. The difficulty is that Data Types and Categorical/Ordinal/Nominal types are orthogonal concepts, thus mapping between them isn't straightforward. @Jeff's answer below specifies the precise manner to achieve the manual mapping.

Body:
`categorical_values  = (df.dtypes == 'object')
categorical_variables = categorical_variables =[categorical_values.index[ind]
for ind, val in enumerate(categorical_values) if val == True]

In the first line of code, we obtain a series which gives information regarding all the columns. The series gives information on which column is an object type and which column is not of the object type by representing it with a Boolean value.

In the second line, we use a list comprehension using enumeration(iterating through index and value), so that we could easily find the column which is of categorical type and append it to the categorical_variables list


问:
Perl stash output
I am trying to run a code snippet from the Advanced Perl Programming book for dumping the stash. This is without any additional packages from CPAN.

The package containing the stash related instructions is as follows:

```<code>package DUMPVAR;

sub dumpvar {
    my ($packageName) = @_;

    local (*alias);
    *stash = *{"${packageName}::"};

    $, = " ";

    while (($varName, $globValue) = each %stash) {

        print "\n $varName ===========================================\n";
        *alias = $globValue;

        if (defined ($alias)) {
            print "\t \$$varName $alias \n";
        }
        if (@alias) {
            print "\t \@$varName @alias \n";
        }
        if (keys %alias) {
            print "\t \%$varName " , %alias, " \n";
        }
    };
};
1;
</code>```

The calling code is

```<code>#!/usr/bin/perl
use strict;
use warnings;

use DUMPVAR;

package MyData;

my $x = 10;
my @y = (1,2,3);
my %z = (1,2,3,4,5,6);
my $z = 300;

DUMPVAR::dumpvar('MyData');
</code>```

I get no output what so ever. what is the problem?

答:
You don't see anything because you've only defined lexical variables. Those aren't tracked in the package system. Get rid of my (and strict because you haven't declared things, and warnings because you only use things once):

```<code>package MyData;

$x = 10;
@y = (1,2,3);
%z = (1,2,3,4,5,6);
$z = 300;

Dumpvar::dumpvar('MyData');
</code>```

The output is:

```<code> y ===========================================
     @y 1 2 3

 x ===========================================
     $x 10

 z ===========================================
     $z 300
     %z  3 4 5 6 1 2
</code>```

Title: Perl stash output

Body:
I am trying to run a code snippet from the Advanced Perl Programming book for dumping the stash. This is without any additional packages from CPAN.

The package containing the stash related instructions is as follows:

package DUMPVAR;

sub dumpvar {
    my ($packageName) = @_;

    local (*alias);
    *stash = *{"${packageName}::"};

    $, = " ";

    while (($varName, $globValue) = each %stash) {

        print "\n $varName ===========================================\n";
        *alias = $globValue;

        if (defined ($alias)) {
            print "\t \$$varName $alias \n";
        }
        if (@alias) {
            print "\t \@$varName @alias \n";
        }
        if (keys %alias) {
            print "\t \%$varName " , %alias, " \n";
        }
    };
};
1;

The calling code is

#!/usr/bin/perl
use strict;
use warnings;

use DUMPVAR;

package MyData;

my $x = 10;
my @y = (1,2,3);
my %z = (1,2,3,4,5,6);
my $z = 300;

DUMPVAR::dumpvar('MyData');

I get no output what so ever. what is the problem?

Body:
You don't see anything because you've only defined lexical variables. Those aren't tracked in the package system. Get rid of my (and strict because you haven't declared things, and warnings because you only use things once):

package MyData;

$x = 10;
@y = (1,2,3);
%z = (1,2,3,4,5,6);
$z = 300;

Dumpvar::dumpvar('MyData');

The output is:

 y ===========================================
     @y 1 2 3

 x ===========================================
     $x 10

 z ===========================================
     $z 300
     %z  3 4 5 6 1 2


问:
Generating a new dataframe from existing columns
I am trying to create a new column D from existing A, B, C column.

first value in Col D is A1

second value in Col D is B2

third value in Col D is C3

fourth value in Col D is A4

fifth value in Col D is B5

sixth value in Col D is C6

following this pattern, the rest of the values in Col D is iteration of this pattern. Please reference the graph.

Any code ideas?

Click the link to see the picture

答:
Here's another way:

```<code>import pandas as pd
import numpy as np

#Create input dataframe:
df = pd.DataFrame(index=[*'123456'], columns=[*'ABC'])
df = df.apply(lambda x: x.name+x.index)
df
</code>```

Input Dataframe:

```<code>    A   B   C
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3
4  A4  B4  C4
5  A5  B5  C5
6  A6  B6  C6
</code>```

Use cumsum with lookup:

```<code>s = ((df['A'].notna().cumsum()-1) % df.shape[1])
df['d'] = df.lookup(df.index, df.columns[s])
df
</code>```

Output:

```<code>    A   B   C   d
1  A1  B1  C1  A1
2  A2  B2  C2  B2
3  A3  B3  C3  C3
4  A4  B4  C4  A4
5  A5  B5  C5  B5
6  A6  B6  C6  C6
</code>```

Body:
Here's another way:

import pandas as pd
import numpy as np

#Create input dataframe:
df = pd.DataFrame(index=[*'123456'], columns=[*'ABC'])
df = df.apply(lambda x: x.name+x.index)
df

Input Dataframe:

    A   B   C
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3
4  A4  B4  C4
5  A5  B5  C5
6  A6  B6  C6

Use cumsum with lookup:

s = ((df['A'].notna().cumsum()-1) % df.shape[1])
df['d'] = df.lookup(df.index, df.columns[s])
df

Output:

    A   B   C   d
1  A1  B1  C1  A1
2  A2  B2  C2  B2
3  A3  B3  C3  C3
4  A4  B4  C4  A4
5  A5  B5  C5  B5
6  A6  B6  C6  C6


问:
Script which takes a PID as operand and prints PIDs of all its children, grandchildren, etc
I am new at programming. As I know is every process can create a child process. When you open a terminal, a process is created, and when you call a command inside the terminal a child process is created. I want to see that child processes and understand how it works. My friend shared his code with me but It is too complicated for me. I want to make it more simple. I hope someone can help me. Have a nice day to everyone! Here is the code:</p>

```<code>    #!/bin/bash

#Function that will display the process with the parent process ID given as argument
function get_child()
{
        #depth will hold the number of generation. E.g 0 for main process, 1 for children, 2 for grandchildre and so on

local depth=$depth
        # ps --ppid $parent will get the processes whose parent ID is $parent

output=`ps --ppid $parent`
        #increment the depth

depth=$(($depth+1))
        # Pipe the value of $output to tail -n + 2. It will remove the first line from $output because that line only contains title of the columns
        # awk '{print $1}' will only print the first column (Process ID) of eachline
        # While read child will iterate over all the process IDs referred as $child

echo "$output" | tail -n +2 | awk '{print $1}' | while read child

do
                #If $child is not empty i.e. it contains a process ID then echo the child process id and send that process id as parent process id to the get_child() function recursively

if [ $child ]
                then
                        for((i=0;i<depth;i++))
                        do
                                echo -n "-"
                        done
                        echo $depth. $child
                        parent=$child
                        get_child $child $depth
                fi
        done
}

parent=$1
depth=0
echo $parent
get_child $parent $depth
</code>```

答:
A short version of your algorithm.

I intentionally leave it without comment, so you can do the research on the Bash features and syntax, and gain some knowledge on your own for your assignment.

#!/usr/bin/env bash

get_child()
{
  local -i pid=0 ppid=$1 depth=$2
  printf '%*s%d. %d\n' "$depth" '' "$depth" "$ppid"
  while read -r pid; do
    ((pid)) && get_child $pid $((depth + 1))
  done < <(ps -o pid= --ppid $ppid)
}

get_child $1 0
```

<p>No Bashism version:</p>

<pre class="lang-sh prettyprint-override"><code>#!/usr/bin/env sh

get_child()
{
  p=0
  printf '%*s%d. %d\n' $2 '' $2 $1
  ps -o pid= --ppid $1 |
    while read -r p; do
      [ $p -ne 0 ] && get_child $p $(($2 + 1))
    done
}

get_child $1 0
</code>```

Body:
I am new at programming. As I know is every process can create a child process. When you open a terminal, a process is created, and when you call a command inside the terminal a child process is created. I want to see that child processes and understand how it works. My friend shared his code with me but It is too complicated for me. I want to make it more simple. I hope someone can help me. Have a nice day to everyone! Here is the code:

    #!/bin/bash

#Function that will display the process with the parent process ID given as argument
function get_child()
{
        #depth will hold the number of generation. E.g 0 for main process, 1 for children, 2 for grandchildre and so on

local depth=$depth
        # ps --ppid $parent will get the processes whose parent ID is $parent

output=`ps --ppid $parent`
        #increment the depth

depth=$(($depth+1))
        # Pipe the value of $output to tail -n + 2. It will remove the first line from $output because that line only contains title of the columns
        # awk '{print $1}' will only print the first column (Process ID) of eachline
        # While read child will iterate over all the process IDs referred as $child

echo "$output" | tail -n +2 | awk '{print $1}' | while read child

do
                #If $child is not empty i.e. it contains a process ID then echo the child process id and send that process id as parent process id to the get_child() function recursively

if [ $child ]
                then
                        for((i=0;i<depth;i++))
                        do
                                echo -n "-"
                        done
                        echo $depth. $child
                        parent=$child
                        get_child $child $depth
                fi
        done
}

parent=$1
depth=0
echo $parent
get_child $parent $depth

Body:
A short version of your algorithm.

I intentionally leave it without comment, so you can do the research on the Bash features and syntax, and gain some knowledge on your own for your assignment.

#!/usr/bin/env bash

get_child()
{
  local -i pid=0 ppid=$1 depth=$2
  printf '%*s%d. %d\n' "$depth" '' "$depth" "$ppid"
  while read -r pid; do
    ((pid)) && get_child $pid $((depth + 1))
  done < <(ps -o pid= --ppid $ppid)
}

get_child $1 0

No Bashism version:

#!/usr/bin/env sh

get_child()
{
  p=0
  printf '%*s%d. %d\n' $2 '' $2 $1
  ps -o pid= --ppid $1 |
    while read -r p; do
      [ $p -ne 0 ] && get_child $p $(($2 + 1))
    done
}

get_child $1 0


问:
how to access ExchangeUser() object in Javascript
Im developing an Outlook Web addin to replace and existing Outlook VSTO addin.

Part of the addin grabs the current users details and does this via the 'Microsoft.Office.Interop.Outlook.ExchnageUser' class (c#) but i cant find the equivalent in the Office.js library.

Should I be using EWS and making calls to the api to retrieve the details?

Many thanks for any help that can be offered

答:
You are on the right avenue, EWS is what you need. See the GetPersona operation which returns a set of properties that are associated with a persona. Here is what MSDN states:

The GetPersona operation provides access to aggregated contact information in the form of a persona. The PersonaId element in the request identifies the persona to return in the response. The response can contain a default set of persona properties or a custom property set. We recommend that you specify a custom property set so that unused properties are not processed and sent from the server to the client.


问:
Is there a way to store data in mongoDB by reference?
What I want to do is avoid data duplication (embedded), but also avoid fields relations by IDs.

Example:

{ Books: [
        { id: 1, name: "Foo1", author: referenceToTheAuthorWithId1 },
        { id: 2, name: "Foo2", author: referenceToTheAuthorWithId1 }
]}

{ Authors: [
       {id: 1, name: "Bar"}
]}

So each time I want to get a book, it will also retrieve its author, but that author object would be a reference to the Author collection.

答:
You can manually set _id fields for all of the documents you insert, and you can have identical ids in documents in various collections that refer to some common data.

In your example, if you replaced Authors with Authorships it would make some sense to have authorship id be the same as book id (at least this schema would support an author writing multiple books).

However, such  a schema does not support multiple authors per book.


问:
Deserialize a binary tree breadth-first in Functional Programming
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

```<code>class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???
</code>```

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

```<code>class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}
</code>```

答:
First of all, you can use a case class to simplify your tree class, and you should use Option instead of null:

```<code>case class Tree(value: Int, left: Option[Tree], right: Option[Tree])
</code>```

Next, the main trouble here is because your tree is immutable, it needs to be built with a depth-first post-order traversal, and your serialization format requires a breadth-first level-order traversal. So you first have to deserialize to a data structure that can then be traversed in depth-first order. The following uses a Map from (row, column) to the node value:

@scala.annotation.tailrec
private def bfsTraverse(
    serialized: List[Option[Int]],
    queue: Queue[(Int, Int)],
    map: Map[(Int, Int), Int]): Map[(Int, Int), Int] = {
  val ((row, col), queueTail) = queue.dequeue
  if (serialized.isEmpty) {
    map
  } else if (serialized.head.isEmpty) {
    bfsTraverse(serialized.tail, queueTail, map)
  } else {
    val newQueue = queueTail.enqueueAll(List((row + 1, col * 2), (row + 1, col * 2 + 1)))
    val newMap = map + ((row, col) -> serialized.head.get)
    bfsTraverse(serialized.tail, newQueue, newMap)
  }
}
```

<p>Now you can use the output of that function to build your <code>Tree</code>:</p>

<pre class="lang-scala prettyprint-override"><code>private def buildTree(row: Int, col: Int, map: Map[(Int, Int), Int]): Option[Tree] = {
  map.get((row, col)).map{value =>
    Tree(value, buildTree(row + 1, col * 2, map), buildTree(row + 1, col * 2 + 1, map))
  }
}
</code>```

Body:
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}

Body:
First of all, you can use a case class to simplify your tree class, and you should use Option instead of null:

case class Tree(value: Int, left: Option[Tree], right: Option[Tree])

Next, the main trouble here is because your tree is immutable, it needs to be built with a depth-first post-order traversal, and your serialization format requires a breadth-first level-order traversal. So you first have to deserialize to a data structure that can then be traversed in depth-first order. The following uses a Map from (row, column) to the node value:

@scala.annotation.tailrec
private def bfsTraverse(
    serialized: List[Option[Int]],
    queue: Queue[(Int, Int)],
    map: Map[(Int, Int), Int]): Map[(Int, Int), Int] = {
  val ((row, col), queueTail) = queue.dequeue
  if (serialized.isEmpty) {
    map
  } else if (serialized.head.isEmpty) {
    bfsTraverse(serialized.tail, queueTail, map)
  } else {
    val newQueue = queueTail.enqueueAll(List((row + 1, col * 2), (row + 1, col * 2 + 1)))
    val newMap = map + ((row, col) -> serialized.head.get)
    bfsTraverse(serialized.tail, newQueue, newMap)
  }
}

Now you can use the output of that function to build your Tree:

private def buildTree(row: Int, col: Int, map: Map[(Int, Int), Int]): Option[Tree] = {
  map.get((row, col)).map{value =>
    Tree(value, buildTree(row + 1, col * 2, map), buildTree(row + 1, col * 2 + 1, map))
  }
}


问:
permute i and T[i]
Assuming that I have an array of int T,
I am looking for an in-place algorithm that permute i and T[i]

I have : [3 2 0 1] (a)

I want : [2 3 1 0] (b)

eg. in (b) T[0] = 2 because, in (a) T[2] was equal to 0.

I was expecting to find a simple O(n) time, O(1) space algorithm, but I can't find it. Any ideas ?

Note :

There is one sigle array (a) is before (b) is after.

Values in the array belong to [0, N[, no duplicate.

答:
This is my attempt to solve this problem in-place without extra memory. It is a O(n) algorithm.

The algorithm by jpalecek is quite intelligent but not intuitive to read, at least not for me. I've tried it out and it works but I haven't had the time to understand why and comments would be great.

The algorithm by Gracenotes is great as long as the array isn't too big. If the data is large, one may have to create the array dynamically.

The basic idea in my algorithm is to update the array by following the chain of index and value pairs. For example index 0 maps to value 3. By using value 3 as the index you will find the next pair which is index 3 in the array and value 1. Essentially I save the next index and value pair and update the previous index and pair value  until I am done the chain.

If you can make it more efficient, elegant or better overall, I would be interested.

I've compiled and tested the code below but haven't used any other test input. I've left in debug output for those who wish to try it out and better understand how it works.

```<code>// Array print routine.
void printArray (const char * str_p,int a[], int n)
{
   printf ("%s\n", str_p);
   for (int i = 0; i < n; i++)
   {
      printf ("%i ", i);
   }
   printf ("\n");
   for (int i = 0; i < n; i++)
   {
      printf ("%i ", a[i]);
   }
   printf ("\n\n");
}

// The main code.
void PermuteTheDamnArray()
{
   printArray ("Initial Array", a,n);

   int i = 0;     // Simply a counter.
   int p_ix = 0;  // Previous Index.
   int p_val = a[0]; // Previous Value.
   int n_ix = a[0];  // Next index.
   int n_val = a[n_ix]; // Next Value.
   for (i = 0; i < n; i++)
   {
      // Replace.
      printf ("Swapping orig (%i,%i) with (%i,%i)\n", n_ix, n_val,p_val, p_ix);
      a[p_val] = p_ix;

      printArray ("Array after swap", a,n);

      // The next index and value pair becomes the new previous index and value pair.
      p_ix = n_ix;
      p_val = n_val;
      printf ("The previous pair is now: (%i,%i)\n", p_ix, p_val);

      // Get the next index and value pair.
      n_ix = n_val;
      n_val = a[n_val];
      printf ("The next pair is now: (%i,%i)\n", n_ix, n_val);

   }

   printArray ("Final Array", a,n);
}

Output:

Swapping orig (3,1) with (3,0)
Array after swap
0 1 2 3
3 2 0 0

The previous pair is now: (3,1)
The next pair is now: (1,2)
Swapping orig (1,2) with (1,3)
Array after swap
0 1 2 3
3 3 0 0

The previous pair is now: (1,2)
The next pair is now: (2,0)
Swapping orig (2,0) with (2,1)
Array after swap
0 1 2 3
3 3 1 0

The previous pair is now: (2,0)
The next pair is now: (0,3)
Swapping orig (0,3) with (0,2)
Array after swap
0 1 2 3
2 3 1 0

The previous pair is now: (0,3)
The next pair is now: (3,0)
Final Array
0 1 2 3
2 3 1 0
</code>```

OwnerDisplayName: Ben

ContentLicense: CC BY-SA 2.5

Title: permute i and T[i]

LastEditorDisplayName: nlucaroni

Body:
This is my attempt to solve this problem in-place without extra memory. It is a O(n) algorithm.

The algorithm by jpalecek is quite intelligent but not intuitive to read, at least not for me. I've tried it out and it works but I haven't had the time to understand why and comments would be great.

The algorithm by Gracenotes is great as long as the array isn't too big. If the data is large, one may have to create the array dynamically.

The basic idea in my algorithm is to update the array by following the chain of index and value pairs. For example index 0 maps to value 3. By using value 3 as the index you will find the next pair which is index 3 in the array and value 1. Essentially I save the next index and value pair and update the previous index and pair value  until I am done the chain.

If you can make it more efficient, elegant or better overall, I would be interested.

I've compiled and tested the code below but haven't used any other test input. I've left in debug output for those who wish to try it out and better understand how it works.

// Array print routine.
void printArray (const char * str_p,int a[], int n)
{
   printf ("%s\n", str_p);
   for (int i = 0; i < n; i++)
   {
      printf ("%i ", i);
   }
   printf ("\n");
   for (int i = 0; i < n; i++)
   {
      printf ("%i ", a[i]);
   }
   printf ("\n\n");
}

// The main code.
void PermuteTheDamnArray()
{
   printArray ("Initial Array", a,n);

   int i = 0;     // Simply a counter.
   int p_ix = 0;  // Previous Index.
   int p_val = a[0]; // Previous Value.
   int n_ix = a[0];  // Next index.
   int n_val = a[n_ix]; // Next Value.
   for (i = 0; i < n; i++)
   {
      // Replace.
      printf ("Swapping orig (%i,%i) with (%i,%i)\n", n_ix, n_val,p_val, p_ix);
      a[p_val] = p_ix;

      printArray ("Array after swap", a,n);

      // The next index and value pair becomes the new previous index and value pair.
      p_ix = n_ix;
      p_val = n_val;
      printf ("The previous pair is now: (%i,%i)\n", p_ix, p_val);

      // Get the next index and value pair.
      n_ix = n_val;
      n_val = a[n_val];
      printf ("The next pair is now: (%i,%i)\n", n_ix, n_val);

   }

   printArray ("Final Array", a,n);
}

Output:

Swapping orig (3,1) with (3,0)
Array after swap
0 1 2 3
3 2 0 0

The previous pair is now: (3,1)
The next pair is now: (1,2)
Swapping orig (1,2) with (1,3)
Array after swap
0 1 2 3
3 3 0 0

The previous pair is now: (1,2)
The next pair is now: (2,0)
Swapping orig (2,0) with (2,1)
Array after swap
0 1 2 3
3 3 1 0

The previous pair is now: (2,0)
The next pair is now: (0,3)
Swapping orig (0,3) with (0,2)
Array after swap
0 1 2 3
2 3 1 0

The previous pair is now: (0,3)
The next pair is now: (3,0)
Final Array
0 1 2 3
2 3 1 0

OwnerDisplayName: Stackster


问:
implementing simple Document management
My qustion is: How would you go on implementing simple DMS(document management) based on following requirements?

DMS shouls be distributed web application.

Support for document versioning.

Support for document locking.

Document search.

Im already clear on what technologies I want to use. I will use Sring MVC, Hibernate and relational (most likely MYSQL) database.

One thing Im not very clear on is if I need to use webdav, since I could just upload or download documets. I thing I have to because I need to acomplish point 2. and especially point 3. somehow. Is this the right way to go?

Any examples or experience with this would come very handy :). May be Milton is not the best library to pick for webdav?

答:
Think about using JCR Java content Repository
http://en.wikipedia.org/wiki/Content_repository_API_for_Java  or you can have a look at the job done on Alfresco or and Exo framework they did a good job </p>

Title: implementing simple Document management


问:
C++: seeding random number per Stroustrup's examples
I'm using small modifications Stroustrup's C++ examples for random numbers in C++ 4th Ed Page 127-130.

I'm having trouble modifying the example on Page 130 below to use a non-deterministic random seed.  I get warning when adding in the code re{rd} in Rand_ints constructor.  I have included the warnings but am unsure what they mean or how to resolve them.  Does anyone know?

Page 130 modified code to use non-deterministic random number:

```<code>#include <random>
#include <iostream>
#include <functional>
using namespace std;

class Rand_int {
public:
    Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
    int operator()() { return dist(re); } // draw an int
private:
    random_device rd;
    default_random_engine re;
    uniform_int_distribution<> dist;
};

int main(int argc, char *argv[])
{
    Rand_int rnd {1, 6};

    vector<int> hist(7);

    for (int i=0; i<200; i++)
        ++hist[rnd()];

    for (size_t i=1; i<hist.size(); i++) {
        cout << i << '\t';
        for (int j=0; j!=hist[i]; ++j)
            cout << '*';
        cout << endl;
    }

    return 0;
}
</code>```

Warnings:

```<code>test93.cc:13:32: warning: ‘Rand_int::dist’ will be initialized after [-Wreorder]
     uniform_int_distribution<> dist;
                                ^~~~
test93.cc:12:27: warning:   ‘std::default_random_engine Rand_int::re’ [-Wreorder]
     default_random_engine re;
                           ^~
test93.cc:8:5: warning:   when initialized here [-Wreorder]
     Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
     ^~~~~~~~
1   ********************************
2   *********************************
3   *************************************
4   ****************************************
5   ********************************
6   **************************
</code>```

Code from Page 127 and 128 that worked to generate non-deterministic random number:

```<code>#include <random>
#include <iostream>
#include <functional>
using namespace std;

int main(int argc, char *argv[])
{
    using engine = default_random_engine;
    using distribution = uniform_int_distribution<>;

    random_device rd;  // for seed
    engine re{rd()};

    distribution dist {1,6};
    auto rand = bind(dist, re);

    vector<int> hist(7);

    for (int i=0; i<200; i++)
        ++hist[rand()];

    for (size_t i=1; i<hist.size(); i++) {
        cout << i << '\t';
        for (int j=0; j!=hist[i]; ++j)
            cout << '*';
        cout << endl;
    }

    return 0;
}
</code>```

答:
Members of a class are initialized in the order that they are declared, regardless of the order you initialize them in the member initializer list. The compiler error is quite specific, and points out that you should write:</p>

```<code>Rand_int(int low, int high) : re{rd()}, dist{low,high} { }
</code>```

Body:
I'm using small modifications Stroustrup's C++ examples for random numbers in C++ 4th Ed Page 127-130.

I'm having trouble modifying the example on Page 130 below to use a non-deterministic random seed.  I get warning when adding in the code re{rd} in Rand_ints constructor.  I have included the warnings but am unsure what they mean or how to resolve them.  Does anyone know?

Page 130 modified code to use non-deterministic random number:

#include <random>
#include <iostream>
#include <functional>
using namespace std;

class Rand_int {
public:
    Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
    int operator()() { return dist(re); } // draw an int
private:
    random_device rd;
    default_random_engine re;
    uniform_int_distribution<> dist;
};

int main(int argc, char *argv[])
{
    Rand_int rnd {1, 6};

    vector<int> hist(7);

    for (int i=0; i<200; i++)
        ++hist[rnd()];

    for (size_t i=1; i<hist.size(); i++) {
        cout << i << '\t';
        for (int j=0; j!=hist[i]; ++j)
            cout << '*';
        cout << endl;
    }

    return 0;
}

Warnings:

test93.cc:13:32: warning: ‘Rand_int::dist’ will be initialized after [-Wreorder]
     uniform_int_distribution<> dist;
                                ^~~~
test93.cc:12:27: warning:   ‘std::default_random_engine Rand_int::re’ [-Wreorder]
     default_random_engine re;
                           ^~
test93.cc:8:5: warning:   when initialized here [-Wreorder]
     Rand_int(int low, int high) :dist{low,high}, re{rd()} { }
     ^~~~~~~~
1   ********************************
2   *********************************
3   *************************************
4   ****************************************
5   ********************************
6   **************************

Code from Page 127 and 128 that worked to generate non-deterministic random number:

#include <random>
#include <iostream>
#include <functional>
using namespace std;

int main(int argc, char *argv[])
{
    using engine = default_random_engine;
    using distribution = uniform_int_distribution<>;

    random_device rd;  // for seed
    engine re{rd()};

    distribution dist {1,6};
    auto rand = bind(dist, re);

    vector<int> hist(7);

    for (int i=0; i<200; i++)
        ++hist[rand()];

    for (size_t i=1; i<hist.size(); i++) {
        cout << i << '\t';
        for (int j=0; j!=hist[i]; ++j)
            cout << '*';
        cout << endl;
    }

    return 0;
}

Body:
Members of a class are initialized in the order that they are declared, regardless of the order you initialize them in the member initializer list. The compiler error is quite specific, and points out that you should write:

Rand_int(int low, int high) : re{rd()}, dist{low,high} { }


问:
Django model to record transactions from two different apps of a Bookstore website
I am new to Django and i'd like to build a bookstore. The site will sell 2 types of products (Books and Individual question solutions) and i have split those into 2 different django apps. How can i handle the final individual purchases. Is there a way to for example have 1 'Purchase' model that will recieve either Books or Solutions and save transaction into database upon completion of purchase ?
I want this Purchase model to have title, date of purchase, customer info (name and email).</p>

答:
Sure, you are very flexibel when using Django.Models. Since one/many-to-many fields can "link information" behind the scenes, there are close to no limits.

You may start with this model structure in your app:

```<code>from django.db import models

# Basic Books Model

class BooksPurchase(models.Model):
    books_title = models.CharField(max_length=150, blank=False)
    books_purchase_date = models.DateTimeField(blank=False)
    books_customer_name = models.CharField(max_length=150, blank=False)
    books_customer_email = models.CharField(max_length=150, blank=False)

    class Meta:
        db_table = 'books_purchase'

# Basic Solutions Model

class Solutions(models.Model):
    solutions_title = models.CharField(max_length=150, blank=False)
    [...]

    class Meta:
        db_table = 'solutions_information'

# Basic User Model

class Customers(models.Model):
    customer_name = models.CharField(max_length=150, blank=False)
    customer_mail = models.CharField(max_length=150, blank=False)
    [...]

    class Meta:
        db_table = 'customer_data'
</code>```

Note that you can use any Model within any file of your Django project by just importing it:

```<code>from app.models import model_name
</code>```

Also don't forget to run makemigrations and migrate to push the model to the DB.

Body:
Sure, you are very flexibel when using Django.Models. Since one/many-to-many fields can "link information" behind the scenes, there are close to no limits.

You may start with this model structure in your app:

from django.db import models

# Basic Books Model

class BooksPurchase(models.Model):
    books_title = models.CharField(max_length=150, blank=False)
    books_purchase_date = models.DateTimeField(blank=False)
    books_customer_name = models.CharField(max_length=150, blank=False)
    books_customer_email = models.CharField(max_length=150, blank=False)

    class Meta:
        db_table = 'books_purchase'

# Basic Solutions Model

class Solutions(models.Model):
    solutions_title = models.CharField(max_length=150, blank=False)
    [...]

    class Meta:
        db_table = 'solutions_information'

# Basic User Model

class Customers(models.Model):
    customer_name = models.CharField(max_length=150, blank=False)
    customer_mail = models.CharField(max_length=150, blank=False)
    [...]

    class Meta:
        db_table = 'customer_data'

Note that you can use any Model within any file of your Django project by just importing it:

from app.models import model_name

Also don't forget to run makemigrations and migrate to push the model to the DB.


答:
The compiler is telling you that the data members of Rand_int will be initialized in the order that they are declared (rd, then re, then dist) but that this does not match the order in which you have specified them in the constructor's initializer list:

```<code>dist{low,high}, re{rd()}
</code>```

This warning is intended to alert you to the fact that re is initialized before dist even though you have specified them in the opposite order.  To fix this, just reorder the initializer list:

```<code>re{rd()}, dist{low,high}
</code>```

This doesn't change the behavior of the program, it just silences the compiler warning.  The warning is there because the initialization order can matter (here it matters that rd is initialized before re, for example) and the incorrect order in the initializer list can indicate that you expect initialization to happen in a different order than it actually is.

Title: C++: seeding random number per Stroustrup's examples

Body:
The compiler is telling you that the data members of Rand_int will be initialized in the order that they are declared (rd, then re, then dist) but that this does not match the order in which you have specified them in the constructor's initializer list:

dist{low,high}, re{rd()}

This warning is intended to alert you to the fact that re is initialized before dist even though you have specified them in the opposite order.  To fix this, just reorder the initializer list:

re{rd()}, dist{low,high}

This doesn't change the behavior of the program, it just silences the compiler warning.  The warning is there because the initialization order can matter (here it matters that rd is initialized before re, for example) and the incorrect order in the initializer list can indicate that you expect initialization to happen in a different order than it actually is.


问:
how to replace strings with path objects in python?
I have the following dictionary:

config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}
```

<p>I want to replace <code><base_dir></code> with the value of <code><base_dir></code>
so I did this:</p>

<pre class="lang-py prettyprint-override"><code>for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<.+\>',value)
        for var in vars_to_replace:
            config[key] = value.replace(var,config[var[1:-1]])
</code>```

Currently getting the error: TypeError: replace() argument 2 must be str, not WindowsPath

If I wrap my config[var[1:-1]] with str(). It gets rid of the error but I lose the WindowsPath and now app_dir becomes a string. I want to reserve the object as WindowsPath.

答:
value is a string, so you are attempting to use the string's replace method, which takes two strings as arguments. If you want to change the value of the app_dir to be a Path object, you'll have to construct a path object and replace the current value ('/app') with that object. You can do this in several ways, here's one:

Convert base_dir to a string, replace the tag in app_dir with that string, and then convert the new path to a Path object

This would look like:

```<code>for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<*[.+]\>',value)
        for var in vars_to_replace:
            new_path = value.replace(var, str(config[var[1:-1]]))
            config[key] = Path(new_path)
</code>```

Another way would be to use something like path.join() to append to the path object:

```<code>path_addition = value.replace(var, "")
new_path_object = config[var].join(path_addition) # <-- might need to adjust this depending on the exact Path class you are using
config[key] = new_path_object
</code>```

Hope these help, happy coding!

Body:
I have the following dictionary:

config = {
'base_dir': Path(__file__).resolve(strict=True).parent.absolute(),
'app_dir': '<base_dir>/app'
}

I want to replace <base_dir> with the value of <base_dir>
so I did this:

for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<.+\>',value)
        for var in vars_to_replace:
            config[key] = value.replace(var,config[var[1:-1]])

Currently getting the error: TypeError: replace() argument 2 must be str, not WindowsPath

If I wrap my config[var[1:-1]] with str(). It gets rid of the error but I lose the WindowsPath and now app_dir becomes a string. I want to reserve the object as WindowsPath.

Body:
value is a string, so you are attempting to use the string's replace method, which takes two strings as arguments. If you want to change the value of the app_dir to be a Path object, you'll have to construct a path object and replace the current value ('/app') with that object. You can do this in several ways, here's one:

Convert base_dir to a string, replace the tag in app_dir with that string, and then convert the new path to a Path object

This would look like:

for key, value in config.items():
    if type(value) == str:
        vars_to_replace = re.findall(r'\<*[.+]\>',value)
        for var in vars_to_replace:
            new_path = value.replace(var, str(config[var[1:-1]]))
            config[key] = Path(new_path)

Another way would be to use something like path.join() to append to the path object:

path_addition = value.replace(var, "")
new_path_object = config[var].join(path_addition) # <-- might need to adjust this depending on the exact Path class you are using
config[key] = new_path_object

Hope these help, happy coding!


问:
duplicate same following elements in array
I should build a function that gets an array and it's size and return a pointer
to new array (i need do create new array by using malloc and realloc) that find the identical numbers and duplicates them in the row
for example the array:{1,8,8,70,2,2,2,5,5,2} and size 10 suppose to return a pointer to this array
{1,8,8,8,8,70,2,2,2,2,2,2,5,5,5,5,2}. Any clue what's wrong with my code??</p>

```<code>int * duplicateArray(int* arr, int n)

{
    int g = 1;
    int i,j=0;
    int *p = (int*)(calloc)(n, sizeof(int));
    assert(p);
    for (i = 0; i < n-1; i++)
    {
        if (arr[i] == arr[i + 1])
        {
             p= (int*)(realloc)(p, n+g * sizeof(int));
             n=n+g;
             assert(p);
             p[j] = arr[i];
             j++;
             p[j] = arr[i+1];
        }
        else
            p[j] = arr[i];
        j++;
    }
   return p;
}
</code>```

答:
Any clue what's wrong with my code??

If the parameter n is 1, then your program will allocate an array for 1 element of type int, but will write nothing to it. It won't copy anything from the input buffer.

You are accessing both the input arr and the output array p out of bounds, which causes undefined behavior. The loop

for (i = 0; i < n-1; i++)

will not count from 0 to the function parameter n minus 2, because n is being incremented inside the loop. This causes your loop to have more iterations than it is supposed to, which causes both the input and the output array to be accessed out of bounds.

Also, there doesn't seem to be much point in your variable g, as it never changes and always has the value 1.

The function prototype

int * duplicateArray(int* arr, int n);

does not seem meaningful, as the calling function has no way of knowing the size of the returned array. If you use the function prototype

void duplicateArray ( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output );

instead, the function duplicateArray can write the address of the new array to *pp_output_array and the number of elements in the array to *p_num_output. That way, the calling function will effectively be able to receive two "return values" instead of only one.

Here is my implementation of the function duplicateArray and also of the calling function:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void duplicateArray( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output )
{
    int i = 0, j = 0;

    // In the most extreme case, the output array must be 2 times larger than
    // the input buffer, so we allocate double the size of the input buffer.
    int *p_output_array = (int*)malloc( num_input * 2 * sizeof(int) );
    assert( p_output_array != NULL );

    while ( i < num_input )
    {
        int num_repetitions;

        int k = p_input_array[i++];

        //count the number of repetitions
        for ( num_repetitions = 0; i < num_input && p_input_array[i] == k; num_repetitions++, i++ );

        if ( num_repetitions == 0 )
        {
            p_output_array[j++] = k;
        }
        else
        {
            for ( int l = 0; l < num_repetitions + 1; l++ )
            {
                p_output_array[j++] = k;
                p_output_array[j++] = k;
            }
        }
    }

    //shrink the array to the actually needed size
    p_output_array = (int*)realloc( p_output_array, j * sizeof(int) );
    assert( p_output_array != NULL );

    *pp_output_array = p_output_array;
    *p_num_output = j;
}

int main()
{
    int arr[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    int *p;
    int num;

    duplicateArray( arr, sizeof(arr)/sizeof(*arr), &p, &num );

    for ( int i = 0; i < num; i++ ) {
        printf( "%d\n", p[i] );
    }

    free( p );
}
</code>```

Body:
I should build a function that gets an array and it's size and return a pointer
to new array (i need do create new array by using malloc and realloc) that find the identical numbers and duplicates them in the row
for example the array:{1,8,8,70,2,2,2,5,5,2} and size 10 suppose to return a pointer to this array
{1,8,8,8,8,70,2,2,2,2,2,2,5,5,5,5,2}. Any clue what's wrong with my code??

int * duplicateArray(int* arr, int n)

{
    int g = 1;
    int i,j=0;
    int *p = (int*)(calloc)(n, sizeof(int));
    assert(p);
    for (i = 0; i < n-1; i++)
    {
        if (arr[i] == arr[i + 1])
        {
             p= (int*)(realloc)(p, n+g * sizeof(int));
             n=n+g;
             assert(p);
             p[j] = arr[i];
             j++;
             p[j] = arr[i+1];
        }
        else
            p[j] = arr[i];
        j++;
    }
   return p;
}

Body:
Any clue what's wrong with my code??

If the parameter n is 1, then your program will allocate an array for 1 element of type int, but will write nothing to it. It won't copy anything from the input buffer.

You are accessing both the input arr and the output array p out of bounds, which causes undefined behavior. The loop

for (i = 0; i < n-1; i++)

will not count from 0 to the function parameter n minus 2, because n is being incremented inside the loop. This causes your loop to have more iterations than it is supposed to, which causes both the input and the output array to be accessed out of bounds.

Also, there doesn't seem to be much point in your variable g, as it never changes and always has the value 1.

The function prototype

int * duplicateArray(int* arr, int n);

does not seem meaningful, as the calling function has no way of knowing the size of the returned array. If you use the function prototype

void duplicateArray ( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output );

instead, the function duplicateArray can write the address of the new array to *pp_output_array and the number of elements in the array to *p_num_output. That way, the calling function will effectively be able to receive two "return values" instead of only one.

Here is my implementation of the function duplicateArray and also of the calling function:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void duplicateArray( const int *p_input_array, int num_input, int **pp_output_array, int *p_num_output )
{
    int i = 0, j = 0;

    // In the most extreme case, the output array must be 2 times larger than
    // the input buffer, so we allocate double the size of the input buffer.
    int *p_output_array = (int*)malloc( num_input * 2 * sizeof(int) );
    assert( p_output_array != NULL );

    while ( i < num_input )
    {
        int num_repetitions;

        int k = p_input_array[i++];

        //count the number of repetitions
        for ( num_repetitions = 0; i < num_input && p_input_array[i] == k; num_repetitions++, i++ );

        if ( num_repetitions == 0 )
        {
            p_output_array[j++] = k;
        }
        else
        {
            for ( int l = 0; l < num_repetitions + 1; l++ )
            {
                p_output_array[j++] = k;
                p_output_array[j++] = k;
            }
        }
    }

    //shrink the array to the actually needed size
    p_output_array = (int*)realloc( p_output_array, j * sizeof(int) );
    assert( p_output_array != NULL );

    *pp_output_array = p_output_array;
    *p_num_output = j;
}

int main()
{
    int arr[] = { 1, 8, 8, 70, 2, 2, 2, 5, 5, 2 };
    int *p;
    int num;

    duplicateArray( arr, sizeof(arr)/sizeof(*arr), &p, &num );

    for ( int i = 0; i < num; i++ ) {
        printf( "%d\n", p[i] );
    }

    free( p );
}


问:
Sharepoint ID search in PowerApps
I have one List Screen in which my items have the ID in Sharepoint as a Subtitle. I want to search by all: Title, Subtitle and Body. The problem is that when I try to search by the ID everything goes blank.

I've used this function:

```<code>Search(my_SP_List, TextSearchBox1.Text, "a", "b", "ID")
</code>```

The thing is that when I have the formula like this Search(my_SP_List, TextSearchBox1.Text, "a", "b") it works, but not with the ID from Sharepoint.

答: This is from their documentation: "The Search function finds records in a table that contain a string in one of their columns." ID probably is not a string</p>

Title: Sharepoint ID search in PowerApps

Body:
I have one List Screen in which my items have the ID in Sharepoint as a Subtitle. I want to search by all: Title, Subtitle and Body. The problem is that when I try to search by the ID everything goes blank.

I've used this function:

Search(my_SP_List, TextSearchBox1.Text, "a", "b", "ID")

The thing is that when I have the formula like this Search(my_SP_List, TextSearchBox1.Text, "a", "b") it works, but not with the ID from Sharepoint.


问:
SQL combine two rows with common batch number into one line
I have an Oracle SQL (select *) query that spools batch transactional information, the result of which outputs the main sender and receivers to different lines for the same transaction like below:

```<code>BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME RECEIVER_ACCT_NO    RECEIVER NAME
12345678    15-May-20   103.55  400001000        ENDCORP         (null)
12345678    15-May-20   34.55   400001000        (null)          78909909         JOHN SMITH
12345678    15-May-20   44.00   400001000        (null)          78853229         HENRY FAGIL
12345678    15-May-20   4.00    400001000        (null)          76849852        BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        (null)          72555099          FELIX MAGS
12222222    16-May-20   1902.00 400000105       ZENDCORP          (null)
12222222    17-May-20   1899.00 400000105        (null)          90333300          KEN GOTL
12222222    18-May-20   3.00    400000105        (null)          90127765         JONES MAST
</code>```

In this case, ENDCORP and ZENDCORP sent out batch payments of a total of 103.55 and 1902.00 to 4 and 2 clients respectively.

However, I would prefer my results to be in the form below:

```<code>BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME    RECEIVER_ACCT_NO        RECEIVER NAME
12345678    15-May-20   34.55   400001000        ENDCORP        78909909                JOHN SMITH
12345678    15-May-20   44.00   400001000        ENDCORP        78853229                HENRY FAGIL
12345678    15-May-20   4.00    400001000        ENDCORP        76849852                BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        ENDCORP        72555099                 FELIX MAGS
12222222    17-May-20  1899.00  400000105       ZENDCORP        90333300                  KEN GOTL
12222222    18-May-20   3.00    400000105       ZENDCORP        90127765                 JONES MAST
</code>```

I would appreciate guidance on how to formulate my query for this result

答:
I'm assuming when you say the query is select * that you are showing us the table structure. Otherwise we'd need more detail of the tables and your query.

If it's one table,  you just need to select where sender name is null and join to the same table on sender acct no and sender name is not null, selecting appropriate columns from each relation.

Body:
I have an Oracle SQL (select *) query that spools batch transactional information, the result of which outputs the main sender and receivers to different lines for the same transaction like below:

BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME RECEIVER_ACCT_NO    RECEIVER NAME
12345678    15-May-20   103.55  400001000        ENDCORP         (null)
12345678    15-May-20   34.55   400001000        (null)          78909909         JOHN SMITH
12345678    15-May-20   44.00   400001000        (null)          78853229         HENRY FAGIL
12345678    15-May-20   4.00    400001000        (null)          76849852        BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        (null)          72555099          FELIX MAGS
12222222    16-May-20   1902.00 400000105       ZENDCORP          (null)
12222222    17-May-20   1899.00 400000105        (null)          90333300          KEN GOTL
12222222    18-May-20   3.00    400000105        (null)          90127765         JONES MAST

In this case, ENDCORP and ZENDCORP sent out batch payments of a total of 103.55 and 1902.00 to 4 and 2 clients respectively.

However, I would prefer my results to be in the form below:

BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME    RECEIVER_ACCT_NO        RECEIVER NAME
12345678    15-May-20   34.55   400001000        ENDCORP        78909909                JOHN SMITH
12345678    15-May-20   44.00   400001000        ENDCORP        78853229                HENRY FAGIL
12345678    15-May-20   4.00    400001000        ENDCORP        76849852                BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        ENDCORP        72555099                 FELIX MAGS
12222222    17-May-20  1899.00  400000105       ZENDCORP        90333300                  KEN GOTL
12222222    18-May-20   3.00    400000105       ZENDCORP        90127765                 JONES MAST

I would appreciate guidance on how to formulate my query for this result


问:
Extract a certain component from a graph using igraph python
Description of the problem:

The objective is to extract the component that a certain vertex belongs to in order to calculate its size.

Steps of the code:

Use the igraph method clusters() to get the list of all connected components (c.c) in the graph.

Then, iterate over the c.c list while checking each time if that certain node belongs to it or not.

When it is found, I calculate its size.

The code is as follows:

```<code>def sizeofcomponent(clusters, vertex):
    for i in range(len(clusters)):
        if str(vertex) in clusters.subgraphs()[i].vs["name"]:
            return(len(clusters.subgraphs()[i].vs["name"]))
</code>```

The Problem is that this code will be used with extremely large graphs, and this way of doing things slowed my code by a lot. Is there a way to improve it?

EDIT 01: Explanation of how the algorithm works

Suppose that the following graph is the main graph:

The Maximal Independent Set (MIS) is calculated and we get the following graph that I call components:

Randomly add a node from the main Graph in a way that that node belongs to the main graph but doesn't belong to components (isn't part of the MIS). Example: adding node 10 to components.

Calculate the size of the component it forms.

The process is repeated with all nodes (ones that don't belong in components (MIS).

In the end, the node that forms the smallest component (smallest size) is the one added permanently to components.

Your solution:

When the following code is executed (i being the vertex):

```<code>    cls = components.clusters()
    c = cls.membership[i]
</code>```

The variable c value would be the following list:

Example: node (2) belongs to the component 1 (of id 1).

Why it wouldn't work for me:

The following line of code wouldn't give me the correct result:

```<code>    cls = components.clusters()
    c = cls.membership[i]
</code>```

because the ids of the nodes in the list c don't match up with the name of the nodes. Example: cls.membership[i] would give an exception error: list out of range. Instead of the correct result which is: 4.

Also, from your code, the size, in your case, is calculated in the following way:

```<code>    c = components.membership[i]
    s = components.membership.count(c)
</code>```

答:
You can simply get the component vertex i belongs to by doing

components = G.clusters()
c = components.membership[i]
```

<p>You can then get the size of component <code>c</code> using</p>

<pre class="lang-py prettyprint-override"><code>s = components.size(c)
</code>```

Body:
Description of the problem:

The objective is to extract the component that a certain vertex belongs to in order to calculate its size.

Steps of the code:

Use the igraph method clusters() to get the list of all connected components (c.c) in the graph.

Then, iterate over the c.c list while checking each time if that certain node belongs to it or not.

When it is found, I calculate its size.

The code is as follows:

def sizeofcomponent(clusters, vertex):
    for i in range(len(clusters)):
        if str(vertex) in clusters.subgraphs()[i].vs["name"]:
            return(len(clusters.subgraphs()[i].vs["name"]))

The Problem is that this code will be used with extremely large graphs, and this way of doing things slowed my code by a lot. Is there a way to improve it?

EDIT 01: Explanation of how the algorithm works

Suppose that the following graph is the main graph:

The Maximal Independent Set (MIS) is calculated and we get the following graph that I call components:

Randomly add a node from the main Graph in a way that that node belongs to the main graph but doesn't belong to components (isn't part of the MIS). Example: adding node 10 to components.

Calculate the size of the component it forms.

The process is repeated with all nodes (ones that don't belong in components (MIS).

In the end, the node that forms the smallest component (smallest size) is the one added permanently to components.

Your solution:

When the following code is executed (i being the vertex):

    cls = components.clusters()
    c = cls.membership[i]

The variable c value would be the following list:

Example: node (2) belongs to the component 1 (of id 1).

Why it wouldn't work for me:

The following line of code wouldn't give me the correct result:

    cls = components.clusters()
    c = cls.membership[i]

because the ids of the nodes in the list c don't match up with the name of the nodes. Example: cls.membership[i] would give an exception error: list out of range. Instead of the correct result which is: 4.

Also, from your code, the size, in your case, is calculated in the following way:

    c = components.membership[i]
    s = components.membership.count(c)

Body:
You can simply get the component vertex i belongs to by doing

components = G.clusters()
c = components.membership[i]

You can then get the size of component c using

s = components.size(c)


问:
Advice on Web Service or related technology
I am developing a system that must be able to receive an XML  messages (preferably without SOAP envelope) from other's company external system through the internet. I am not sure what technology is external system written in.
The developers from the external company must create a XML sending feature. I would like to minimazie their effort.
Is WCF good choice for that?

The OS will be either Windows XP with IIS 5.1 or Windows Server 2003 with IIS 6.0.
.NET Framework is 3.5.

Thanks.

答: You can use the WCF but also you can use Web Services.</p>


问:
How to use QtMqtt in CMake project?
To use Qt MQTT library in qmake project file (*.pro) QT += mqtt should be added.

What is CMake pandan for that?

答:
Based on the official example of how to use cmake with Qt I have created the CMakeLists.txt to compile one of the official Qt Mqtt examples:  Simple MQTT Client Example.</p>

```<code>cmake_minimum_required(VERSION 3.1.0)

project(simplemqttclient)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

if(CMAKE_VERSION VERSION_LESS "3.7.0")
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()

find_package(Qt5 COMPONENTS Widgets <b>Mqtt</b> REQUIRED)

add_executable(simplemqttclient
    mainwindow.ui
    mainwindow.cpp
    main.cpp
)

target_link_libraries(simplemqttclient Qt5::Widgets <b>Qt5::Mqtt</b>)</code>```

Title: How to use QtMqtt in CMake project?

Body:
Based on the official example of how to use cmake with Qt I have created the CMakeLists.txt to compile one of the official Qt Mqtt examples:  Simple MQTT Client Example.

cmake_minimum_required(VERSION 3.1.0)

project(simplemqttclient)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

if(CMAKE_VERSION VERSION_LESS "3.7.0")
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
endif()

find_package(Qt5 COMPONENTS Widgets Mqtt REQUIRED)

add_executable(simplemqttclient
    mainwindow.ui
    mainwindow.cpp
    main.cpp
)

target_link_libraries(simplemqttclient Qt5::Widgets Qt5::Mqtt)


问:
How to get content on the right of a card to position under the image using bootstrap?
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

```<code>    <div class="card">
        <div class="row no-gutters">
           <div class="col-auto col-md-6">
               <img src="img/image.jpg" class="img-fluid image" alt="PayCloud App Demo" width="620" height="465">
           </div>
           <div class="col">
             <div class="card-block px-2">
                <p class="card-title AppName">AppName</p>
                <p class="card-title Description">Restaurant Payment Service - January 2020</p>
                <p class="card-text AppDescription">App Description.</p>
                <a href="link.html"><span class="button">View Project</span></a>
             </div>
          </div>
       </div>
</div>
</code>```

CSS Below

```<code>.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}
</code>```

答:
What you are searching for is @media (CSS)
For more please go ahead and read this.</p>

Body:
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

AppName

Restaurant Payment Service - January 2020

App Description.

                View Project

CSS Below

.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}


问:
Is there a way to build CLI with no dependencies required?
Recently I though about scaffolding a little CLI with Ruby, but was concerned about using it on a machine with no Ruby installed. I've searched for examples of popular CLI's and found that Docker CLI is built with Go language. I'm able to use this CLI on my computer with no Go installed. How can one build a tool that will not require you to install Ruby?

My guess is that there's a build process involved and it might be compiled to something present on most systems, like shell or smth. Sorry if this is a lame guess/question!

答:
(note: this is not a detailed answer, just a summary of how it works)
Cli programs are just as other programs, there is nothing special about them.

Go is a compiled language - a program called "compiler" takes the go code and translate it directly to machine language, following the conventions imposed by an operative system. It becames pure 0 and 1, no references to anything else. The main advantage is that is self-contained, but you have to recompile it on every different architecture (32bit, arm processors, ...) and operating system (windows, linux, macos) - it's the operating system that take cares of redirecting input and output on cli.

Ruby, instead, is interpreted. There is a program called "Ruby interpreter" which translates your code to the appropriate machine code on the fly. It's a different approach, it's more "high level".
The advantage is that you don't need to recompile the code. However, the  "Ruby interpreter" itself must be written in some compiled language.