问:
i want to get data from database after filter between dates. I tried but no data found
```<code>if(!empty($data['start_date']) ||
            !empty($data['end_date'])){

            $sql = 'SELECT save_cards.*,
                    save_card_transaction.first_doc_name,
                    save_card_transaction.second_doc_name,
                    save_card_transaction.txn_id
                    FROM save_cards
                    RIGHT JOIN save_card_transaction
                    ON save_cards.id = save_card_transaction.card_id
                    WHERE ';

            if(!empty($data['start_date'])){
                $sql .="save_cards.created_date <= DATE(" .$data['start_date'].") ";
            }
            if(!empty($data['end_date']) && !empty($data['end_date'])){
                $sql .=" && ";
            }
            if(!empty($data['end_date'])){
                $sql .="save_cards.created_date >= DATE(".$data['end_date'].") ";
            }

            $sql .= 'AND save_cards.is_verified =? && save_card_transaction.payment_status =? &&  save_card_transaction.first_doc_name IS NOT NULL && save_card_transaction.second_doc_name IS NOT NULL order by save_cards.created_date desc';
            $result = $this->db->query($sql, array($data['verify'], $data['status']));
return $result->result_array();
</code>```

答:
Hi based on few info you gave mabe wrong if

```<code>if(!empty($data['end_date']) && !empty($data['end_date']))
</code>```

to

```<code>if(!empty($data['end_date']) && !empty($data['start_date']))
</code>```

Body:
Hi based on few info you gave mabe wrong if

if(!empty($data['end_date']) && !empty($data['end_date']))

to

if(!empty($data['end_date']) && !empty($data['start_date']))


来源: stackexchange

问:
How to get type of chan with reflect package
Say I have a chan in Go:

```<code>var c = make(chan int)
</code>```

how can discover that it's a channel using:

```<code>var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan
</code>```

but does anyone know how I determine the type of the channel, in this case int?

答:
Use Elem to get the channel type:

```<code>var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan
channelType := reflect.ValueOf(c).Type().Elem()
</code>```

For an int channel, channelType will be int.

ContentLicense: CC BY-SA 4.0

Body:
Say I have a chan in Go:

var c = make(chan int)

how can discover that it's a channel using:

var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan

but does anyone know how I determine the type of the channel, in this case int?

Body:
Use Elem to get the channel type:

var isChannel = reflect.ValueOf(c).Kind() == reflect.Chan
channelType := reflect.ValueOf(c).Type().Elem()

For an int channel, channelType will be int.


问:
Two functions involving recursive sum and dictionary
I'm doing an assignment. These are the instructions, and the docstring they provide:

You will write two functions in this challenge. First write a function
  called rec_dig_sum that takes in an integer and returns the recursive
  digit sum of that number.

Example of recursive digit sums: 101 => 1+0+1 = 2.

Then use that function within another function called
  distr_of_rec_digit_sums, that returns a dictionary where the keys are
  recursive digit sums, and the values are the counts of those digit
  sums occurring between a low and high (inclusive) range of input
  numbers. Assume low and high are positive integers where high is
  greater than low, and neither low nor high are negative. Your function
  should return a dictionary, not just print it.

```<code>def rec_dig_sum(n):
    '''
    Returns the recursive digit sum of an integer.

    Parameter
    ---------
    n: int

    Returns
    -------
    rec_dig_sum: int
       the recursive digit sum of the input n
    '''

def distr_of_rec_digit_sums(low=0, high=1500):
    '''
    Returns a dictionary representing the counts
        of recursive digit sums within a given range.

    Parameters
    ----------
    low: int
        an integer, 0 or positive, representing
        the lowest value in the range of integers
        for which finding the recursive digit sum
    high: int
        a positive integer greater than low, the
        inclusive upper bound for which finding
        the recursive digit sum

    Returns
    -------
    dict_of_rec_dig_sums: {int:int}
        returns a dictionary where the keys are
        the recursive digit sums and the values
        are the counts of those digit sums occurring
    '''
</code>```

This is the code I have attempted:

```<code>def rec_dig_sum(n):
  convert_to_int = [int(i) for i in lst]
  total = sum(convert_to_int)
  return total

def distr_of_rec_digit_sums(low=0, high=1500):
  if length >= 0 and length <= 1500 :
    d1 = {rec_dig_sum(n) : length}
  return d1

lst = list(str(n))
total = 0
length = len(lst)

print(distr_of_rec_digit_sums(5987))
</code>```

I am not sure why inputting the argument at the end of the function causes an error, as the first function should run using the same argument.

Am I approaching this correctly? Is there a way to make this better?

答:
First, your function is passed an argument, n, which is the integer whose digits are to be added together but you completely ignore this value and instead compute the sum using the value lst. The initialization of lst is performing half the work required to produce the result. All of the work necessary for producing the result should be in function rec_dig_sum, which should use the value n passed to it and nothing else. Using the approach you have taken, which is satisfactory, we then have:

```<code>def rec_dig_sum(n):
    convert_to_int = [int(i) for i in str(n)]
    total = sum(convert_to_int)
    return total
</code>```

Second, your statement lst = list(str(n)) will generate an error because n is only defined as a function argument to rec_dig_sum and is therefore not in scope.

Third, my interpretation of your exercise is that function distr_of_rec_digit_sums will be passed two values, low and high, and using those values you should generate all the integers in the range low, low + 1 ... high and for each one call function rec_dig_sum. These repeated calls to rec_dig_sum will result in returning a finite number of distinct values (this number being at least 1 and at most high - low + 1). You are for each distinct value count how many times that value occurred and create a dictionary where each key is a distinct value returned by rec_dig_sum and the value is the count of times that value was returned. For example, calling rec_dig_sum with arguments 12 and 21 will both result in the value 2 returned. So, if the function distr_of_rec_digit_sums is called with low=12 and high=21, then one of the dictionary keys will be 2 with a value of 2 (the count). You are then to return that dictionary. Now that I have hopefully explained this better, I will leave it to you make an improved attempt. If you have problems with this, pose it as a separate question.

Body:
I'm doing an assignment. These are the instructions, and the docstring they provide:

You will write two functions in this challenge. First write a function
  called rec_dig_sum that takes in an integer and returns the recursive
  digit sum of that number.

Example of recursive digit sums: 101 => 1+0+1 = 2.

Then use that function within another function called
  distr_of_rec_digit_sums, that returns a dictionary where the keys are
  recursive digit sums, and the values are the counts of those digit
  sums occurring between a low and high (inclusive) range of input
  numbers. Assume low and high are positive integers where high is
  greater than low, and neither low nor high are negative. Your function
  should return a dictionary, not just print it.

def rec_dig_sum(n):
    '''
    Returns the recursive digit sum of an integer.

    Parameter
    ---------
    n: int

    Returns
    -------
    rec_dig_sum: int
       the recursive digit sum of the input n
    '''

def distr_of_rec_digit_sums(low=0, high=1500):
    '''
    Returns a dictionary representing the counts
        of recursive digit sums within a given range.

    Parameters
    ----------
    low: int
        an integer, 0 or positive, representing
        the lowest value in the range of integers
        for which finding the recursive digit sum
    high: int
        a positive integer greater than low, the
        inclusive upper bound for which finding
        the recursive digit sum

    Returns
    -------
    dict_of_rec_dig_sums: {int:int}
        returns a dictionary where the keys are
        the recursive digit sums and the values
        are the counts of those digit sums occurring
    '''

This is the code I have attempted:

def rec_dig_sum(n):
  convert_to_int = [int(i) for i in lst]
  total = sum(convert_to_int)
  return total

def distr_of_rec_digit_sums(low=0, high=1500):
  if length >= 0 and length <= 1500 :
    d1 = {rec_dig_sum(n) : length}
  return d1

lst = list(str(n))
total = 0
length = len(lst)

print(distr_of_rec_digit_sums(5987))

I am not sure why inputting the argument at the end of the function causes an error, as the first function should run using the same argument.

Am I approaching this correctly? Is there a way to make this better?

Body:
First, your function is passed an argument, n, which is the integer whose digits are to be added together but you completely ignore this value and instead compute the sum using the value lst. The initialization of lst is performing half the work required to produce the result. All of the work necessary for producing the result should be in function rec_dig_sum, which should use the value n passed to it and nothing else. Using the approach you have taken, which is satisfactory, we then have:

def rec_dig_sum(n):
    convert_to_int = [int(i) for i in str(n)]
    total = sum(convert_to_int)
    return total

Second, your statement lst = list(str(n)) will generate an error because n is only defined as a function argument to rec_dig_sum and is therefore not in scope.

Third, my interpretation of your exercise is that function distr_of_rec_digit_sums will be passed two values, low and high, and using those values you should generate all the integers in the range low, low + 1 ... high and for each one call function rec_dig_sum. These repeated calls to rec_dig_sum will result in returning a finite number of distinct values (this number being at least 1 and at most high - low + 1). You are for each distinct value count how many times that value occurred and create a dictionary where each key is a distinct value returned by rec_dig_sum and the value is the count of times that value was returned. For example, calling rec_dig_sum with arguments 12 and 21 will both result in the value 2 returned. So, if the function distr_of_rec_digit_sums is called with low=12 and high=21, then one of the dictionary keys will be 2 with a value of 2 (the count). You are then to return that dictionary. Now that I have hopefully explained this better, I will leave it to you make an improved attempt. If you have problems with this, pose it as a separate question.


问:
How to return count of function calls between calls with the same input?
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

```<code>System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1
</code>```

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?

答:
Assuming I've understood the question correctly as:
'Return the number of invocations of the method since the last time the current argument was given, or -1 if it has never been given before', then you could do this with any Collection which maintains insertion order.

For example:

```<code>private final List<Integer> invocations = new ArrayList<>();

public int newNumber(final int i) {
    if (!this.invocations.contains(i)) {

        // Not seen before, so add to the List, and return -1.
        this.invocations.add(i);
        return -1;
    }

    // size - 1 for 0 indexed list.
    // - last index of it since that was the last time it was called.
    final int lastInvocation
            = this.invocations.size() - 1 - this.invocations.lastIndexOf(i);

    // Remove all prior occurrences of it in the List.
    // Not strictly necessary, but stops the List just growing all the time.
    this.invocations.removeIf(value -> value.equals(i));

    // Add the element as the latest invocation (head of the List)
    this.invocations.add(i);
    return lastInvocation;
}
</code>```

Note, thread safety very much not considered here.

Body:
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?

Body:
Assuming I've understood the question correctly as:
'Return the number of invocations of the method since the last time the current argument was given, or -1 if it has never been given before', then you could do this with any Collection which maintains insertion order.

For example:

private final List<Integer> invocations = new ArrayList<>();

public int newNumber(final int i) {
    if (!this.invocations.contains(i)) {

        // Not seen before, so add to the List, and return -1.
        this.invocations.add(i);
        return -1;
    }

    // size - 1 for 0 indexed list.
    // - last index of it since that was the last time it was called.
    final int lastInvocation
            = this.invocations.size() - 1 - this.invocations.lastIndexOf(i);

    // Remove all prior occurrences of it in the List.
    // Not strictly necessary, but stops the List just growing all the time.
    this.invocations.removeIf(value -> value.equals(i));

    // Add the element as the latest invocation (head of the List)
    this.invocations.add(i);
    return lastInvocation;
}

Note, thread safety very much not considered here.


问:
How to efficiently get output nodes in a directed graph in networkx?
I created a simple directed graph (DiGraph) in the Python network package networkx, like so:

```<code>import networkx as nx

G = DiGraph([(1, 2)])
</code>```

Now I would like to know the fastest / most efficient way to determine the output nodes (which in this case is the node 2). By output node I mean nodes in the directed graph that have no successor - with input nodes being nodes that have no predecessor. The analogy is from Machine Learning, in which I am supplying values to the input nodes, perform mathematical operations on the edges and have output values in the output nodes. See here for an example, in which p, d and lambda are input nodes and p' and d' are output nodes.

After reading the documentation I came up with such inefficient methods as traversing all nodes of the graph, calling successors() on them and saving all nodes with no successor. This however is terribly inefficient, especially since the graph is obviously considerably larger and more complex in my actual project. I was hoping for a simple and efficient method such as G.out_nodes() or something similar that is keeping track of the output nodes when the graph is edited, though I seem to be unable to find it. However since determining output and input nodes in a directed graph is no uncommon task am I of the opinion that I am missing something. I was hoping that you might be able to help me. Thank you very much.

答:
Once you have your graph you could iterate and get the nodes with out_degree equal to 0.

```<code>output_nodes = [u for u, deg in g.out_degree() if not deg]
</code>```

However, you could get them directly when building your graph, indeed you could remove from the nodes u if (u,v) is an arc. The remaining will be output nodes.

Another possibility is to use another way to represent your graph according to size/most common operations to be applied.

Body:
I created a simple directed graph (DiGraph) in the Python network package networkx, like so:

import networkx as nx

G = DiGraph([(1, 2)])

Now I would like to know the fastest / most efficient way to determine the output nodes (which in this case is the node 2). By output node I mean nodes in the directed graph that have no successor - with input nodes being nodes that have no predecessor. The analogy is from Machine Learning, in which I am supplying values to the input nodes, perform mathematical operations on the edges and have output values in the output nodes. See here for an example, in which p, d and lambda are input nodes and p' and d' are output nodes.

After reading the documentation I came up with such inefficient methods as traversing all nodes of the graph, calling successors() on them and saving all nodes with no successor. This however is terribly inefficient, especially since the graph is obviously considerably larger and more complex in my actual project. I was hoping for a simple and efficient method such as G.out_nodes() or something similar that is keeping track of the output nodes when the graph is edited, though I seem to be unable to find it. However since determining output and input nodes in a directed graph is no uncommon task am I of the opinion that I am missing something. I was hoping that you might be able to help me. Thank you very much.

Body:
Once you have your graph you could iterate and get the nodes with out_degree equal to 0.

output_nodes = [u for u, deg in g.out_degree() if not deg]

However, you could get them directly when building your graph, indeed you could remove from the nodes u if (u,v) is an arc. The remaining will be output nodes.

Another possibility is to use another way to represent your graph according to size/most common operations to be applied.


问:
How to hash sha256 many times in python
I want to hash my password many times but it's hard to repeat codes many times depends on exponent.

So, for example in this code for exponent 2 and base 3:

3**2= 9

So I need to hash my password nine times!

I scanned all the web to find any code for help in Python but all found in C language.

Is there an easy way to hash my password many times in
Python with hashlib.sha356 not pbkdf2_hmac?

Here is code for example:

Hello World!

Result:

c079473ced8ca65d5ce59cabf451ab7a513db97ab4d2266b9cb0c4d13383fb81

```<code>from hashlib import sha256

pw = input('Enter Password: ')
h1 = sha256(pw.encode('utf-8')).digest()
h2 = sha256(h1).digest()
h3 = sha256(h2).digest()
h4 = sha256(h3).digest()
h5 = sha256(h4).digest()
h6 = sha256(h5).digest()
h7 = sha256(h6).digest()
h8 = sha256(h7).digest()
h9 = sha256(h8).hexdigest()
print(h9)
</code>```

答:
from hashlib import sha256

pw = input('Enter Password: ')
h = sha256(pw.encode('utf-8')).digest()

N = 10
for i in range(N):
    if i != N-1:
        h = sha256(h).digest()
    else:
        h = sha256(h).hexdigest()

print(h)
```

Title: How to hash sha256 many times in python

Body:
I want to hash my password many times but it's hard to repeat codes many times depends on exponent.

So, for example in this code for exponent 2 and base 3:

3**2= 9

So I need to hash my password nine times!

I scanned all the web to find any code for help in Python but all found in C language.

Is there an easy way to hash my password many times in
Python with hashlib.sha356 not pbkdf2_hmac?

Here is code for example:

Hello World!

Result:

c079473ced8ca65d5ce59cabf451ab7a513db97ab4d2266b9cb0c4d13383fb81

from hashlib import sha256

pw = input('Enter Password: ')
h1 = sha256(pw.encode('utf-8')).digest()
h2 = sha256(h1).digest()
h3 = sha256(h2).digest()
h4 = sha256(h3).digest()
h5 = sha256(h4).digest()
h6 = sha256(h5).digest()
h7 = sha256(h6).digest()
h8 = sha256(h7).digest()
h9 = sha256(h8).hexdigest()
print(h9)


问:
C++ Classes: Christian Holiday Calculator
Basically, I'm trying to complete this exam-style question for exam practice. I know how to do everything but the last question, to do with classes. I kinda get them, but don't know how to apply it to the question. Could anybody give me some starting points or tips (or even possible answers) to how I would go about creating a C++ class? Any help is much appreciated. The question is below. Apologies about how long it is.

In 1800 the mathematician Carl Friedrich Gauss presented an algorithm for calculating the
date of the Easter holiday in the new Gregorian calendar (introduced in the British Empire in
the year 1752). For this a number of expressions need to be evaluated:
Two terms M and N, which for a given year y hold the values:

```<code>year      M N
1700-1799 23 3
1800-1899 23 4
1900-2099 24 5
2100-2199 24 6
The expressions are:
a = y mod 19
b = y mod 4
c = y mod 7
d = (19a + M) mod 30
e = (2b + 4c + 6d + N) mod 7
</code>```

If 22+d+e is smaller than 32 than this sum is the day of the Easter holiday in March.
Otherwise d+e-9 is the day of Easter in April unless:
- the result is the 26th April, in which case Easter is on the 19th April instead
- the result is the 25th April, in which case Easter is on the 18th of April if d is 28 and
a is greater than 10

a) Implement a C/C++ function that given a year as parameter will
print out the date for the Easter holiday. (10 marks)
Other Christian holidays can be calculated from the date of Easter:
Good Friday is the Friday before Easter Sunday.
Palm Sunday is the Sunday before Easter Sunday.
Whit Sunday is 7 weeks after Easter Sunday.
Ascension day is 10 days before Whit Sunday.
Note: April and June are 30 days long, whereas March and May are 31 days long.

b) Design/describe algorithms for identifying the date for the Christian
holidays "Good Friday", "Palm Sunday", "Ascension" and "Whit
Sunday". (no source code is required for this answer) (15 Marks)

The terms M and N in the Easter calculation algorithm described by Gauss can also
be calculated using the following expressions:

```<code>k = floor(y/100)
p = floor((13 + 8k)/25)
q = floor(k/4)
M = (15 − p + k − q) mod 30
N = (4 + k − q) mod 7
</code>```

The floor function rounds down a value – in the maths library math.h this is
available as a C function with the prototype double floor(double);

c) Produce a C++ class to implement a Christian Holiday calculator. It
should have private attributes (member variables) representing the
day, month and year of the date and a private method for
calculating the terms M and N. The default constructor should set
all attributes to 0. It should be possible to change the year using a
set() method and to retrieve day and month using get() methods.
The class should also contain compute methods for the different
holidays – example: computeEaster().

答:
So, you are stuck on creating a class. Either you don't know how to create a class at all, or you don't know how to create this specific class.

To create a class at all, use the class keyword: class { int i; };. If you have not yet created any classes in C++, then you may need to retake this or another C++ programming class.

If your problem, instead, is that you don't understand how to translate your professor's class design into C++ code, then you are not nearly as alone as you feel. Translating from ambiguous English design statements to concrete C++ programs is difficult, and is the reason we get paid the big bucks.

Let's go through it step by step.

Produce a C++ class to implement a Christian Holiday calculator.

That sounds easy enough, doesn't it?

```<code>class ChristianHolidayCalculator {
};
</code>```

There, that step is done!.

It should have private attributes (member variables) representing the day, month and year of the date

Do you know what attributes or member variables are? Do you need to check the index of your textbook? Go ahead, I'll wait. ... Oh, you're back! You must have seen that member variables are a collection of variables which are scoped by the class declaration and which spring into existence (as a group) everytime an object of that class is created.

```<code>class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
};
</code>```

Oh, you thought I would name them "year", "month", and "day"? No, that's your homework, not mine. Since you told us that you know how to do the math, I'll leave the specifics to you.

and a private method for calculating the terms M and N.

There are two more vocabulary words: method and private. Go review your course material for those.

You surely found that a method is a function inside the class scope. Methods are special in that they are invoked only in relation to objects of the class at hand.

As for "private", well, I'll leave that to you. Surely you learned something about classes this year?

```<code>class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
    void GuitarTune() {
      // Code to tighten strings goes here.
    }
};
</code>```

Since this method has to compute M and N, you'll need someplace to store the results. Hmm, maybe you need more member variables?

Finally, your teacher mentioned set(), get() and compute() methods. This is his shorthand way of telling you which public methods to create. He probably doesn't mean literally int get() { ... }. He probably means that you need to create a group of methods, all similar in name and in design:

```<code>class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
    void GuitarTune() {
      // Code to tighten strings goes here.
    }
    int getRed() { /* return red value */ }
    int getGreen() { /* return green value */ }
    int getBlue() { /* return blue value */ }
    void setRed(int newRed) { /* assign red value */ }
    void setGreen(int newGreen) { /* guess */ }
    ... calculateEaster() ... { ... }
};
</code>```

There is how you start to create the class. I hope this gives the push you need to get started. Good luck on your exams.

Body:
Basically, I'm trying to complete this exam-style question for exam practice. I know how to do everything but the last question, to do with classes. I kinda get them, but don't know how to apply it to the question. Could anybody give me some starting points or tips (or even possible answers) to how I would go about creating a C++ class? Any help is much appreciated. The question is below. Apologies about how long it is.

In 1800 the mathematician Carl Friedrich Gauss presented an algorithm for calculating the
date of the Easter holiday in the new Gregorian calendar (introduced in the British Empire in
the year 1752). For this a number of expressions need to be evaluated:
Two terms M and N, which for a given year y hold the values:

year      M N
1700-1799 23 3
1800-1899 23 4
1900-2099 24 5
2100-2199 24 6
The expressions are:
a = y mod 19
b = y mod 4
c = y mod 7
d = (19a + M) mod 30
e = (2b + 4c + 6d + N) mod 7

If 22+d+e is smaller than 32 than this sum is the day of the Easter holiday in March.
Otherwise d+e-9 is the day of Easter in April unless:
- the result is the 26th April, in which case Easter is on the 19th April instead
- the result is the 25th April, in which case Easter is on the 18th of April if d is 28 and
a is greater than 10

a) Implement a C/C++ function that given a year as parameter will
print out the date for the Easter holiday. (10 marks)
Other Christian holidays can be calculated from the date of Easter:
Good Friday is the Friday before Easter Sunday.
Palm Sunday is the Sunday before Easter Sunday.
Whit Sunday is 7 weeks after Easter Sunday.
Ascension day is 10 days before Whit Sunday.
Note: April and June are 30 days long, whereas March and May are 31 days long.

b) Design/describe algorithms for identifying the date for the Christian
holidays "Good Friday", "Palm Sunday", "Ascension" and "Whit
Sunday". (no source code is required for this answer) (15 Marks)

The terms M and N in the Easter calculation algorithm described by Gauss can also
be calculated using the following expressions:

k = floor(y/100)
p = floor((13 + 8k)/25)
q = floor(k/4)
M = (15 − p + k − q) mod 30
N = (4 + k − q) mod 7

The floor function rounds down a value – in the maths library math.h this is
available as a C function with the prototype double floor(double);

c) Produce a C++ class to implement a Christian Holiday calculator. It
should have private attributes (member variables) representing the
day, month and year of the date and a private method for
calculating the terms M and N. The default constructor should set
all attributes to 0. It should be possible to change the year using a
set() method and to retrieve day and month using get() methods.
The class should also contain compute methods for the different
holidays – example: computeEaster().

Body:
So, you are stuck on creating a class. Either you don't know how to create a class at all, or you don't know how to create this specific class.

To create a class at all, use the class keyword: class { int i; };. If you have not yet created any classes in C++, then you may need to retake this or another C++ programming class.

If your problem, instead, is that you don't understand how to translate your professor's class design into C++ code, then you are not nearly as alone as you feel. Translating from ambiguous English design statements to concrete C++ programs is difficult, and is the reason we get paid the big bucks.

Let's go through it step by step.

Produce a C++ class to implement a Christian Holiday calculator.

That sounds easy enough, doesn't it?

class ChristianHolidayCalculator {
};

There, that step is done!.

It should have private attributes (member variables) representing the day, month and year of the date

Do you know what attributes or member variables are? Do you need to check the index of your textbook? Go ahead, I'll wait. ... Oh, you're back! You must have seen that member variables are a collection of variables which are scoped by the class declaration and which spring into existence (as a group) everytime an object of that class is created.

class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
};

Oh, you thought I would name them "year", "month", and "day"? No, that's your homework, not mine. Since you told us that you know how to do the math, I'll leave the specifics to you.

and a private method for calculating the terms M and N.

There are two more vocabulary words: method and private. Go review your course material for those.

You surely found that a method is a function inside the class scope. Methods are special in that they are invoked only in relation to objects of the class at hand.

As for "private", well, I'll leave that to you. Surely you learned something about classes this year?

class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
    void GuitarTune() {
      // Code to tighten strings goes here.
    }
};

Since this method has to compute M and N, you'll need someplace to store the results. Hmm, maybe you need more member variables?

Finally, your teacher mentioned set(), get() and compute() methods. This is his shorthand way of telling you which public methods to create. He probably doesn't mean literally int get() { ... }. He probably means that you need to create a group of methods, all similar in name and in design:

class ChristianHolidayCalculator {
    double width;
    double height;
    double depth;
    void GuitarTune() {
      // Code to tighten strings goes here.
    }
    int getRed() { /* return red value */ }
    int getGreen() { /* return green value */ }
    int getBlue() { /* return blue value */ }
    void setRed(int newRed) { /* assign red value */ }
    void setGreen(int newGreen) { /* guess */ }
    ... calculateEaster() ... { ... }
};

There is how you start to create the class. I hope this gives the push you need to get started. Good luck on your exams.

ContentLicense: CC BY-SA 3.0


问:
Formatting Array into Lat Lng Array for Google Map API Format in Javascript
How to format this array:

```<code>array = ["37.772, -122.214", "-27.467, 153.027"]
</code>```

into Lat/Lng for google map API that look like this:

```<code>flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: -27.467, lng: 153.027}];
</code>```

I'm trying this code:

```<code>let latLngArray = [];
for (let i = 0; i < array.length; i++) {
  const gData = new google.maps.LatLng(array[i][0], array[i][1]);
  latLngArray.push(gData);
}
</code>```

but it resulting lat lng without value:

答:
Another approach with slice could be:

const array = ["37.772, -122.214", "-27.467, 153.027"];

let flightPlanCoordinates = array.map(coor => ({lat: +coor.slice(0, coor.indexOf(',')),
                                         lng: +coor.slice(coor.indexOf(',') +1)}));

console.log(flightPlanCoordinates)```

Body:
How to format this array:

array = ["37.772, -122.214", "-27.467, 153.027"]

into Lat/Lng for google map API that look like this:

flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: -27.467, lng: 153.027}];

I'm trying this code:

let latLngArray = [];
for (let i = 0; i < array.length; i++) {
  const gData = new google.maps.LatLng(array[i][0], array[i][1]);
  latLngArray.push(gData);
}

but it resulting lat lng without value:


问:
CSS Circle DIV with a background not in scale 1:1
I want to make a linguage picker for my Hugo website and I find this useful library: https://www.phoca.cz/cssflags/ that gives in pure svg and css all the flag of the world
Now I create my own subset of flag and in the css file each flag has something like that:

```<code>/* europe */
.eu {
 background: url('data:image/svg+xml;base64, BUNCH OF DATA);
 width: 150%;
 height: 100%;
 background-size: 100% 100%;
}
</code>```

The width and height could be not the same...so some flag has 150% as width and 100% for height and someone else different. What I want to achieve is perfect circle div of about 30px of diameter with at the center the flag. I try this code:

```<code><div class="u-language">
            <a href="#" id="language-bar-invoker" class="u-icon-v1>
              <i class="eu g-rounded-20"></i>
            </a>
</div>
</code>```

And the class g-rounded has this code:

```<code>.g-rounded-20 {
    border-radius: 20px!important;
}
</code>```

but the result is a oval and not a circle! How can I solve that?

Thanks

答:
To achieve a perfect circle of 30px diameter with the flag at the center:

#language-bar-invoker i {
  display: inline-block;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #eee;
  background-position: center center;
  background-size: 150%;
}

.eu {
  background-image: url(https://c.tadst.com/gfx/750w/flag-day.jpg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="u-language">

      <i class="eu"></i>

</div></code>```

To achieve a circle, make sure the height and width are equal. Remember, height can only be set on block and inline-block elements. Then set border-radius to 50%.

Body:
I want to make a linguage picker for my Hugo website and I find this useful library: https://www.phoca.cz/cssflags/ that gives in pure svg and css all the flag of the world
Now I create my own subset of flag and in the css file each flag has something like that:

/* europe */
.eu {
 background: url('data:image/svg+xml;base64, BUNCH OF DATA);
 width: 150%;
 height: 100%;
 background-size: 100% 100%;
}

The width and height could be not the same...so some flag has 150% as width and 100% for height and someone else different. What I want to achieve is perfect circle div of about 30px of diameter with at the center the flag. I try this code:

And the class g-rounded has this code:

.g-rounded-20 {
    border-radius: 20px!important;
}

but the result is a oval and not a circle! How can I solve that?

Thanks

Body:
To achieve a perfect circle of 30px diameter with the flag at the center:

#language-bar-invoker i {
  display: inline-block;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #eee;
  background-position: center center;
  background-size: 150%;
}

.eu {
  background-image: url(https://c.tadst.com/gfx/750w/flag-day.jpg);
}

<div class="u-language">
    <a href="#" id="language-bar-invoker" class="u-icon-v1">
      <i class="eu"></i>
    </a>
</div>

To achieve a circle, make sure the height and width are equal. Remember, height can only be set on block and inline-block elements. Then set border-radius to 50%.


问:
Object code generation for new RISCV instruction emitted by LLVM backend
From https://github.com/riscv/riscv-llvm,

Using the llvm-riscv is fairly simple to build a full executable
  however you need riscv64-unknown-*-gcc to do the assembling and
  linking. An example of compiling hello world:

```<code>$ clang -target riscv64 -mriscv=RV64IAMFD -S hello.c -o hello.S
$ riscv64-unknown-elf-gcc -o hello.riscv hello.S
</code>```

My question is: if I change the LLVM backend and get it to emit a new instruction in the hello.S file, how will riscv64-unknown-elf-gcc know how to convert it into object code? Do I also need to make changes in riscv64-unknown-elf-gcc so that it knows the format of the new instruction?

答: riscv64-unknown-elf-gcc calls as, i.e. usually GNU as from the binutils to assemble assembly code (i.e. hello.S in your snippet) into executable machine code. Thus you would have to modify the binutils if you want to assemble a new instruction.

Body:
From https://github.com/riscv/riscv-llvm,

Using the llvm-riscv is fairly simple to build a full executable
  however you need riscv64-unknown-*-gcc to do the assembling and
  linking. An example of compiling hello world:

$ clang -target riscv64 -mriscv=RV64IAMFD -S hello.c -o hello.S
$ riscv64-unknown-elf-gcc -o hello.riscv hello.S

My question is: if I change the LLVM backend and get it to emit a new instruction in the hello.S file, how will riscv64-unknown-elf-gcc know how to convert it into object code? Do I also need to make changes in riscv64-unknown-elf-gcc so that it knows the format of the new instruction?


问:
Numpy where with indices along with values
I have an array

```<code>import numpy as np
t = np.array([[1,2,3],
 [2,3,4],
 [5,6,7],
 [8,9,1]])
</code>```

I need array indices where value is greater than 5 along with the actual values. Like below:

```<code>[[(2, 1),6], [(2, 2),7], [(3, 0),8], [(3, 1),9]]
</code>```

I tried below:

```<code>result = np.where(t>5)
list(zip(result[0], result[1]))
</code>```

This gives me only the indices

```<code>[(2, 1), (2, 2), (3, 0), (3, 1)]
</code>```

Any pointer?

Body:
I have an array

import numpy as np
t = np.array([[1,2,3],
 [2,3,4],
 [5,6,7],
 [8,9,1]])

I need array indices where value is greater than 5 along with the actual values. Like below:

[[(2, 1),6], [(2, 2),7], [(3, 0),8], [(3, 1),9]]

I tried below:

result = np.where(t>5)
list(zip(result[0], result[1]))

This gives me only the indices

[(2, 1), (2, 2), (3, 0), (3, 1)]

Any pointer?

Body:
just incase its a pandas dataframe, since pandas is tagged, you can also try;

#df  = pd.DataFrame(t)
[*df.where(df.gt(5)).stack().to_dict().items()]

Output:

[((2, 1), 6.0), ((2, 2), 7.0), ((3, 0), 8.0), ((3, 1), 9.0)]

Or;

[*map(list,df.where(df.gt(5)).stack().to_dict().items())]

Output:

[[(2, 1), 6.0], [(2, 2), 7.0], [(3, 0), 8.0], [(3, 1), 9.0]]


问:
How to use JSON_VALUE with a variable
I have a statement I'm trying to construct in Oracle 18c.  The following line works fine:

```<code>Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[1].type')
  into l_temp_var
  from dual;
</code>```

However, I have to vary the second index by a variable.  The second index currently contains [1].  I  tried using [i] defined as a numeric or varchar, but that doesn't work.  How can I construct a Select JSON_VALUE statement so that it uses a variable?
Thanks for looking at this.

答:
I couldn't make the concatenation work.  I tried another approach.  I had to put the "type" and "identifier" into a Json table.

```<code>    --Obtain the NVP values of "industryIdentifiers" e.g. ISBN_10, ISBN_13 .
    For rowz in
        (select *
            from json_table(l_resp, '$.items[0].volumeInfo.industryIdentifiers[*]'
                            columns (ii_type varchar2(512) path '$.type',
                                     ii_identifier varchar2(512) path '$.identifier'
                                     )
                            ) j_ii_tab
        )
    Loop
/*
    If rowz.ii_type = 'ISBN_10' Then
        :P133_ISBN_10 := rowz.ii_identifier;
    Elsif rowz.ii_type = 'ISBN_13' Then
        :P133_ISBN_13 := rowz.ii_identifier;
    End If ;
*/
    dbms_output.put_line('ii_type: ' || rowz.ii_type);
    dbms_output.put_line('ii_identifier: ' || rowz.ii_identifier);
    End Loop rowz;
</code>```

It might be helpful to see the Json data at: https://www.googleapis.com/books/v1/volumes?q=isbn:9781484204856

Title: How to use JSON_VALUE with a variable

Body:
I have a statement I'm trying to construct in Oracle 18c.  The following line works fine:

Select JSON_VALUE(l_resp, '$.items[0].volumeInfo.industryIdentifiers[1].type')
  into l_temp_var
  from dual;

However, I have to vary the second index by a variable.  The second index currently contains [1].  I  tried using [i] defined as a numeric or varchar, but that doesn't work.  How can I construct a Select JSON_VALUE statement so that it uses a variable?
Thanks for looking at this.

Body:
I couldn't make the concatenation work.  I tried another approach.  I had to put the "type" and "identifier" into a Json table.

    --Obtain the NVP values of "industryIdentifiers" e.g. ISBN_10, ISBN_13 .
    For rowz in
        (select *
            from json_table(l_resp, '$.items[0].volumeInfo.industryIdentifiers[*]'
                            columns (ii_type varchar2(512) path '$.type',
                                     ii_identifier varchar2(512) path '$.identifier'
                                     )
                            ) j_ii_tab
        )
    Loop
/*
    If rowz.ii_type = 'ISBN_10' Then
        :P133_ISBN_10 := rowz.ii_identifier;
    Elsif rowz.ii_type = 'ISBN_13' Then
        :P133_ISBN_13 := rowz.ii_identifier;
    End If ;
*/
    dbms_output.put_line('ii_type: ' || rowz.ii_type);
    dbms_output.put_line('ii_identifier: ' || rowz.ii_identifier);
    End Loop rowz;

It might be helpful to see the Json data at: https://www.googleapis.com/books/v1/volumes?q=isbn:9781484204856


问:
Creating List of MonoBehaviours on an object
I have an object in the scene that has a monobehaviour attached. This monobehaviour has a public List. I want to be able to drag other monobheaviours from the project window to the inspector to fill this list so that this object can then add these monobehaviours to itself in the future to change its actions. The list shows up, but I cannot drag and drop them from the project window to the inspector - why is this? Thanks</p>

答:
If I understood correctly you should do something like this:

```<code>List<NameOfTheMonobehaviourScript> list = new List<NameOfTheMonobehaviourScript>();
</code>```

And after that just drag the gameobjects with the scripts to the list, Unity will automatically reference the script on the gameobject instead of the gameobject itself.

Hope that this is what you meant!

Body:
If I understood correctly you should do something like this:

List<NameOfTheMonobehaviourScript> list = new List<NameOfTheMonobehaviourScript>();

And after that just drag the gameobjects with the scripts to the list, Unity will automatically reference the script on the gameobject instead of the gameobject itself.

Hope that this is what you meant!


问:
how to insert a basic span tag with a unique classname with quill
This is my existing draft:
- https://codepen.io/inspiraller/pen/ExjKPNE

```<code>   let Embed = Quill.import('blots/embed');

    class SpanEmbed extends Embed {
      static blotName = 'spanEmbed';
      static tagName = 'span';
      static className = "spanEmbed"
      static create(variable) {
        const node = super.create();
        node.classList.add('myclass');
        node.innerText = variable.value;
        return node;
      }
    }

    SpanEmbed.blotName = 'spanEmbed';
    SpanEmbed.tagName = 'span';
    SpanEmbed.className='myclass';

    //############################################

    Quill.register(SpanEmbed);

    var quill = new Quill('#editor-container');

    $('#spanEmbed-button').click(function() {
      quill.format('spanEmbed', true);
    });
</code>```

The problem is when I click spanEmbed, it creates undefined.

I just want it to create:

```<code><span className="myclass"></span>
</code>```

Currently I am getting an error in the console:

error
  TypeError: wrapper.appendChild is not a function

答:
I realised I didn't insert properly. It's now fixed:

   let Embed = Quill.import('blots/embed');

    class SpanEmbed extends Embed {
      static create(value) {
        const node = super.create();
        node.classList.add('myspan');
        node.innerText = value;
        return node;
      }
    }

    SpanEmbed.blotName = 'spanEmbed';
    SpanEmbed.tagName = 'span';
    SpanEmbed.className='myclass';

    //############################################

    Quill.register(SpanEmbed);

    var quill = new Quill('#editor-container');

    $('#spanEmbed-button').click(function() {
      var range = quill.getSelection();
      if (range) {
        quill.insertEmbed(range.index, 'spanEmbed', 'this text');
      }
    });
```

Body:
This is my existing draft:
- https://codepen.io/inspiraller/pen/ExjKPNE

   let Embed = Quill.import('blots/embed');

    class SpanEmbed extends Embed {
      static blotName = 'spanEmbed';
      static tagName = 'span';
      static className = "spanEmbed"
      static create(variable) {
        const node = super.create();
        node.classList.add('myclass');
        node.innerText = variable.value;
        return node;
      }
    }

    SpanEmbed.blotName = 'spanEmbed';
    SpanEmbed.tagName = 'span';
    SpanEmbed.className='myclass';

    //############################################

    Quill.register(SpanEmbed);

    var quill = new Quill('#editor-container');

    $('#spanEmbed-button').click(function() {
      quill.format('spanEmbed', true);
    });

The problem is when I click spanEmbed, it creates undefined.

I just want it to create:

Currently I am getting an error in the console:

error
  TypeError: wrapper.appendChild is not a function


问:
How can I force a TD with no content to render its border?
The TD has a DIV inside which I removed using jQuery's fadeOut function, but when it finishes the border disappears too.

I want to avoid that, is there any way other than adding a " " (which causes it to be ugly)?

EDIT: I am using Internet Explorer (6 and 7)

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Graeme Perrow

Body: <td style="font-size: 1pt">&nbsp;<td>

OwnerDisplayName: finnw


问:
What's the best way to save trivial user states (e.g. dismissed welcome msg) in database?
Should I use (create) a column for every new state? Or one field with a bunch of comma separated states (alternatively a json obj)? Any suggestions welcome.

UPDATE

First let me day thanks for the answers. I just want to clear up, what options I see:

Put a column for every state in the user row (initial plan) / Can get messy with lots of states (in the future)

Put one column with json/xml data in the user row / Easy to maintain (no db change required), but doesn't feel right

Have a dedicated states table (thx lhiles)/ Sounds cool, how would this table look like?

I'm looking for pros/cons of the different implementations. Again: Thanks!

答:
My preferred method is to create a dedicated table for user settings. Each state/setting corresponds to a column within that table. As your project grows additional columns can be added without cluttering your apps core data.

Another route, if you feel that there will be too many settings to devote 1 setting per column, would be to store the settings as XML (or json as you mentioned) data within SQL. This would allow you to derive any type of state format you wanted, however, it puts more work on the programmer to parse, validate, and persist those settings.


问:
non-type template parameter of user-defined type
I'm trying to define a template-class that has a non-type template parameter of a user-defined type. Unfortunately, without success so far. The real code is a bit too lengthy, but a simplified example looks like this:

```<code>#include <iostream>

template <class T>
class Maybe {
    bool is_ = false;
    T value_;

  public:
    constexpr Maybe() = default;
    constexpr Maybe(T value) : is_(true), value_(value) {}

    constexpr bool is() const { return is_; }
};

template <Maybe<int> parm>
struct Test {
    void say() const {
        std::cout << "parm is " << (parm.is() ? "set" : "not set") << ".\n";
    }
};

int main() {
    Test<Maybe<int>{}> not_set;
    Test<Maybe<int>(2)> is_set;

    not_set.say();
    is_set.say();
}
</code>```

When I try to compile this code (with Clang 3.4) I get the following error message:

```<code>test.cc:15:22: error: a non-type template parameter cannot have type
      'Maybe<int>'
template <Maybe<int> parm>
                     ^
test.cc:23:10: error: value of type 'Maybe<int>' is not implicitly
      convertible to 'int'
    Test<Maybe<int>{}> not_set;
         ^~~~~~~~~~~~
test.cc:24:10: error: value of type 'Maybe<int>' is not implicitly
      convertible to 'int'
    Test<Maybe<int>(2)> is_set;
         ^~~~~~~~~~~~~
3 errors generated.
</code>```

Now, I know that a non-type template parameter has to fulfill some conditions. However, I thought that being constexpr would be sufficient. Or can it really only be one of the built-in integral types?

Is there a way to pass non-type template parameters of my own user-defined type?

答:
In C++20, this is possible using structural literal class types:

#include <iostream>

struct NullOptT {} NullOpt;

/**
 * Literal class type.
 *
 * Represents an optionally provided `int`.
 */
struct OptionalInt {
    constexpr OptionalInt(NullOptT) {}
    constexpr OptionalInt(int value): has_value(true), value(value) {}

    const bool has_value = false;
    const uint32_t value {};
};

/**
 * Prints whether or not a value was provided for "maybe" WITHOUT branching :)
 */
template<OptionalInt maybe>
void Print() {
    if constexpr(maybe.has_value) {
        std::cout << "Value is: " << maybe.value << std::endl;
    } else {
        std::cout << "No value." << std::endl;
    }
}

// Note: implicit conversions are at play!
int main()
{
    Print<123>();     // Prints "Value is: 123"
    Print<NullOpt>(); // Prints "No value."
}
```

I wrote up a blog post with more detail on the usage and restrictions of class literal NTTPs here: Literal Classes as Non-type Template Parameters in C++20.

Body:
I'm trying to define a template-class that has a non-type template parameter of a user-defined type. Unfortunately, without success so far. The real code is a bit too lengthy, but a simplified example looks like this:

#include <iostream>

template <class T>
class Maybe {
    bool is_ = false;
    T value_;

  public:
    constexpr Maybe() = default;
    constexpr Maybe(T value) : is_(true), value_(value) {}

    constexpr bool is() const { return is_; }
};

template <Maybe<int> parm>
struct Test {
    void say() const {
        std::cout << "parm is " << (parm.is() ? "set" : "not set") << ".\n";
    }
};

int main() {
    Test<Maybe<int>{}> not_set;
    Test<Maybe<int>(2)> is_set;

    not_set.say();
    is_set.say();
}

When I try to compile this code (with Clang 3.4) I get the following error message:

test.cc:15:22: error: a non-type template parameter cannot have type
      'Maybe<int>'
template <Maybe<int> parm>
                     ^
test.cc:23:10: error: value of type 'Maybe<int>' is not implicitly
      convertible to 'int'
    Test<Maybe<int>{}> not_set;
         ^~~~~~~~~~~~
test.cc:24:10: error: value of type 'Maybe<int>' is not implicitly
      convertible to 'int'
    Test<Maybe<int>(2)> is_set;
         ^~~~~~~~~~~~~
3 errors generated.

Now, I know that a non-type template parameter has to fulfill some conditions. However, I thought that being constexpr would be sufficient. Or can it really only be one of the built-in integral types?

Is there a way to pass non-type template parameters of my own user-defined type?

Body:
In C++20, this is possible using structural literal class types:

#include <iostream>

struct NullOptT {} NullOpt;

/**
 * Literal class type.
 *
 * Represents an optionally provided `int`.
 */
struct OptionalInt {
    constexpr OptionalInt(NullOptT) {}
    constexpr OptionalInt(int value): has_value(true), value(value) {}

    const bool has_value = false;
    const uint32_t value {};
};

/**
 * Prints whether or not a value was provided for "maybe" WITHOUT branching :)
 */
template<OptionalInt maybe>
void Print() {
    if constexpr(maybe.has_value) {
        std::cout << "Value is: " << maybe.value << std::endl;
    } else {
        std::cout << "No value." << std::endl;
    }
}

// Note: implicit conversions are at play!
int main()
{
    Print<123>();     // Prints "Value is: 123"
    Print<NullOpt>(); // Prints "No value."
}

I wrote up a blog post with more detail on the usage and restrictions of class literal NTTPs here: Literal Classes as Non-type Template Parameters in C++20.


问:
Linux shell su -c 'sed' command
```<code>$ sudo su - root -c 'sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config'
</code>```

after run the command,it always displays

```<code>sed: -e expression #1, char 2: extra characters after command
</code>```

and

```<code>$ sudo su - root -c "sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config"
</code>```

will display

```<code>sed: -e expression #1, char 20: unterminated address regex
</code>```

how should I modify it?

答:
Single quotes don't nest. Since you have single quotes in the sed command, use double quotes for the outer set. Then make sure to escape \$a so it's not interpreted as a shell variable named $a.

```<code>sudo su - root -c "sed -i '\$a\\PermitRootLogin yes' /etc/ssh/sshd_config"
</code>```

You can avoid the quoting problems by getting rid of the whole su - business, though. sudo already gives you root access, no need to combine it with su. Once you do that you no longer need two sets of quotes and the problem disappears entirely.

```<code>sudo sed -i '$a\PermitRootLogin yes' /etc/ssh/sshd_config
</code>```

By the way, sed is a bit heavy handed if all you want to do is append a line of text. It will copy the original file to a temporary file, add the line to the copy, and then replace the original with the copy. You can avoid this overhead by using >> or tee -a, either of which will append the line in place without all the copying.

```<code>sudo sh -c 'echo "PermitRootLogin yes" >> /etc/ssh/sshd_config'
</code>```

```<code>sudo tee -a /etc/ssh/sshd_config <<< 'PermitRootLogin yes' > /dev/null
</code>```

Title: Linux shell su -c 'sed' command

Body:
$ sudo su - root -c 'sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config'

after run the command,it always displays

sed: -e expression #1, char 2: extra characters after command

and

$ sudo su - root -c "sed -i '$a\PermitRootLogin yes' etc/ssh/sshd_config"

will display

sed: -e expression #1, char 20: unterminated address regex

how should I modify it?

Body:
Single quotes don't nest. Since you have single quotes in the sed command, use double quotes for the outer set. Then make sure to escape \$a so it's not interpreted as a shell variable named $a.

sudo su - root -c "sed -i '\$a\\PermitRootLogin yes' /etc/ssh/sshd_config"

You can avoid the quoting problems by getting rid of the whole su - business, though. sudo already gives you root access, no need to combine it with su. Once you do that you no longer need two sets of quotes and the problem disappears entirely.

sudo sed -i '$a\PermitRootLogin yes' /etc/ssh/sshd_config

By the way, sed is a bit heavy handed if all you want to do is append a line of text. It will copy the original file to a temporary file, add the line to the copy, and then replace the original with the copy. You can avoid this overhead by using >> or tee -a, either of which will append the line in place without all the copying.

sudo sh -c 'echo "PermitRootLogin yes" >> /etc/ssh/sshd_config'

sudo tee -a /etc/ssh/sshd_config <<< 'PermitRootLogin yes' > /dev/null


问:
Quickly insert 24 million rows into Oracle
Which is the best way to insert 24 million rows into a table in Oracle (from the same database table)?

Target table has unique and not null indexes and it is partitioned.

答:
The fastest way to insert a large number of rows is to use parallelism and direct-path writes:

```<code>alter session enable parallel dml;

insert /*+ append parallel */ into test1
select -a, b, c from test;

commit;
</code>```

(You might be able to simply use a negative sign to avoid primary key violations.  IDs are almost always positive, but there's usually not a rule preventing them from being negative.)

This code isn't merely a FAST=TRUE flag.  There are many important caveats you must understand first.

Parallelism requires Enterprise Edition (the most expensive version), not-terrible hardware (more than a single core and a single disk), and a sane configuration (if a DBA set the parameter parallel_max_servers = 1 then there will be no parallel threads available).  And parallelism can often "steal" from other processes - you might need 10x the system resources for only 5x performance improvement.  And getting the right degree of parallelism can be tricky.

Direct-path writes directly to the data files and and avoid writing REDO and UNDO (extra data used for recovery and consistency).  The trade-off here is that the statement will lock the entire table - nobody else will be able to write to it at the same time.  And the table will not be recoverable until the next full backup.  And there are lots of things that can block direct-path writes, like TRIGGERS, certain foreign key relationships, etc.

Check the execution plan carefully to ensure you're getting all the features.  You want to see "LOAD AS SELECT" instead of "LOAD CONVENTIONAL" to ensure you're getting direct-path writes.  And you'll want to see "PX" operations to ensure you're getting parallelism.  You'll want a "PX" above both the reading and the writing part of the operation.  Check the Note section carefully, it may tell you why you're not getting what you ask for.

```<code>explain plan for
insert /*+ append parallel */ into test1
select * from test2;

select * from table(dbms_xplan.display);

Plan hash value: 1209398148

----------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                          | Name     | Rows  | Bytes | Cost (%CPU)| Time     |    TQ  |IN-OUT| PQ Distrib |
----------------------------------------------------------------------------------------------------------------------------
|   0 | INSERT STATEMENT                   |          |     1 |    39 |     2   (0)| 00:00:01 |        |      |            |
|   1 |  PX COORDINATOR                    |          |       |       |            |          |        |      |            |
|   2 |   PX SEND QC (RANDOM)              | :TQ10000 |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | P->S | QC (RAND)  |
|   3 |    LOAD AS SELECT (HYBRID TSM/HWMB)| TEST1    |       |       |            |          |  Q1,00 | PCWP |            |
|   4 |     OPTIMIZER STATISTICS GATHERING |          |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWP |            |
|   5 |      PX BLOCK ITERATOR             |          |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWC |            |
|   6 |       TABLE ACCESS FULL            | TEST1    |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWP |            |
----------------------------------------------------------------------------------------------------------------------------

Note
-----
   - automatic DOP: Computed Degree of Parallelism is 2
</code>```

This can be a lot of work!  You might spend hours optimizing a single INSERT, and you might need to read the Oracle documentation to solve some problems.  But if you're patient and have the right configuration, it's possible to see huge improvements in INSERT performance.

Body:
The fastest way to insert a large number of rows is to use parallelism and direct-path writes:

alter session enable parallel dml;

insert /*+ append parallel */ into test1
select -a, b, c from test;

commit;

(You might be able to simply use a negative sign to avoid primary key violations.  IDs are almost always positive, but there's usually not a rule preventing them from being negative.)

This code isn't merely a FAST=TRUE flag.  There are many important caveats you must understand first.

Parallelism requires Enterprise Edition (the most expensive version), not-terrible hardware (more than a single core and a single disk), and a sane configuration (if a DBA set the parameter parallel_max_servers = 1 then there will be no parallel threads available).  And parallelism can often "steal" from other processes - you might need 10x the system resources for only 5x performance improvement.  And getting the right degree of parallelism can be tricky.

Direct-path writes directly to the data files and and avoid writing REDO and UNDO (extra data used for recovery and consistency).  The trade-off here is that the statement will lock the entire table - nobody else will be able to write to it at the same time.  And the table will not be recoverable until the next full backup.  And there are lots of things that can block direct-path writes, like TRIGGERS, certain foreign key relationships, etc.

Check the execution plan carefully to ensure you're getting all the features.  You want to see "LOAD AS SELECT" instead of "LOAD CONVENTIONAL" to ensure you're getting direct-path writes.  And you'll want to see "PX" operations to ensure you're getting parallelism.  You'll want a "PX" above both the reading and the writing part of the operation.  Check the Note section carefully, it may tell you why you're not getting what you ask for.

explain plan for
insert /*+ append parallel */ into test1
select * from test2;

select * from table(dbms_xplan.display);

Plan hash value: 1209398148

----------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                          | Name     | Rows  | Bytes | Cost (%CPU)| Time     |    TQ  |IN-OUT| PQ Distrib |
----------------------------------------------------------------------------------------------------------------------------
|   0 | INSERT STATEMENT                   |          |     1 |    39 |     2   (0)| 00:00:01 |        |      |            |
|   1 |  PX COORDINATOR                    |          |       |       |            |          |        |      |            |
|   2 |   PX SEND QC (RANDOM)              | :TQ10000 |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | P->S | QC (RAND)  |
|   3 |    LOAD AS SELECT (HYBRID TSM/HWMB)| TEST1    |       |       |            |          |  Q1,00 | PCWP |            |
|   4 |     OPTIMIZER STATISTICS GATHERING |          |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWP |            |
|   5 |      PX BLOCK ITERATOR             |          |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWC |            |
|   6 |       TABLE ACCESS FULL            | TEST1    |     1 |    39 |     2   (0)| 00:00:01 |  Q1,00 | PCWP |            |
----------------------------------------------------------------------------------------------------------------------------

Note
-----
   - automatic DOP: Computed Degree of Parallelism is 2

This can be a lot of work!  You might spend hours optimizing a single INSERT, and you might need to read the Oracle documentation to solve some problems.  But if you're patient and have the right configuration, it's possible to see huge improvements in INSERT performance.


问:
R replacing words in column by annotation dataframe
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!</p>

```<code>a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)
</code>```

答:
Here is another option with gsubfn

```<code>library(gsubfn)
data1$res <- gsubfn("\\w+", setNames(as.list(as.character(data2$c)),
             data2$b), as.character(data1$a))
data1
#                                a         res
#1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
#2                 ENSG00000185294       GeneC
#3                              NA          NA
</code>```

In base R, this can be also done by splitting the 'a' column with strsplit and then do match with a named vector created from 'b', 'c' columns of second dataset

```<code>is.na(data1$a) <- data1$a == "NA" # converting to real NA instead of character
i1 <- !is.na(data1$a)
# create named vector
v1 <- setNames(as.character(data2$c), data2$b)
data1$res[i1] <- sapply(strsplit(as.character(data1$a[i1]), ":"),
           function(x) paste(v1[x], collapse=":"))
</code>```

Body:
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!

a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)

Body:
Here is another option with gsubfn

library(gsubfn)
data1$res <- gsubfn("\\w+", setNames(as.list(as.character(data2$c)),
             data2$b), as.character(data1$a))
data1
#                                a         res
#1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
#2                 ENSG00000185294       GeneC
#3                              NA          NA

In base R, this can be also done by splitting the 'a' column with strsplit and then do match with a named vector created from 'b', 'c' columns of second dataset

is.na(data1$a) <- data1$a == "NA" # converting to real NA instead of character
i1 <- !is.na(data1$a)
# create named vector
v1 <- setNames(as.character(data2$c), data2$b)
data1$res[i1] <- sapply(strsplit(as.character(data1$a[i1]), ":"),
           function(x) paste(v1[x], collapse=":"))


问:
Winston - MaxListenersExceededWarning: Possible EventEmitter memory leak detected
Got below error in winston when using file logging with winston-daily-rotate-file package, code works well with winston console logging,

```<code>  MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at DailyRotateFile.addListener (events.js:272:10)
        at DailyRotateFile.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:217:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)
    (node:20805) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at DailyRotateFile.addListener (events.js:272:10)
        at DailyRotateFile.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:216:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)
    (node:20805) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 31 error listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at Console.addListener (events.js:272:10)
        at Console.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:217:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)
</code>```

Tried to set max listeners to infinity,

```<code>const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.setMaxListeners(Infinity);
</code>```

still facing same issue.

答:
Set handleExceptions: false as shown below

```<code>createLogger({
    level:  'info',
    transports: [
      new transports.Console({
        format: format.combine(
          format.colorize(),
          format.simple(),
          myFormat
      ),
        handleExceptions: false
      })
    ],
    format: logFormat(label)
  })
</code>```

Body:
Got below error in winston when using file logging with winston-daily-rotate-file package, code works well with winston console logging,

  MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at DailyRotateFile.addListener (events.js:272:10)
        at DailyRotateFile.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:217:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)
    (node:20805) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at DailyRotateFile.addListener (events.js:272:10)
        at DailyRotateFile.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:216:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)
    (node:20805) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 31 error listeners added. Use emitter.setMaxListeners() to increase limit
        at _addListener (events.js:256:17)
        at Console.addListener (events.js:272:10)
        at Console.once (events.js:301:8)
        at asyncForEach (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:217:17)
        at /home/ubuntumachine/Desktop/project/node_modules/async/internal/withoutIndex.js:9:16
        at eachOfArrayLike (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:65:9)
        at exports.default (/home/ubuntumachine/Desktop/project/node_modules/async/eachOf.js:9:5)
        at eachLimit (/home/ubuntumachine/Desktop/project/node_modules/async/forEach.js:80:24)
        at ExceptionHandler._uncaughtException (/home/ubuntumachine/Desktop/project/node_modules/winston/lib/winston/exception-handler.js:203:5)
        at process.emit (events.js:198:13)

Tried to set max listeners to infinity,

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.setMaxListeners(Infinity);

still facing same issue.

Body:
Set handleExceptions: false as shown below

createLogger({
    level:  'info',
    transports: [
      new transports.Console({
        format: format.combine(
          format.colorize(),
          format.simple(),
          myFormat
      ),
        handleExceptions: false
      })
    ],
    format: logFormat(label)
  })


问:
How to not only open a HTML file from python CGI script but also pass data like strings and JSON files to HTML script?
I've been trying to figure out how to do this for a while without using a framework (I can make this work with Flask for example) but I haven't found anything as of yet. I have two html scripts and a python cgi script. In essence I have the first html file wherein the user enters a string that I read into my python cgi script which in turn does a number of things to finally give me a bunch of strings and json file that I need to pass to another html file and be able to read them there as well.

So far the first half works, and I can open the second html with a redirect which is not elegant but nothing else has worked with the following code:

```<code>#!/Users/<username>/opt/anaconda3/bin//python
import pandas as pd
import numpy as np
import cgi
import cgitb
import sys
cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
protein_name = form.getvalue('protein_name')
####### function search_results takes in protein_name and gives me the data ###
####### I need to pass to the html file: results.html #########################

if ((search_results(protein_name)!="No protein entered")&(search_results(protein_name)!="No results found")):

    all_vars = search_results(protein_name)
    ##### all_vars is a tuple of strings like gene_name, json files and integers
    print("Content-type: text/html","\n\n")
    print ('''
  <head><meta http-equiv="refresh" content="0;URL='http://localhost/results.html'" /></head>
''')
</code>```

Any suggestions on how to proceed? Any help is appreciated, thanks!

答:
As you have probably discovered, your current technique issues a redirect to 'results.html', but otherwise discards any results. I don't know exactly what your goals are, but one approach would be to treat 'results.html' as a simple template. Your script will populate it and return it in response to each request. In the example below, 'results.html' can contain arbitrary HTML, along with the line '##RESULTS##', which will be replaced with your output.

```<code>#!/Users/<username>/opt/anaconda3/bin/python

import sys
import pandas as pd
import numpy as np
import cgi
import cgitb
cgitb.enable()

def process_results(results):
    if results=='No protein entered' or results=='No results found':
        return results
    # else do something with results, e.g., format into an HTML table
    buf = '<table>\n'
    for result in results:
        buf += f'<tr><td>{cgi.escape(str(result))}</td></tr>\n'
    buf += '</table>\n'
    return buf

form = cgi.FieldStorage()
protein_name = form.getvalue('protein_name')
results = search_results(protein_name)

print("Content-type: text/html\n")
with open('results.html') as template:
    for line in (x.rstrip() for x in template):
        if line == '##RESULTS##':
            print(process_results(results))
        else:
            print(line)
</code>```

Good luck.

Body:
I've been trying to figure out how to do this for a while without using a framework (I can make this work with Flask for example) but I haven't found anything as of yet. I have two html scripts and a python cgi script. In essence I have the first html file wherein the user enters a string that I read into my python cgi script which in turn does a number of things to finally give me a bunch of strings and json file that I need to pass to another html file and be able to read them there as well.

So far the first half works, and I can open the second html with a redirect which is not elegant but nothing else has worked with the following code:

#!/Users/<username>/opt/anaconda3/bin//python
import pandas as pd
import numpy as np
import cgi
import cgitb
import sys
cgitb.enable()

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
protein_name = form.getvalue('protein_name')
####### function search_results takes in protein_name and gives me the data ###
####### I need to pass to the html file: results.html #########################

if ((search_results(protein_name)!="No protein entered")&(search_results(protein_name)!="No results found")):

    all_vars = search_results(protein_name)
    ##### all_vars is a tuple of strings like gene_name, json files and integers
    print("Content-type: text/html","\n\n")
    print ('''
  <meta http-equiv="refresh" content="0;URL='http://localhost/results.html'" />
''')

Any suggestions on how to proceed? Any help is appreciated, thanks!

Body:
As you have probably discovered, your current technique issues a redirect to 'results.html', but otherwise discards any results. I don't know exactly what your goals are, but one approach would be to treat 'results.html' as a simple template. Your script will populate it and return it in response to each request. In the example below, 'results.html' can contain arbitrary HTML, along with the line '##RESULTS##', which will be replaced with your output.

#!/Users/<username>/opt/anaconda3/bin/python

import sys
import pandas as pd
import numpy as np
import cgi
import cgitb
cgitb.enable()

def process_results(results):
    if results=='No protein entered' or results=='No results found':
        return results
    # else do something with results, e.g., format into an HTML table
    buf = '<table>\n'
    for result in results:
        buf += f'<tr><td>{cgi.escape(str(result))}</td></tr>\n'
    buf += '</table>\n'
    return buf

form = cgi.FieldStorage()
protein_name = form.getvalue('protein_name')
results = search_results(protein_name)

print("Content-type: text/html\n")
with open('results.html') as template:
    for line in (x.rstrip() for x in template):
        if line == '##RESULTS##':
            print(process_results(results))
        else:
            print(line)

Good luck.


问:
How to change json data format from array to array of objects with javascript?
I am trying to load data into ag-grid so I got the json data like this format:

```<code>{"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}}
</code>```

I need it to be like this to pass it to the grid:

```<code>{"my_data":[{"labels": 1}, {"labels": 2}, ..., {"idx":"idx1"}, {"idx":"idx2"}, ...}]
</code>```

Is there a fast way to do it this format or I have to loop through the data using reduce or map ?

desired format example: https://www.ag-grid.com/sample-data/monthlySales.json

I tried to load the data like this

```<code>var obj = $.parseJSON(JSON.stringify(data));
gridOptions.api.setRowData(obj.mydata.labels);
</code>```

答:
Use reduce will simplify.

const data = { my_data: { labels: [1, 2, 3], idx: ["idx1", "idx2"] } };

const updated = Object.entries(data.my_data).reduce((acc, [key, value]) => {
  value.forEach(item => acc.push({ [key]: item }));
  return acc;
}, []);

const data_updated = { my_data: updated };

console.log(data_updated);```

Body:
I am trying to load data into ag-grid so I got the json data like this format:

{"my_data":{"labels":[1,2,3,...], "idx":["idx1", "idx2", ...]}}

I need it to be like this to pass it to the grid:

{"my_data":[{"labels": 1}, {"labels": 2}, ..., {"idx":"idx1"}, {"idx":"idx2"}, ...}]

Is there a fast way to do it this format or I have to loop through the data using reduce or map ?

desired format example: https://www.ag-grid.com/sample-data/monthlySales.json

I tried to load the data like this

var obj = $.parseJSON(JSON.stringify(data));
gridOptions.api.setRowData(obj.mydata.labels);


问:
Python PriorityQueue Heapify Method
I am using this library for a heap:

```<code>from Queue import PriorityQueue
</code>```

I need to trigger a heapify because in this priority queue i am inserting a node class and the prioirty queue is ordered based on node.val like this:

```<code>class Node():
   __init__(self,val,text):
       self.val = val
       self.text = text

</code>```

and my pq:

```<code>pq = PriorityQueue()
first = Node(1,'abcd')
pq.put((first.val,first))

xyz = Node(10,'asdf')
pq.put((xyz.val,xyz))

fsa = Node(7,'asdsbcd')
pq.put((fsa.val,fsa))

</code>```

now it works fine but if i want to for example change first nodes value like this:

```<code>first.val = 100
</code>```

is there a method like pq.heapify() or something..

how do i call a heapify method so that it can sort it? because if i dont then it will be sort the list and assume first still is 1 not 100.

答:
I believe it would be better to use heapq library for your heap.

Then you can use a process from this answer to update the min value in the heap as follows.

Advantages:

Approach allows updating smallest element using replace.

Takes only O(log(n)) to update the value of the smallest element (i.e. changing first from 1 to 100)

Faster than using Heapify when only one item needs to be updated (which takes O(n))

Code

```<code>import heapq

class Node():
  def __init__(self,val,text):
       self.val = val
       self.text = text
  def __str__(self):   # Add a method to node to string for display
    return f'{self.val}, {self.text}'

class MyHeap(object):
  """The class keeps an internal list, where each element is a tuple.
    The first tuple element is the priority (val), calculated at element insertion
    time, using the key parameter, passed at Heap instantiation"""
  def __init__(self, initial=None, key=lambda x:x.val):
    self.key = key
    if initial:
      self._data = [(key(item), item) for item in initial]
      heapq.heapify(self._data)
    else:
      self._data = []

  def push(self, item):
    heapq.heappush(self._data, (self.key(item), item))

  def pop(self):
    return heapq.heappop(self._data)[1]

  def replace(self, item):
    # Pops min element and adds a new element
    v = self.pop()
    self.push(item)
    return v
</code>```

Testing

Test 1. Add Elements and dump heap

```<code># Add elements
pq = MyHeap()
first = Node(1,'abcd')
pq.push(first)

xyz = Node(10,'asdf')
pq.push(xyz)

fsa = Node(7,'asdsbcd')
pq.push(fsa)

# Dump elements in order
print('Initial Ordering')
while pq._data:
  print(pq.pop())
</code>```

Result

```<code>Initial Ordering
1, abcd
7, asdsbcd
10, asdf
</code>```

Test 2. Remove smallest and add as new element with larger value with new value

```<code># Add elements
pq.push(first)
pq.push(xyz)
pq.push(fsa)

# Update first element using replace
first.val = 100
pq.replace(first)

print('\nNew Ordering')
while pq._data:
  print(pq.pop())
</code>```

Result

```<code>New Ordering
7, asdsbcd
10, asdf
100, abcd
</code>```

Test 3: Add Elements as List

```<code>print('\nUsing List')
pq = MyHeap([first, xyz, fsa])
while pq._data:
  print(pq.pop())
</code>```

Result

```<code>Using List
7, asdsbcd
10, asdf
100, abcd
</code>```

Title: Python PriorityQueue Heapify Method

Body:
I am using this library for a heap:

from Queue import PriorityQueue

I need to trigger a heapify because in this priority queue i am inserting a node class and the prioirty queue is ordered based on node.val like this:

class Node():
   __init__(self,val,text):
       self.val = val
       self.text = text

and my pq:

pq = PriorityQueue()
first = Node(1,'abcd')
pq.put((first.val,first))

xyz = Node(10,'asdf')
pq.put((xyz.val,xyz))

fsa = Node(7,'asdsbcd')
pq.put((fsa.val,fsa))

now it works fine but if i want to for example change first nodes value like this:

first.val = 100

is there a method like pq.heapify() or something..

how do i call a heapify method so that it can sort it? because if i dont then it will be sort the list and assume first still is 1 not 100.

Body:
I believe it would be better to use heapq library for your heap.

Then you can use a process from this answer to update the min value in the heap as follows.

Advantages:

Approach allows updating smallest element using replace.

Takes only O(log(n)) to update the value of the smallest element (i.e. changing first from 1 to 100)

Faster than using Heapify when only one item needs to be updated (which takes O(n))

Code

import heapq

class Node():
  def __init__(self,val,text):
       self.val = val
       self.text = text
  def __str__(self):   # Add a method to node to string for display
    return f'{self.val}, {self.text}'

class MyHeap(object):
  """The class keeps an internal list, where each element is a tuple.
    The first tuple element is the priority (val), calculated at element insertion
    time, using the key parameter, passed at Heap instantiation"""
  def __init__(self, initial=None, key=lambda x:x.val):
    self.key = key
    if initial:
      self._data = [(key(item), item) for item in initial]
      heapq.heapify(self._data)
    else:
      self._data = []

  def push(self, item):
    heapq.heappush(self._data, (self.key(item), item))

  def pop(self):
    return heapq.heappop(self._data)[1]

  def replace(self, item):
    # Pops min element and adds a new element
    v = self.pop()
    self.push(item)
    return v

Testing

Test 1. Add Elements and dump heap

# Add elements
pq = MyHeap()
first = Node(1,'abcd')
pq.push(first)

xyz = Node(10,'asdf')
pq.push(xyz)

fsa = Node(7,'asdsbcd')
pq.push(fsa)

# Dump elements in order
print('Initial Ordering')
while pq._data:
  print(pq.pop())

Result

Initial Ordering
1, abcd
7, asdsbcd
10, asdf

Test 2. Remove smallest and add as new element with larger value with new value

# Add elements
pq.push(first)
pq.push(xyz)
pq.push(fsa)

# Update first element using replace
first.val = 100
pq.replace(first)

print('\nNew Ordering')
while pq._data:
  print(pq.pop())

Result

New Ordering
7, asdsbcd
10, asdf
100, abcd

Test 3: Add Elements as List

print('\nUsing List')
pq = MyHeap([first, xyz, fsa])
while pq._data:
  print(pq.pop())

Result

Using List
7, asdsbcd
10, asdf
100, abcd


问:
Redirecting to homepage does not work after submitting a form
I have a form and its' submit button has a function attached to it.

```<code>    <form class="form">
        <button class="btn" type="submit" onclick="submitItem()">Save</button>
    </form>
</code>```

My submitItem() function looks like this:

```<code>function submitItem() {
    const url = 'http://localhost:3000/items';

    const data = {
      // input values here
    };

    const json = JSON.stringify(data);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

    xhr.send(json);

    window.location.replace('/index.html');
}
</code>```

The post request works - new item gets added, but the window.location.replace('/index.html') does not work and leaves me in the form page with submitted data in the URL parameters.

答:
Since your button element is inside a form tag, whenever the button is clicked, the form will trigger a submit event since the button type is "submit".
Hence, the page refreshes. This will override your window.location.replace("/index.html") and thus nothing happens.

One solution is, remove the enclosing form tags.

Or include an onsubmit="submitItem(); return false" to the form tag as shown below.

Don't forget to remove the onclick on the button.

```<code> <form class="form" onsubmit="submitItem(); return false">
        <button class="btn" type="submit">Save</button>
    </form>
</code>```

Body:
I have a form and its' submit button has a function attached to it.

    <form class="form">
        <button class="btn" type="submit" onclick="submitItem()">Save</button>
    </form>

My submitItem() function looks like this:

function submitItem() {
    const url = 'http://localhost:3000/items';

    const data = {
      // input values here
    };

    const json = JSON.stringify(data);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

    xhr.send(json);

    window.location.replace('/index.html');
}

The post request works - new item gets added, but the window.location.replace('/index.html') does not work and leaves me in the form page with submitted data in the URL parameters.

Body:
Since your button element is inside a form tag, whenever the button is clicked, the form will trigger a submit event since the button type is "submit".
Hence, the page refreshes. This will override your window.location.replace("/index.html") and thus nothing happens.

One solution is, remove the enclosing form tags.

Or include an onsubmit="submitItem(); return false" to the form tag as shown below.

Don't forget to remove the onclick on the button.

 <form class="form" onsubmit="submitItem(); return false">
        <button class="btn" type="submit">Save</button>
    </form>