问:
Using a search function for arrays of different types of structs in C
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

```<code>typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;
</code>```

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

```<code>book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}
</code>```

And instead be able to perform the search for both data structures in a single function?

答:
The other answers are great, but just because your code is in C, it doesn't mean it can't be in C++!  </p>

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

#define SIZE 256

struct Base {
    int isbn;
    char name[SIZE];
    int year;
};

struct Book {
    struct Base base; // Inheritance, C style
    int number;
};

struct Magazine {
    struct Base base;  // Inheritance, C style
    char author[SIZE];
};

/*
You're going to need to cast the arguments and return value.
Also provide the size of the element.
However: the code is generic, casting always works (if `Base` is the first element) , and there is no need for IF or SWITCH statements.
*/
struct Base* search(struct Base* array,int length,size_t size,int key){
    for (int i=0;i<length;++i){
        if (array->isbn == key){
            return array;
        }
        // array[i] won't work, because the size of Base is not the size we need to jump in.
        array = (struct Base*)((uint8_t*)array + size);
    }
    return NULL;
}

int main(int argc,char** argv){

    // Initialize some data
    struct Book books[] = {
        { {123,"Moby Dick",1851},1 },
        { {124,"Oliver Twist",1837},2 }
    };
    struct Magazine magazines[] = {
        {{ 125,"Wired",2020 }, "Some author"},
        {{ 126,"Byte",1990 }, "Some author"}
    };

    // Search for a book and a magazine
    struct Book* book = (struct Book*)search((struct Base*)books,2,sizeof(struct Book),124);
    struct Magazine* magazine = (struct Magazine*)search((struct Base*)magazines,2,sizeof(struct Magazine),126);

    if (book){
        printf("Found book %s, number: %d\n",book->base.name,book->number);
    }
    if (magazine){
        printf("Found magazine %s, author: %s\n",magazine->base.name,magazine->author);
    }
}
</code>```

Body:
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}

And instead be able to perform the search for both data structures in a single function?

Body:
The other answers are great, but just because your code is in C, it doesn't mean it can't be in C++!

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

#define SIZE 256

struct Base {
    int isbn;
    char name[SIZE];
    int year;
};

struct Book {
    struct Base base; // Inheritance, C style
    int number;
};

struct Magazine {
    struct Base base;  // Inheritance, C style
    char author[SIZE];
};

/*
You're going to need to cast the arguments and return value.
Also provide the size of the element.
However: the code is generic, casting always works (if `Base` is the first element) , and there is no need for IF or SWITCH statements.
*/
struct Base* search(struct Base* array,int length,size_t size,int key){
    for (int i=0;i<length;++i){
        if (array->isbn == key){
            return array;
        }
        // array[i] won't work, because the size of Base is not the size we need to jump in.
        array = (struct Base*)((uint8_t*)array + size);
    }
    return NULL;
}

int main(int argc,char** argv){

    // Initialize some data
    struct Book books[] = {
        { {123,"Moby Dick",1851},1 },
        { {124,"Oliver Twist",1837},2 }
    };
    struct Magazine magazines[] = {
        {{ 125,"Wired",2020 }, "Some author"},
        {{ 126,"Byte",1990 }, "Some author"}
    };

    // Search for a book and a magazine
    struct Book* book = (struct Book*)search((struct Base*)books,2,sizeof(struct Book),124);
    struct Magazine* magazine = (struct Magazine*)search((struct Base*)magazines,2,sizeof(struct Magazine),126);

    if (book){
        printf("Found book %s, number: %d\n",book->base.name,book->number);
    }
    if (magazine){
        printf("Found magazine %s, author: %s\n",magazine->base.name,magazine->author);
    }
}


来源: stackexchange

问:
Relying on the (copy) attribute to copy NSMutableDictionary causes crash
The following program relies on the copy

attribute to copy a NSMutableDictionary.

The copy is apparently ok, but, if I try

to add a new element to the copy, the program crashes.

Is it some kind of bug?

PS. If it matters it's NON ARC

```<code>#import <Foundation/Foundation.h>

@interface Dog: NSObject
@property (copy) NSMutableDictionary *dict;
@end

@implementation Dog
@synthesize dict;

- (id) init
{
    if ( (self = [super init]) ) {
    dict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in dict) {
    printf("%s --> %s\n", [key UTF8String], [dict[key] UTF8String] );
    }
}

@end

//------------------------------------------------------

int main() {
    Dog *dog1 = [[Dog alloc] init];
    Dog *dog2 = [[Dog alloc] init];

    dog1.dict[@"color"] = @"black";
    dog2.dict = dog1.dict;
    [dog2 print];
    // the print shows that dog2.dict is indeed a copy of dog1.dict
    // lldb shows that it is a shallow copy, which I guess is ok
    // since values are immutable.
    // ... so far so good.
    dog1.dict[@"tail"] = @"long";   // This goes smoothly
    //
    // But...
    dog2.dict[@"tail"] = @"long";
    // here program crashes with the following message
    //
    // -[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0
    //*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0'
    return(0);
}
</code>```

EDIT:
If I replace the line

```<code>dog2.dict = dog1.dict;
</code>```

with

```<code>[dog2.dict addEntriesFromDictionary: dog1.dict];
</code>```

then it works. There is no crash.

So, OK, this is the correct way of doing it.

But my point is: don't I deserve at least a warning

from the compiler?

答:
copy attribute creates an NSDictionary instance, not NSMutableDictionary, that's why it's crashing.
First, change the property to retain from copy:

```<code>@property (retain) NSMutableDictionary* duct;
</code>```

Then you can do the following:

```<code>Dog *dog2 = [[Dog alloc] init];
dog2.dict = [dog1.dict mutableCopy];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The following program relies on the copy

attribute to copy a NSMutableDictionary.

The copy is apparently ok, but, if I try

to add a new element to the copy, the program crashes.

Is it some kind of bug?

PS. If it matters it's NON ARC

#import <Foundation/Foundation.h>

@interface Dog: NSObject
@property (copy) NSMutableDictionary *dict;
@end

@implementation Dog
@synthesize dict;

- (id) init
{
    if ( (self = [super init]) ) {
    dict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in dict) {
    printf("%s --> %s\n", [key UTF8String], [dict[key] UTF8String] );
    }
}

@end

//------------------------------------------------------

int main() {
    Dog *dog1 = [[Dog alloc] init];
    Dog *dog2 = [[Dog alloc] init];

    dog1.dict[@"color"] = @"black";
    dog2.dict = dog1.dict;
    [dog2 print];
    // the print shows that dog2.dict is indeed a copy of dog1.dict
    // lldb shows that it is a shallow copy, which I guess is ok
    // since values are immutable.
    // ... so far so good.
    dog1.dict[@"tail"] = @"long";   // This goes smoothly
    //
    // But...
    dog2.dict[@"tail"] = @"long";
    // here program crashes with the following message
    //
    // -[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0
    //*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0'
    return(0);
}

EDIT:
If I replace the line

dog2.dict = dog1.dict;

with

[dog2.dict addEntriesFromDictionary: dog1.dict];

then it works. There is no crash.

So, OK, this is the correct way of doing it.

But my point is: don't I deserve at least a warning

from the compiler?

Body:
copy attribute creates an NSDictionary instance, not NSMutableDictionary, that's why it's crashing.
First, change the property to retain from copy:

@property (retain) NSMutableDictionary* duct;

Then you can do the following:

Dog *dog2 = [[Dog alloc] init];
dog2.dict = [dog1.dict mutableCopy];


问:
See commands of make and all called make files thereafter
I am trying to decompose a make build system of a very large code base however I am unable to see every command the make invokes because it calls various make files in numerous directories outside of the current directory. I followed this answer and various other ones Making make print commands before executing when NOT using CMake

Though the above yielded some advancement and was quite illuminating it was not the home run I need. It offers solutions to see the commands that make invokes. Which is better than great. However, the issue is the various sub make commands that are invoked thereafter. I only see those commands as printed with no additional information of what is occurring sub make. I tried to alias make such that

```<code>alias make='make SHELL='\''/bin/bash -x'\'''

# or

alias make='make -n'
</code>```

However the above fail to replace the invoked make commands with the alias. Is there another way I can dissect a large code base make build system out there?

```<code>> make
rmdir --ignore-fail-on-non-empty /somefolder* 2> /dev/null; true
cd /someotherfolder/; make cur-dir=somefolder dirs-to-build=somemorefolders/ env_variable another_variable someMakeRule # no output from this  make
make  TARGET=someTarget env_variable gdbinit source_dir someMakeRule; # no output from this  make
# ...
# output from first top makefile
# ...
make[1]: Nothing to be done for 'someMakeRule'.
</code>```

答:
You cannot use an alias, because aliases only exist in interactive shells and are not present in non-interactive shells like the one make uses to invoke comments in recipes.  Same with shell functions.

You also cannot set the SHELL variable to a command that uses arguments: the value of SHELL must be only a command name.  You can, though, set the .SHELLFLAGS variable to extra options to pass to the shell.  Don't forget you need the -c option in addition to whatever flags you add!

Something like .SHELLFLAGS=-xc

If your makefiles are all properly invoking their submakes then using make -n as the initial invocation should Just Work.

By "properly invoking" I mean, they should always use the $(MAKE) variable when invoking sub-makes and never use a raw make command.

If they do not invoke sub-make properly and you cannot fix that, then the best you can do is write a shell script called make that does what your aliases above do, then add that to your PATH so it's found first.  Obviously inside the script you'll have to use a fully-qualified path to run the "real" make else you'll get infinite recursion :)

Body:
I am trying to decompose a make build system of a very large code base however I am unable to see every command the make invokes because it calls various make files in numerous directories outside of the current directory. I followed this answer and various other ones Making make print commands before executing when NOT using CMake

Though the above yielded some advancement and was quite illuminating it was not the home run I need. It offers solutions to see the commands that make invokes. Which is better than great. However, the issue is the various sub make commands that are invoked thereafter. I only see those commands as printed with no additional information of what is occurring sub make. I tried to alias make such that

alias make='make SHELL='\''/bin/bash -x'\'''

# or

alias make='make -n'

However the above fail to replace the invoked make commands with the alias. Is there another way I can dissect a large code base make build system out there?

> make
rmdir --ignore-fail-on-non-empty /somefolder* 2> /dev/null; true
cd /someotherfolder/; make cur-dir=somefolder dirs-to-build=somemorefolders/ env_variable another_variable someMakeRule # no output from this  make
make  TARGET=someTarget env_variable gdbinit source_dir someMakeRule; # no output from this  make
# ...
# output from first top makefile
# ...
make[1]: Nothing to be done for 'someMakeRule'.


问:
Limit the date to today and block the previous dates
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html></code>```

Thank you very much for your help and your time.

答:
Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:

```<code>var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);
</code>```

Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.

Body:
I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.

Compare two dates with JavaScript

I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.

For information, I am obliged to use JavaScript to handle the dates.

function validation()
{
    const date_start = document.getElementById('date_start').value;
    const inputDate = new Date(date_start);

    const dayFromImputDate = inputDate.getFullYear(); // previous day

    const now = new Date();
    const dateNow = now.getFullYear();

    if(dayFromImputDatee < dateNow) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
    }

    if(date_start == ""){
        document.getElementById('date_startError').innerHTML = " ** date empty ! ";
        return false;
    }

    console.log("Date is valid");
    return true;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Titre de la page</title>
  <link rel="stylesheet" href="style.css">

<form action="#" onsubmit="return validation()" >

Date start :

<input type="date" name="date_start" id="date_start">

<input type="submit" value="ok">
</form>

Thank you very much for your help and your time.

Body:
Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:

var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);

Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.


问:
Why "Follow symbol under cursor" does not work in Qt Creator for Mac OS X?
I'm using Qt Creator under Mac osx, but "Follow symbol under cursor" option, to allow me to jump for class and methods' definitions, does not really work... it only works for local symbols. neither does "Switch between method declaration/definition"

Any ideas?

Thanks much for any thought.
Lior

答:
As @badcat said, ensure that you have the most recent version.

Other than that, when you have problems following a "symbol under cursor" it could mean 1 of 2 things.

1)  I would check that you have your project appropriately constructed so that it has all the include and source files that it needs.

2)  This is more rare, but check that you have function definitions in header files and that they are included properly by your source files.  As opposed to what you may ask?  We have a project here where, instead of include files, functions are defined in .cc files, and extern statements are used so that other files have access to them. (It's legacy code)  In such a case, Qt Creator doesn't know how to find anything because files are only aware of each other while linking and have no other way to see each other.

ContentLicense: CC BY-SA 3.0


问:
python plotting multiple bars
I've been trying to do it for several hours and I have a mistake every time. I want to create 3 bar plots in one graph. The y-axis is to be between 0 and 1000.
The end result should be this

Thats my code:

```<code>import matplotlib.pyplot as plt
import numpy as np
import csv

df = pd.read_csv('razemKM.csv')
dfn = pd.read_csv('razemNPM.csv')
print(df)
y=[0,1000]
a=(df["srednia"]-df["odchStand"])
a1=df["srednia"]
a2=(df["srednia"]+df["odchStand"])

plt.bar(y,a,width=0.1,color='r')
plt.bar(y,a1,width=0.1,color='g')
plt.bar(y,a2,width=0.1,color='y')

plt.show()
</code>```

答:
You can use pandas plot function:</p>

```<code>df['Sum'] = df["srednia"]+df["odchStand"]
df['Dif'] = df["srednia"]-df["odchStand"]

df.plot.bar(y=['Diff','srednia', 'Sum'],width=0.1)
plt.show()
</code>```

Title: python plotting multiple bars

Body:
I've been trying to do it for several hours and I have a mistake every time. I want to create 3 bar plots in one graph. The y-axis is to be between 0 and 1000.
The end result should be this

Thats my code:

import matplotlib.pyplot as plt
import numpy as np
import csv

df = pd.read_csv('razemKM.csv')
dfn = pd.read_csv('razemNPM.csv')
print(df)
y=[0,1000]
a=(df["srednia"]-df["odchStand"])
a1=df["srednia"]
a2=(df["srednia"]+df["odchStand"])

plt.bar(y,a,width=0.1,color='r')
plt.bar(y,a1,width=0.1,color='g')
plt.bar(y,a2,width=0.1,color='y')

plt.show()

Body:
You can use pandas plot function:

df['Sum'] = df["srednia"]+df["odchStand"]
df['Dif'] = df["srednia"]-df["odchStand"]

df.plot.bar(y=['Diff','srednia', 'Sum'],width=0.1)
plt.show()


问:
How to return a empty cursor from a stored procedure?
I have OUT parameter of a stored procedure as a REF CURSOR. Based on a particular condition, I would want to either return a result set (already implemented).

But how do I return an empty cursor when the condition fails? Without raising an exception? Just pasting pseudo code:

```<code>IF condition = true THEN
   OPEN OUT_CUR FOR
   Select Some query

ELSE

   Return empty OUT_CUR

END IF
</code>```

答:
```<code>IF condition = true THEN
   OPEN OUT_CUR FOR
   Select Some query

ELSE

    OPEN OUT_CUR FOR select * from unnest(array[1,2]) arr where  false

END IF
</code>```

Body:
I have OUT parameter of a stored procedure as a REF CURSOR. Based on a particular condition, I would want to either return a result set (already implemented).

But how do I return an empty cursor when the condition fails? Without raising an exception? Just pasting pseudo code:

IF condition = true THEN
   OPEN OUT_CUR FOR
   Select Some query

ELSE

   Return empty OUT_CUR

END IF


问:
Pandas: Remove rows from the dataframe that begin with a letter and save CSV
Here is a sample CSV I'm working with

Here is my code:

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

def deleteSearchTerm(inputFile):
#(1) Open the file
    df = pd.read_csv(inputFile)

#(2) Filter every row where the first letter is 's' from search term
    df = df[df['productOMS'].str.contains('^[a-z]+')]
        #REGEX to filter anything that would ^ (start with) a letter

inputFile = inputFile
deleteSearchTerm(inputFile)
</code>```

What I want to do:

Anything in the column ProductOMS that begins with a letter would be a row that I don't want. So I'm trying to delete them based on a condition and I was also trying would regular expressions just so I'd get a little bit more comfortable with them.

I tried to do that with:

```<code>df = df[df['productOMS'].str.contains('^[a-z]+')]
</code>```

where if any of the rows starts with any lower case letter I would drop it (I think)

Please let me know if I need to add anything to my post!

Edit:

Here is a link to a copy of the file I'm working with.

https://drive.google.com/file/d/1Dsw2Ana3WVIheNT43Ad4Dv6C8AIbvAlJ/view?usp=sharing

Another Edit: Here is the dataframe I'm working with

```<code>productNum,ProductOMS,productPrice
2463448,1002623072,419.95,
2463413,1002622872,289.95,
2463430,1002622974,309.95,
2463419,1002622908,329.95,
2463434,search?searchTerm=2463434,,
2463423,1002622932,469.95,
</code>```

New Edit:
Here's some updated code using an answer

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

def deleteSearchTerm(inputFile):
#(1) Open the file

    df = pd.read_csv(inputFile)
    print(df)

#(2) Filter every row where the first letter is 's' from search term
    df = df[~pd.to_numeric(df['ProductOMS'],errors='coerce').isnull()]

    print(df)

inputFile = inputFile
deleteSearchTerm(inputFile)
</code>```

When I run this code and print out the dataframes this gets rid of the rows that start with 'search'. However my CSV file is not updating

答:
It looks like a scope problem to me.
First we need to return df:

```<code>def deleteSearchTerm(inputFile):
#(1) Open the file

    df = pd.read_csv(inputFile)
    print(df)

#(2) Filter every row where the first letter is 's' from search term
    df = df[~pd.to_numeric(df['ProductOMS'],errors='coerce').isnull()]

    print(df)
    return df
</code>```

Then replace the line

```<code>DeleteSearchTerm(InputFile)
</code>```

with:

```<code>InputFile = DeleteSearchTerm(InputFile)
</code>```

Basically your function is not returning anything.
After you fix that you just need to redefine your inputFile variable to the new dataframe your function is returning.

If you already defined df earlier in your code and you're trying to manipulate it, then the function is not actually changing your existing global df variable. Instead it's making a new local variable under the same name.

To fix this we first return the local df and then re-assign the global df to the local one.

You should be able to find more information about variable scope at this link:

https://www.geeksforgeeks.org/global-local-variables-python/

It also appears you never actually update your original file.

Try adding this to the end of your code:

```<code>df.to_csv('CSV file name', index=True)
</code>```

Index just says whether you want to have a line index.

Body:
Here is a sample CSV I'm working with

Here is my code:

import numpy as np
import pandas as pd

def deleteSearchTerm(inputFile):
#(1) Open the file
    df = pd.read_csv(inputFile)

#(2) Filter every row where the first letter is 's' from search term
    df = df[df['productOMS'].str.contains('^[a-z]+')]
        #REGEX to filter anything that would ^ (start with) a letter

inputFile = inputFile
deleteSearchTerm(inputFile)

What I want to do:

Anything in the column ProductOMS that begins with a letter would be a row that I don't want. So I'm trying to delete them based on a condition and I was also trying would regular expressions just so I'd get a little bit more comfortable with them.

I tried to do that with:

df = df[df['productOMS'].str.contains('^[a-z]+')]

where if any of the rows starts with any lower case letter I would drop it (I think)

Please let me know if I need to add anything to my post!

Edit:

Here is a link to a copy of the file I'm working with.

https://drive.google.com/file/d/1Dsw2Ana3WVIheNT43Ad4Dv6C8AIbvAlJ/view?usp=sharing

Another Edit: Here is the dataframe I'm working with

productNum,ProductOMS,productPrice
2463448,1002623072,419.95,
2463413,1002622872,289.95,
2463430,1002622974,309.95,
2463419,1002622908,329.95,
2463434,search?searchTerm=2463434,,
2463423,1002622932,469.95,

New Edit:
Here's some updated code using an answer

import numpy as np
import pandas as pd

def deleteSearchTerm(inputFile):
#(1) Open the file

    df = pd.read_csv(inputFile)
    print(df)

#(2) Filter every row where the first letter is 's' from search term
    df = df[~pd.to_numeric(df['ProductOMS'],errors='coerce').isnull()]

    print(df)

inputFile = inputFile
deleteSearchTerm(inputFile)

When I run this code and print out the dataframes this gets rid of the rows that start with 'search'. However my CSV file is not updating

Body:
It looks like a scope problem to me.
First we need to return df:

def deleteSearchTerm(inputFile):
#(1) Open the file

    df = pd.read_csv(inputFile)
    print(df)

#(2) Filter every row where the first letter is 's' from search term
    df = df[~pd.to_numeric(df['ProductOMS'],errors='coerce').isnull()]

    print(df)
    return df

Then replace the line

DeleteSearchTerm(InputFile)

with:

InputFile = DeleteSearchTerm(InputFile)

Basically your function is not returning anything.
After you fix that you just need to redefine your inputFile variable to the new dataframe your function is returning.

If you already defined df earlier in your code and you're trying to manipulate it, then the function is not actually changing your existing global df variable. Instead it's making a new local variable under the same name.

To fix this we first return the local df and then re-assign the global df to the local one.

You should be able to find more information about variable scope at this link:

https://www.geeksforgeeks.org/global-local-variables-python/

It also appears you never actually update your original file.

Try adding this to the end of your code:

df.to_csv('CSV file name', index=True)

Index just says whether you want to have a line index.


问:
How to install and use F# Powerpack in Mono?
I need to install use F# powerpack.
I use mono version 2.10.2 on Mac.

```<code>mono --version
Mono JIT compiler version 2.10.2 (tarball Mon Apr 18 09:14:01 MDT 2011)
Copyright (C) 2002-2011 Novell, Inc and Contributors. www.mono-project.com
        TLS:           normal
        SIGSEGV:       normal
        Notification:  kqueue
        Architecture:  x86
        Disabled:      none
        Misc:          debugger softdebug
        LLVM:          yes(2.9svn-mono)
        GC:            Included Boehm (with typed GC)
</code>```

Installation.

Download the powerpack zip file from here.

Unzip the file to directory ~/bin.

Add the ~/bin/FSharpPowerPack-1.9.9.9/bin to the PATH. I also add it to the MONO_PATH just in case. (I'm not sure if this is necessary or not)

For the dlls in the ~/bin/FSharpPowerPack-1.9.9.9/bin/gac, use the command sudo gacutil -i <ALL_THE_FILES_IN_DLL>.dll

Using the powerpack

I tested with the sample code in this page. I name it linq.fs

```<code>open Microsoft.FSharp.Linq
let adderExpr = <@ fun i -> i + 1 @>.ToLinqExpression()
let adder = <@ fun i -> i + 1 @>.Compile()
</code>```

Questions

I got errors with fsc linq.fs /r:FSharp.PowerPack.Linq.dll. What might be wrong?

/Users/smcho/Desktop/fs/powerpack/linq.fs(1,38): error FS0039: The field, constructor or member 'ToLinqExpression' is not defined

/Users/smcho/Desktop/fs/powerpack/linq.fs(2,34): error FS0039: The field, constructor or member 'Compile' is not defined

Do I need to install all the dll with gacutil -i? Or, just appending the dll path to the PATH/MONO_PATH environment variable is just good enough?

答:
Your installation procedure seems to be correct (just unzip and install using gacutil -i).  I think there is just a minor issue with the sample - the ToLinqExpression extension method is available in a module that needs to be explicitly opened, so your file should be:

EDIT The right module name is actually Microsoft.FSharp.Linq.QuotationEvaluation:

```<code>open Microsoft.FSharp.Linq.QuotationEvaluation

let adderExpr = <@ fun i -> i + 1 @>.ToLinqExpression()
let adder = <@ fun i -> i + 1 @>.Compile()
</code>```

Body:
I need to install use F# powerpack.
I use mono version 2.10.2 on Mac.

mono --version
Mono JIT compiler version 2.10.2 (tarball Mon Apr 18 09:14:01 MDT 2011)
Copyright (C) 2002-2011 Novell, Inc and Contributors. www.mono-project.com
        TLS:           normal
        SIGSEGV:       normal
        Notification:  kqueue
        Architecture:  x86
        Disabled:      none
        Misc:          debugger softdebug
        LLVM:          yes(2.9svn-mono)
        GC:            Included Boehm (with typed GC)

Installation.

Download the powerpack zip file from here.

Unzip the file to directory ~/bin.

Add the ~/bin/FSharpPowerPack-1.9.9.9/bin to the PATH. I also add it to the MONO_PATH just in case. (I'm not sure if this is necessary or not)

For the dlls in the ~/bin/FSharpPowerPack-1.9.9.9/bin/gac, use the command sudo gacutil -i <ALL_THE_FILES_IN_DLL>.dll

Using the powerpack

I tested with the sample code in this page. I name it linq.fs

open Microsoft.FSharp.Linq
let adderExpr = <@ fun i -> i + 1 @>.ToLinqExpression()
let adder = <@ fun i -> i + 1 @>.Compile()

Questions

I got errors with fsc linq.fs /r:FSharp.PowerPack.Linq.dll. What might be wrong?

/Users/smcho/Desktop/fs/powerpack/linq.fs(1,38): error FS0039: The field, constructor or member 'ToLinqExpression' is not defined

/Users/smcho/Desktop/fs/powerpack/linq.fs(2,34): error FS0039: The field, constructor or member 'Compile' is not defined

Do I need to install all the dll with gacutil -i? Or, just appending the dll path to the PATH/MONO_PATH environment variable is just good enough?

Body:
Your installation procedure seems to be correct (just unzip and install using gacutil -i).  I think there is just a minor issue with the sample - the ToLinqExpression extension method is available in a module that needs to be explicitly opened, so your file should be:

EDIT The right module name is actually Microsoft.FSharp.Linq.QuotationEvaluation:

open Microsoft.FSharp.Linq.QuotationEvaluation

let adderExpr = <@ fun i -> i + 1 @>.ToLinqExpression()
let adder = <@ fun i -> i + 1 @>.Compile()


问:
Room database in a Android library and Objects and Dao's in Android project
I want to implement Room database in my app, but I want to do that by creating a Library project.

Library project will store data
Android project will have the Objects and Dao's

Is this possible?

For this I have to implement Room in both Android project as well as Library

But can I have Dao's and Objects in Android project and Database in Library

Why I want to do this.
I want to build this feature in a generic way so that it can be used in my other project. Also Library will not just store the data, it will have some offline functionality which read a Offline data table and checks the internet connection and picks data from the table and send it to server.

None of this is implemented yet. I am in the process of thinking what is the right aproach

Thanks for your suggestions

R

答: I think you can use dynamic feature module, because it dependency to the app module and you can use Dao and Objects from app.


问:
jQuery: How do I check a number from string?
there is a class named:

```<code><div class="level_11 price_level" style="display: block;">
</code>```

I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.

I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.

I need to check the number and say if my number is lower then the number from the level_, then run the script.

```<code>let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1;  // Don't touch this //
let logLevel = Level +1; // Don't touch this //

console.log(`Success ✓ - ${IBuilding.length} buildings left`);

$.each(IBuilding, function(Index, Entity) {
    let BuildingMissing = IBuilding.length - (Index + 1);

    window.setTimeout(function() {
      $.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
      console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success ✓ - last building successfully expanded to level: ' + logLevel }`);

      }, Index * 250);
});
});
</code>```

Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"

Can anyone help me out? :/

答:
I found this on link /buildings/ID/:

current level of building

Maybe I can check the Level from there?
The HTML section for that is:

```<code><dd>

        13

          <a href="/buildings/7356983/expand" class="btn btn-default btn-xs">Ausbauen</a>

      </dd>
</code>```

Body:
there is a class named:

I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.

I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.

I need to check the number and say if my number is lower then the number from the level_, then run the script.

let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1;  // Don't touch this //
let logLevel = Level +1; // Don't touch this //

console.log(`Success ✓ - ${IBuilding.length} buildings left`);

$.each(IBuilding, function(Index, Entity) {
    let BuildingMissing = IBuilding.length - (Index + 1);

    window.setTimeout(function() {
      $.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
      console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success ✓ - last building successfully expanded to level: ' + logLevel }`);

      }, Index * 250);
});
});

Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"

Can anyone help me out? :/

Body:
I found this on link /buildings/ID/:

current level of building

Maybe I can check the Level from there?
The HTML section for that is:

<dd>

        13

          <a href="/buildings/7356983/expand" class="btn btn-default btn-xs">Ausbauen</a>

      </dd>


问:
Replace string between first and second occurrence of forward slash
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

```<code>const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

</code>```

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

答:
var s = '/questions/ask/1';
var s2 = '/questions-math/ask/1';
var r = s.replace(/[^\/][-a-zA-Z]*/, 'example');
var r2 = s2.replace(/[^\/][-a-zA-Z]*/, 'example');
console.log(r);
console.log(r2);```
</div>
</div>
</p>

<p><strong>EDIT:</strong></p>

<p><em>The issue of lazy vs greedy.</em></p>

<p>For some incomprehensible reason, there is a fashion for using lazy-mode regular expressions. Such expressions are not a panacea for everything. In this case, <em>the use of default greedy-mode expressions makes them easier to use and develop.</em></p>

<p>"Higher performance" is also a myth, just think about the algorithm used but for illustration I compared these solutions by calculating the average of 100 tests each <em>one million substitutions</em>:</p>

```I. 10-year PC, CPU 4 core 23145.70 BogoMIPS
Greedy:  278 ms
Lazy:    900 ms

II. 30-year PC, CPU 1 core 3397.11 BogoMIPS
Greedy:  6736 ms
Lazy:    7490 ms
```

As you can see, the unwavering expression turned out to be slower and this difference drastically increases with the increase in processor power.

Note that these differences relate to 1 million substitutions, with one substitution they have absolutely no meaning.

Naturally, this will not be the case in all cases. If we care about the performance of a function, there is no shortcut way, the answer will be given only by making measurements by profiling.

Body:
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

Body:
var s = '/questions/ask/1';
var s2 = '/questions-math/ask/1';
var r = s.replace(/[^\/][-a-zA-Z]*/, 'example');
var r2 = s2.replace(/[^\/][-a-zA-Z]*/, 'example');
console.log(r);
console.log(r2);

EDIT:

The issue of lazy vs greedy.

For some incomprehensible reason, there is a fashion for using lazy-mode regular expressions. Such expressions are not a panacea for everything. In this case, the use of default greedy-mode expressions makes them easier to use and develop.

"Higher performance" is also a myth, just think about the algorithm used but for illustration I compared these solutions by calculating the average of 100 tests each one million substitutions:

I. 10-year PC, CPU 4 core 23145.70 BogoMIPS
Greedy:  278 ms
Lazy:    900 ms

II. 30-year PC, CPU 1 core 3397.11 BogoMIPS
Greedy:  6736 ms
Lazy:    7490 ms

As you can see, the unwavering expression turned out to be slower and this difference drastically increases with the increase in processor power.

Note that these differences relate to 1 million substitutions, with one substitution they have absolutely no meaning.

Naturally, this will not be the case in all cases. If we care about the performance of a function, there is no shortcut way, the answer will be given only by making measurements by profiling.


问:
Changing graphs in real-time using matplotlib
This is the code.

```<code>import matplotlib.pyplot as plt
import random

x = []
y = []

for i in range(10):
    x.append(i)
    y.append(random.randint(0,100))

graph = plt.bar(x,y)
plt.show()
</code>```

Whenever I change any value of y, say y[4] = 7, then I want that to be
reflected in the graph. I want that graph to move.

I tried searching the solution for this but none of them worked for me.

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random

x = []
y = []

for i in range(10):
    x.append(i)
    y.append(random.randint(0,100))

fig, ax = plt.subplots()
bar, = ax.plot(x,y)

def animate(i):
    x = []
    y = []

    for i in range(10):
        x.append(i)
        y.append(random.randint(0,100))

    bar.set_xdata(x)
    bar.set_ydata(y)

    return bar,

animation  = FuncAnimation(fig, animate, interval = 1000)
plt.show()
</code>```

I want similar results, but in form of bar graph.  Any help is appreciated.

答:
Finally got what I wanted</p>

```<code>import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

X = []
Y = []

for i in range(20):
    Y.append(random.randint(1, 100))
    X.append(i)

fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(X, Y, color="#ff7f7f")
ax.set_yticks([])
ax.set_xticks(X)

for number in range(len(Y)):
    ax.text(number, Y[number], Y[number],
            horizontalalignment='center', va="baseline", fontsize=13)

def draw_barchart(year):
    ax.clear()

    X.clear()
    Y.clear()

    for i in range(20):
        Y.append(random.randint(1, 100))
        X.append(i)

    ax.bar(X, Y, color="#ff7f7f")
    ax.set_yticks([])
    ax.set_xticks(X)

    ax.set_yticks([])
    ax.set_xticks(X)

    for number in range(len(Y)):
        ax.text(number, Y[number], Y[number], horizontalalignment='center', va="baseline", fontsize=13)

    plt.box(False)

animator = animation.FuncAnimation(fig, draw_barchart, interval=1000)

plt.show()
</code>```

Body:
This is the code.

import matplotlib.pyplot as plt
import random

x = []
y = []

for i in range(10):
    x.append(i)
    y.append(random.randint(0,100))

graph = plt.bar(x,y)
plt.show()

Whenever I change any value of y, say y[4] = 7, then I want that to be
reflected in the graph. I want that graph to move.

I tried searching the solution for this but none of them worked for me.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random

x = []
y = []

for i in range(10):
    x.append(i)
    y.append(random.randint(0,100))

fig, ax = plt.subplots()
bar, = ax.plot(x,y)

def animate(i):
    x = []
    y = []

    for i in range(10):
        x.append(i)
        y.append(random.randint(0,100))

    bar.set_xdata(x)
    bar.set_ydata(y)

    return bar,

animation  = FuncAnimation(fig, animate, interval = 1000)
plt.show()

I want similar results, but in form of bar graph.  Any help is appreciated.

Body:
Finally got what I wanted

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

X = []
Y = []

for i in range(20):
    Y.append(random.randint(1, 100))
    X.append(i)

fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(X, Y, color="#ff7f7f")
ax.set_yticks([])
ax.set_xticks(X)

for number in range(len(Y)):
    ax.text(number, Y[number], Y[number],
            horizontalalignment='center', va="baseline", fontsize=13)

def draw_barchart(year):
    ax.clear()

    X.clear()
    Y.clear()

    for i in range(20):
        Y.append(random.randint(1, 100))
        X.append(i)

    ax.bar(X, Y, color="#ff7f7f")
    ax.set_yticks([])
    ax.set_xticks(X)

    ax.set_yticks([])
    ax.set_xticks(X)

    for number in range(len(Y)):
        ax.text(number, Y[number], Y[number], horizontalalignment='center', va="baseline", fontsize=13)

    plt.box(False)

animator = animation.FuncAnimation(fig, draw_barchart, interval=1000)

plt.show()


问:
Need helping in getting counts out of an array of objects in JavaScript
I'm working with an array of objects that looks something like this:

```<code>const fruits = [
 {
   Fruit: Apple,
   Count: 4
 },
 {
   Fruit: Orange,
   Count: 3
 },
 {
   Fruit: Apple,
   Count: 2
 }
]
</code>```

I like to end up with my array looking something like this:

```<code>const fruits = [
 {
  Fruit: Apple,
  Count: 6
 },
 {
  Fruit: Orange,
  Count: 3
 },
]
</code>```

Is there any help with this? I've tried to use Reduce but Reduce, needless to say, is my biggest weakness in JavaScript. I've looked at so many articles that get a close answer but nothing that can fully help me. Thank you for the help.

答:
Here's the reduce solution you need:

const fruits = [
 {
   Fruit: "Apple",
   Count: 4
 },
 {
   Fruit: "Orange",
   Count: 3
 },
 {
   Fruit: "Apple",
   Count: 2
 }
]

let result = fruits.reduce((acc,current) => {
   let obj = acc.find(x => x.Fruit === current.Fruit);
   if(!obj){
      acc.push({ Fruit: current.Fruit, Count: current.Count });
   } else {
      obj.Count += current.Count;
   }
   return acc;
}, []);

console.log(result);```

Basically you need to build a new array (acc) and add a new item if there's no such Fruit or increment the counter.

Body:
I'm working with an array of objects that looks something like this:

const fruits = [
 {
   Fruit: Apple,
   Count: 4
 },
 {
   Fruit: Orange,
   Count: 3
 },
 {
   Fruit: Apple,
   Count: 2
 }
]

I like to end up with my array looking something like this:

const fruits = [
 {
  Fruit: Apple,
  Count: 6
 },
 {
  Fruit: Orange,
  Count: 3
 },
]

Is there any help with this? I've tried to use Reduce but Reduce, needless to say, is my biggest weakness in JavaScript. I've looked at so many articles that get a close answer but nothing that can fully help me. Thank you for the help.

Body:
Here's the reduce solution you need:

const fruits = [
 {
   Fruit: "Apple",
   Count: 4
 },
 {
   Fruit: "Orange",
   Count: 3
 },
 {
   Fruit: "Apple",
   Count: 2
 }
]

let result = fruits.reduce((acc,current) => {
   let obj = acc.find(x => x.Fruit === current.Fruit);
   if(!obj){
      acc.push({ Fruit: current.Fruit, Count: current.Count });
   } else {
      obj.Count += current.Count;
   }
   return acc;
}, []);

console.log(result);

Basically you need to build a new array (acc) and add a new item if there's no such Fruit or increment the counter.


问:
How to write a CASE statement in the WHERE clause in Snowflake
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

```<code>case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE
</code>```

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

```<code>SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable
</code>```

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

答:
The issue is when I have to use this in a WHERE clause.

How about adding the age to the dateofbirth instead?

```<code>where dateadd(year, minage, dateofbirth) <= current_date and
      dateadd(year, maxage + 1, dateofbirth) > current_date
</code>```

Body:
I am trying to rewrite a piece of SQL code that was initially written for Vertica. Vertica has the AGE_IN_YEARS() built-in function which was great to get someone's age. But, now, I need to find a way to have it to work in Snowflake and I did.

An equivalent statement that replaces AGE_IN_YEARS(DateOfBirth) in Snowflake can be:

case when dateadd(year, datediff(years, DateOfBirth, CURRENT_DATE), DateOfBirth) > CURRENT_DATE
then datediff(years, DateOfBirth, CURRENT_DATE) -1
else datediff(years, DateOfBirth, CURRENT_DATE)
end as AGE

The issue is when I have to use this in a WHERE clause. The original Vertica code is:

SELECT name, dob,
(SELECT AgeRangeCode
   FROM AgeRangeTable
   WHERE AGE_IN_YEARS(DateOfBirth) BETWEEN MinAge AND MaxAge) AS AgeRangeCode,
CURRENT_DATE as TODAY
from MemberInfoTable

and if i add the AGE_IN_YEARS() replacement to the above query, I get

SQL compilation error: Unsupported subquery type cannot be evaluated

How do I go about writing this case in the WHERE clause

Body:
The issue is when I have to use this in a WHERE clause.

How about adding the age to the dateofbirth instead?

where dateadd(year, minage, dateofbirth) <= current_date and
      dateadd(year, maxage + 1, dateofbirth) > current_date


问:
Django get username of logged in user and pass it to models
I am creating a project in django in which I have two diff users i.e. Customers and restaurants. I am creating a model for Menu in which I want add to add user name of logged in user to restaurant name in models. Is there anyway to do this. I have searched through the net got answers like foreign key but not able to implement. Also I need username in views to search from database according to username.
Models.py</p>

```<code>class menu_details(models.Model):
    restaurant_name = models.CharField(blank=True, max_length=20)
    dish_name = models.CharField(blank=True, max_length=20)
    dish_type = models.CharField(max_length=10, choices=food_type, default='veg')
    price = models.CharField(blank=True, max_length=20)
    description = models.TextField(blank=True, max_length=5000)
    image = models.ImageField0(blank=True)

    class Meta:
        db_table = "menu_details"
</code>```

答:
If you want to have username of already logged in user in a view you can use user object from request:

from .models import menu_details

def my_view(request):
    if request.user.is_authenticated:
        user = request.user # user object from the person who is visiting
        username = user.username # username of logged in user
        menu_details.objects.filter(restaurant_name=username) # getting the menu using restaurant

```

Body:
I am creating a project in django in which I have two diff users i.e. Customers and restaurants. I am creating a model for Menu in which I want add to add user name of logged in user to restaurant name in models. Is there anyway to do this. I have searched through the net got answers like foreign key but not able to implement. Also I need username in views to search from database according to username.
Models.py

class menu_details(models.Model):
    restaurant_name = models.CharField(blank=True, max_length=20)
    dish_name = models.CharField(blank=True, max_length=20)
    dish_type = models.CharField(max_length=10, choices=food_type, default='veg')
    price = models.CharField(blank=True, max_length=20)
    description = models.TextField(blank=True, max_length=5000)
    image = models.ImageField0(blank=True)

    class Meta:
        db_table = "menu_details"


问:
Increment hex string
I'm trying to increment an hex string like this:

```
#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;
```

Here's my procedure:

```<code>var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;
</code>```

Whith this procedure, only the second byte increment.
The result is:

```
#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1
```

Thanks

答:
You have three problems here:

SizeOf(Sequence) is not the length of a sequence.

You defined your sequence type as [0..3], so you need to start the index as 0

endian issues. On little endian machines, even if you'll do the indexes and lengths right, you'll get #$67#$1c#$87#$b1 #$68#$1c#$87#$b1 #$69#$1c#$87#$b1 ... For solution to this problem, see this article

ContentLicense: CC BY-SA 2.5

Title: Increment hex string

Body:
I'm trying to increment an hex string like this:

#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;

Here's my procedure:

var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;

Whith this procedure, only the second byte increment.
The result is:

#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1

Thanks

LastEditorDisplayName: Tomalak

OwnerDisplayName: jpalecek


问:
C: Pipe: How to pass a dynamic int array using pipe correctly
I tried to write a dynamic allocated int array in several child processes, and read them in parent process using pipe, but the result is like [-15236548, 37526, -15236548, 37526,0,0,0,0,0,0], it looks like the addresses are read instead of the real values[1,1,1,1,0,2,1,1,1,1]. I am really struggling in it for the whole day, any help would be greatly appreciated!!!

The child process are 10, they would first write an array each, and after all of them are done, parent process reads the 10 array.

```<code>int *getArr(){
    int * arr1 = malloc(sizeof(int) *100);
    //do something
    return arr1;
}

//write values to pipe
void write_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t wlen = write(fd, p, len);
        if(wlen <= 0)
            exit(0);
        p += wlen;
        len -= wlen;
    }
}

// read values from pipe
void read_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t rlen = read(fd, p, len);
        if(rlen <= 0)
            exit(0);
        p += rlen;
        len -= rlen;
    }
}

// pass values, and get it ready to be wrote
void write_ints(int fd, int *p, int len){
    write_check(fd, p, len * sizeof(*p));
}

// allocate memory for fetching values
void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}

int main(){
    int len = 100;
    int *arr1 = malloc(sizeof(int) * 100);
    int *fds = malloc(sizeof(int) * 10 * 2);

    // child processes write values to pipe
    for(int i=0; i<10; i++){
        child_pid = fork();
        if (child_pid == 0){
            // do something
            arr1 = getArr();
            write_ints(fd[i*2+1], &arr1, len);
        }
    }
    // parent process reads values
    for(int i=0; i<10; i++){
        // do something
        read_ints(fd[i*2], &arr1, len);
    }
}
</code>```

答: expected int * but argument is int ** error is due to passing &arr1 .address of a pointer is a double pointer.just pass arr1 (in both write_ints and read_ints) and you wont get that error.</p>

Body:
I tried to write a dynamic allocated int array in several child processes, and read them in parent process using pipe, but the result is like [-15236548, 37526, -15236548, 37526,0,0,0,0,0,0], it looks like the addresses are read instead of the real values[1,1,1,1,0,2,1,1,1,1]. I am really struggling in it for the whole day, any help would be greatly appreciated!!!

The child process are 10, they would first write an array each, and after all of them are done, parent process reads the 10 array.

int *getArr(){
    int * arr1 = malloc(sizeof(int) *100);
    //do something
    return arr1;
}

//write values to pipe
void write_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t wlen = write(fd, p, len);
        if(wlen <= 0)
            exit(0);
        p += wlen;
        len -= wlen;
    }
}

// read values from pipe
void read_check(int fd, void *buffer, size_t len){
    char *p = buffer;
    while(len>0){
        size_t rlen = read(fd, p, len);
        if(rlen <= 0)
            exit(0);
        p += rlen;
        len -= rlen;
    }
}

// pass values, and get it ready to be wrote
void write_ints(int fd, int *p, int len){
    write_check(fd, p, len * sizeof(*p));
}

// allocate memory for fetching values
void read_ints(int fd, int *p, int len){
    p = malloc(len * sizeof(*p));
    read_check(fd, p, len* sizeof(*p));
}

int main(){
    int len = 100;
    int *arr1 = malloc(sizeof(int) * 100);
    int *fds = malloc(sizeof(int) * 10 * 2);

    // child processes write values to pipe
    for(int i=0; i<10; i++){
        child_pid = fork();
        if (child_pid == 0){
            // do something
            arr1 = getArr();
            write_ints(fd[i*2+1], &arr1, len);
        }
    }
    // parent process reads values
    for(int i=0; i<10; i++){
        // do something
        read_ints(fd[i*2], &arr1, len);
    }
}


问:
Disable Touch of inner RecyclerView
I'm new to RecyclerView and I want to implement OnItemClickListner like Listview. To do this I'm using following code.

```<code>public static class ViewHolder extends RecyclerView.ViewHolder {

    public RecyclerView recyclerView;

    public ViewHolder(View itemView) {
        super(itemView);

        recyclerView = (RecyclerView) itemView.findViewById(R.id.recycleViewIngredient);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //Item Click Listner
            }
        });
    }
}
</code>```

It is working fine. The problem is I have another Recyclerview inside this Recyclerview. If I tap on inner recycler view, Item Click listner for parent view did not respond. I don't wan't to make inner recyclerview clickable.

Any help will be great.

答:
try:</p>

```<code>viewHolder.someInnerRecyclerView.suppressLayout(true);
viewHolder.someInnerRecyclerView.setFocusable(false);
viewHolder.someInnerRecyclerView.setClickable(false);
</code>```

Title: Disable Touch of inner RecyclerView

Body:
I'm new to RecyclerView and I want to implement OnItemClickListner like Listview. To do this I'm using following code.

public static class ViewHolder extends RecyclerView.ViewHolder {

    public RecyclerView recyclerView;

    public ViewHolder(View itemView) {
        super(itemView);

        recyclerView = (RecyclerView) itemView.findViewById(R.id.recycleViewIngredient);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //Item Click Listner
            }
        });
    }
}

It is working fine. The problem is I have another Recyclerview inside this Recyclerview. If I tap on inner recycler view, Item Click listner for parent view did not respond. I don't wan't to make inner recyclerview clickable.

Any help will be great.

Body:
try:

viewHolder.someInnerRecyclerView.suppressLayout(true);
viewHolder.someInnerRecyclerView.setFocusable(false);
viewHolder.someInnerRecyclerView.setClickable(false);


问:
Exclude specific URL from Tomcat ExpiresFilter Cache
Is it possible to exclude a single specific URL from the Tomcat Expires Filter, so that it is not cached by the client Browser?

The file Content-Type is text/javascript (as seen in the browser), compressed as gzip.

It is important that all remaining Javascript files remain cacheable.

This is the default expires filter:

```<code><filter>
   <filter-name>ExpiresFilter</filter-name>
   <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
   <init-param>
      <param-name>ExpiresByType application/javascript</param-name>
      <param-value>access plus 7 day</param-value>
   </init-param>
   ...
</filter>
<filter-mapping>
   <filter-name>ExpiresFilter</filter-name>
   <url-pattern>/*</url-pattern>
   <dispatcher>REQUEST</dispatcher>
</filter-mapping>
</code>```

Here is the new Expires Filter I tried to add in addition to the default Filter:

```<code><filter>
   <filter-name>SecondaryExpiresFilter</filter-name>
   <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
   <init-param>
      <param-name>ExpiresByType text/javascript</param-name>
      <param-value>access plus 1 second</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>SecondaryExpiresFilter</filter-name>
   <url-pattern>/js/session.jsp</url-pattern>
   <dispatcher>REQUEST</dispatcher>
</filter-mapping>
</code>```

The specified request continues to come back with:

```<code>cache-control
"max-age=604800"
</code>```

I also tried the following types:

application/javascript

text/javascript;charset=UTF-8

The latter should, according to the docs, take precedence over the less specific text/javascript

https://tomcat.apache.org/tomcat-8.5-doc/config/filter.html#Expires_Filter

答:
One way to do this is to write your own class which extends ExpiresFilter and override the isEligibleToExpirationHeaderGeneration method, like this:

```<code>@Override
protected boolean isEligibleToExpirationHeaderGeneration(
        HttpServletRequest request, XHttpServletResponse response) {
    if("/my/special/uri".equals(request.getRequestURI())) {
        return false; // Don't do any Expires stuff
    } else {
        return super.isEligibleToExpirationHeaderGeneration(request, response);
    }
}
</code>```

Body:
Is it possible to exclude a single specific URL from the Tomcat Expires Filter, so that it is not cached by the client Browser?

The file Content-Type is text/javascript (as seen in the browser), compressed as gzip.

It is important that all remaining Javascript files remain cacheable.

This is the default expires filter:

<filter>
   <filter-name>ExpiresFilter</filter-name>
   <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
   <init-param>
      <param-name>ExpiresByType application/javascript</param-name>
      <param-value>access plus 7 day</param-value>
   </init-param>
   ...
</filter>
<filter-mapping>
   <filter-name>ExpiresFilter</filter-name>
   <url-pattern>/*</url-pattern>
   <dispatcher>REQUEST</dispatcher>
</filter-mapping>

Here is the new Expires Filter I tried to add in addition to the default Filter:

<filter>
   <filter-name>SecondaryExpiresFilter</filter-name>
   <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
   <init-param>
      <param-name>ExpiresByType text/javascript</param-name>
      <param-value>access plus 1 second</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>SecondaryExpiresFilter</filter-name>
   <url-pattern>/js/session.jsp</url-pattern>
   <dispatcher>REQUEST</dispatcher>
</filter-mapping>

The specified request continues to come back with:

cache-control
"max-age=604800"

I also tried the following types:

application/javascript

text/javascript;charset=UTF-8

The latter should, according to the docs, take precedence over the less specific text/javascript

https://tomcat.apache.org/tomcat-8.5-doc/config/filter.html#Expires_Filter

Body:
One way to do this is to write your own class which extends ExpiresFilter and override the isEligibleToExpirationHeaderGeneration method, like this:

@Override
protected boolean isEligibleToExpirationHeaderGeneration(
        HttpServletRequest request, XHttpServletResponse response) {
    if("/my/special/uri".equals(request.getRequestURI())) {
        return false; // Don't do any Expires stuff
    } else {
        return super.isEligibleToExpirationHeaderGeneration(request, response);
    }
}


问:
How to Stop component to refresh after axios post in react. After uploading image from formData
I am building a blog builder where i need to upload the image as image is selected on onChange event and that url of uploaded image need to be updated in state.

After post request for image upload . Component gets refreshed automatically and selected file and state is also refreshed.

what to do to stop component from refreshing and the setState  to update the correct url of image..

```<code>handleChange = async (event) =>
{
    event.preventDefault();
    if(event.target.name == 'file')
    {

        var x=event.target.files[0]
        var y= event.target.name
        let formData = new FormData();
        formData.append('file',x)
        const response = await axios.post('http://localhost:8009/post/image',formData,{
           headers: {
             'Content-Type': 'multipart/form-data'
          }
        })
        let {data} = await response
        console.log(data)
        let file1 = data.name
        this.setState({
            content:{
                key:uuid(),
                name:y,
                file:file1,
                content:URL.createObjectURL(x)
            }
        })

   }
}
</code>```

The form for Image is as :

```<code><input type="file" name="file" className="form-control-file"  onChange={this.handleChange} required/>
</code>```

Backend on node :

```<code>router.post('/image',(req,res)=>
{
    console.log(req)

    let file = req.files.file;
    filename = Date.now() + '-' + file.name;

    file.mv(`./client/public/uploads/${filename}`, (err)=>{

        if(err) throw err;

    });
    console.log(`/uploads/${filename}`);
    res.json({name:`/uploads/${filename}`})
})
</code>```

答:
I see you're uploading to your local environment. I had a similar issue working with Vue, but then stumbled upon this answer by @fanfare pointing out that if you're using any kind of "hot/live refresh" (in Vue is called Hot Module Reload) and the file is being uploaded in any of the folders the server monitors for changes, then the new file being saved could be the cause of the refresh.

In my case saving the file outside of the monitored folder solved the issue.

Body:
I am building a blog builder where i need to upload the image as image is selected on onChange event and that url of uploaded image need to be updated in state.

After post request for image upload . Component gets refreshed automatically and selected file and state is also refreshed.

what to do to stop component from refreshing and the setState  to update the correct url of image..

handleChange = async (event) =>
{
    event.preventDefault();
    if(event.target.name == 'file')
    {

        var x=event.target.files[0]
        var y= event.target.name
        let formData = new FormData();
        formData.append('file',x)
        const response = await axios.post('http://localhost:8009/post/image',formData,{
           headers: {
             'Content-Type': 'multipart/form-data'
          }
        })
        let {data} = await response
        console.log(data)
        let file1 = data.name
        this.setState({
            content:{
                key:uuid(),
                name:y,
                file:file1,
                content:URL.createObjectURL(x)
            }
        })

   }
}

The form for Image is as :

<input type="file" name="file" className="form-control-file"  onChange={this.handleChange} required/>

Backend on node :

router.post('/image',(req,res)=>
{
    console.log(req)

    let file = req.files.file;
    filename = Date.now() + '-' + file.name;

    file.mv(`./client/public/uploads/${filename}`, (err)=>{

        if(err) throw err;

    });
    console.log(`/uploads/${filename}`);
    res.json({name:`/uploads/${filename}`})
})


问:
Changing bar width when using stat_summary with ggplot
I am using stat_summary in ggplot to plot a bar chart. I would like to change the width of the bars. Usually this is done using the width option. With pre-summarised data and stat="identity it works as expected:

```<code>data <- data.frame(group=rep(c("a","b"), 20), y=rnorm(40,100,50))
se <- function(x, na.rm=T) sd(x, na.rm=na.rm)/sqrt(length(x))
data2 <- cast(data, group ~ ., value="y", c(mean, se))
ggplot(data2, aes(group, mean, ymin=mean-1.96*se, ymax=mean+1.96*se)) +
 geom_bar(stat="identity", width=0.5) + geom_errorbar(width=0, size=2)
</code>```

However, in the same plot on original data using stat_summary, the bars don't change width, while errorbars do:

```<code>ggplot(data, aes(group, y)) + stat_summary(fun.y="mean", geom="bar", width=0.5) +
 stat_summary(fun.data="mean_cl_normal", geom="errorbar", width=0, size=2)
</code>```

Is there a way to change bar width even when using stat_summary?

Since the first example works, this question obviously already has a work-around, however, I would really like to know if there is any way to do it with stat_summary, because I use it a lot and is often more convenient.

Thank you!

答: This issue has been resolved. width now also works with stat_summary and geom="errorbar".

Body:
I am using stat_summary in ggplot to plot a bar chart. I would like to change the width of the bars. Usually this is done using the width option. With pre-summarised data and stat="identity it works as expected:

data <- data.frame(group=rep(c("a","b"), 20), y=rnorm(40,100,50))
se <- function(x, na.rm=T) sd(x, na.rm=na.rm)/sqrt(length(x))
data2 <- cast(data, group ~ ., value="y", c(mean, se))
ggplot(data2, aes(group, mean, ymin=mean-1.96*se, ymax=mean+1.96*se)) +
 geom_bar(stat="identity", width=0.5) + geom_errorbar(width=0, size=2)

However, in the same plot on original data using stat_summary, the bars don't change width, while errorbars do:

ggplot(data, aes(group, y)) + stat_summary(fun.y="mean", geom="bar", width=0.5) +
 stat_summary(fun.data="mean_cl_normal", geom="errorbar", width=0, size=2)

Is there a way to change bar width even when using stat_summary?

Since the first example works, this question obviously already has a work-around, however, I would really like to know if there is any way to do it with stat_summary, because I use it a lot and is often more convenient.

Thank you!


问:
Typescript, I'm curious if it can implement this dynamic type checking
It seems a little out of the ordinary.

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

type Keys = keyof APIS;

/**
 * params: key in Keys + '/' + k in keyof APIS[key]
 */
function getSomething(params: string) {
  //
}

getSomething('user/name');     // yes
getSomething('user/age');      // yes
getSomething('job/address');   // yes
getSomething('job/company');   // yes

getSomething('job/name');      // no
getSomething('user/address');  // no

```

params is a concatenated string, Typescript can do type checking?
Who can provide an idea can also ?

答:
You can do this generically with a path function:

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

const x: APIS = {
  user: {
    name: "n",
    age: 1,
  },
  job: {
    address: "add",
    company: "c"
  }
}

const path2 = <T, K1 extends keyof T>(k1: K1, k2: keyof T[K1], o: T) => o[k1][k2];

console.log(path2('user', 'name', x))
```

<p>But I believe you have to write separate functions for each 'depth' of path, as you need to be able to specify a generic for each. I'm guessing that that there may be a way to get around this (but I can't think of it right now).</p>

<p>I'd suggest you'd be better thinking of ways to further break down what it is you're trying to do:</p>

<pre class="lang-js prettyprint-override"><code>const path = <T>(p: keyof T) => (x: T) => x[p];

const compose2 = <T, U, V>(
    f: (x: U) => V,
    g: (x: T) => U,
) => (x: T) => f(g(x));

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

const x: APIS = {
    user: {
        name: "n",
        age: 1,
    },
    job: {
        address: "add",
        company: "c"
    }
};

const getName = compose2(path('name'), path('user'));
const getCompany = compose2(path('company'), path('job'));

const testA = getName(x);
const testB = getCompany(x);

console.log(testA);
console.log(testB);
</code>```

However in terms of what you'd actually like to do; you're talking about Typescript being able to parse concatenated string literal types; it seems that this is not possible (see this issue). There's a lot of interest, but doesn't seem like much in the way of a solution yet.

Body:
It seems a little out of the ordinary.

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

type Keys = keyof APIS;

/**
 * params: key in Keys + '/' + k in keyof APIS[key]
 */
function getSomething(params: string) {
  //
}

getSomething('user/name');     // yes
getSomething('user/age');      // yes
getSomething('job/address');   // yes
getSomething('job/company');   // yes

getSomething('job/name');      // no
getSomething('user/address');  // no

params is a concatenated string, Typescript can do type checking?
Who can provide an idea can also ?

Body:
You can do this generically with a path function:

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

const x: APIS = {
  user: {
    name: "n",
    age: 1,
  },
  job: {
    address: "add",
    company: "c"
  }
}

const path2 = <T, K1 extends keyof T>(k1: K1, k2: keyof T[K1], o: T) => o[k1][k2];

console.log(path2('user', 'name', x))

But I believe you have to write separate functions for each 'depth' of path, as you need to be able to specify a generic for each. I'm guessing that that there may be a way to get around this (but I can't think of it right now).

I'd suggest you'd be better thinking of ways to further break down what it is you're trying to do:

const path = <T>(p: keyof T) => (x: T) => x[p];

const compose2 = <T, U, V>(
    f: (x: U) => V,
    g: (x: T) => U,
) => (x: T) => f(g(x));

interface APIS {
  user: {
    name: string;
    age: number;
  },
  job: {
    address: string;
    company: string;
  }
}

const x: APIS = {
    user: {
        name: "n",
        age: 1,
    },
    job: {
        address: "add",
        company: "c"
    }
};

const getName = compose2(path('name'), path('user'));
const getCompany = compose2(path('company'), path('job'));

const testA = getName(x);
const testB = getCompany(x);

console.log(testA);
console.log(testB);

However in terms of what you'd actually like to do; you're talking about Typescript being able to parse concatenated string literal types; it seems that this is not possible (see this issue). There's a lot of interest, but doesn't seem like much in the way of a solution yet.


问:
Rust: How to cast from a signed integer type to a larger signed integer type *without* sign extension
Suppose we have an i8 which we want to cast to an i16 without sign extension.

We can't do us a simple as cast, as this will sign extend.

```<code>println!("{:b}", -128i8); // 10000000 <- we want this zero-extended in an i16.
println!("{:b}", -128i8 as i16);  // 1111111110000000 sign extended :(
</code>```

We cannot transmute, because the types are of different size:

```<code>println!("{:b}", unsafe {mem::transmute::<_, i16>(128i8)});
// ^ error[E0512]: cannot transmute between types of different sizes, or dependently-sized types :(
</code>```

The best I've come up with is the following convoluted casting chain:

```<code>println!("{:b}", -128i8 as u8 as u16 as i16); // 10000000 :), but :( because convoluted.
</code>```

The intermediate cast to u8 means that casting up to a u16 will zero-extend instead of sign extend, then casting from u16 to i16 is fine, as the types are the same size and no extension is required.

But there must be a better way? Is there?

答:
Keeping in mind that for this case (printing the number's bits) you can just do the unsigned conversion.

However in general Rust doesn't really like doing implicit conversions, but you can always write

let n : i8 = -128;
let m : i32 = n as u8 as i32;
```

You pretty much can't get better than this in general, as double casting is common in fields like changing pointer's types. Also consider not using unsafe when the operation you are doing can be done safely without downsides (aside from maybe a slight code smell).

Body:
Suppose we have an i8 which we want to cast to an i16 without sign extension.

We can't do us a simple as cast, as this will sign extend.

println!("{:b}", -128i8); // 10000000 <- we want this zero-extended in an i16.
println!("{:b}", -128i8 as i16);  // 1111111110000000 sign extended :(

We cannot transmute, because the types are of different size:

println!("{:b}", unsafe {mem::transmute::<_, i16>(128i8)});
// ^ error[E0512]: cannot transmute between types of different sizes, or dependently-sized types :(

The best I've come up with is the following convoluted casting chain:

println!("{:b}", -128i8 as u8 as u16 as i16); // 10000000 :), but :( because convoluted.

The intermediate cast to u8 means that casting up to a u16 will zero-extend instead of sign extend, then casting from u16 to i16 is fine, as the types are the same size and no extension is required.

But there must be a better way? Is there?

Body:
Keeping in mind that for this case (printing the number's bits) you can just do the unsigned conversion.

However in general Rust doesn't really like doing implicit conversions, but you can always write

let n : i8 = -128;
let m : i32 = n as u8 as i32;

You pretty much can't get better than this in general, as double casting is common in fields like changing pointer's types. Also consider not using unsafe when the operation you are doing can be done safely without downsides (aside from maybe a slight code smell).


问:
What overheads on server-side are there when signing Git commits?
Git provides a way to sign commits using GPG keys. What additional overheads are involved on the git server-side (e.g. GitHub Enterprise, GitLab Self-Managed, etc.) compared to the same commit without signing?

How much more storage is needed per commit? Is it only the GPG key ID that is stored additionally? Or is something else also being stored.

How much more processing is needed per commit? Does git need to perform some resource intensive operation to verify the commits? Or only the GPG key ID is checked?

How much more data is sent over the network when pushing the commits? Only the GPG key ID or something more?

To be a little more concrete, between these examples, how much more overhead is incurred on the server-side?

Example 1 - with signing

git add example.txt
git commit -S -m 'My Commit'
git push
```

<p>Example 2 - without signing</p>

<pre class="lang-sh prettyprint-override"><code>git add example.txt
git commit -m 'My Commit'
git push
</code>```

example.txt (Not sure if this matters though)

```<code>Hello World!
</code>```

答:
I'm fairly confident that all it does is a cryptologic check of some sort.  Since git itself is doing this kind of thing all the time with commit hashes, I can't imagine it's much more overhead.

In fact, at GitLab we've been working on resource consumption and recently reduced memory consumption by quite a bit.  I can't imagine the GPG signing processes make a significant impact on resource utilization - but I could be wrong.

Body:
Git provides a way to sign commits using GPG keys. What additional overheads are involved on the git server-side (e.g. GitHub Enterprise, GitLab Self-Managed, etc.) compared to the same commit without signing?

How much more storage is needed per commit? Is it only the GPG key ID that is stored additionally? Or is something else also being stored.

How much more processing is needed per commit? Does git need to perform some resource intensive operation to verify the commits? Or only the GPG key ID is checked?

How much more data is sent over the network when pushing the commits? Only the GPG key ID or something more?

To be a little more concrete, between these examples, how much more overhead is incurred on the server-side?

Example 1 - with signing

git add example.txt
git commit -S -m 'My Commit'
git push

Example 2 - without signing

git add example.txt
git commit -m 'My Commit'
git push

example.txt (Not sure if this matters though)

Hello World!


问:
React Native: What is the difference between calling props.aFunction and props.aFunction() with parenthesis?
This TouchableOpacity component: <TouchableOpacity onPress={props.goToDetails()}> takes props from its parent function, in this code, when calling the function goToDetails my code only works and shows the right results when using parenthesis, while sometimes when I just use the name of the function -in the class-, the code works fine without parenthesis: onPress={this.goToDetails}.
This is the full code,

In the class:

```<code>render(){
  return (
   <View>
     <MovieList results ={this.state.searchResults} goToDetails={()=>this.goToDetails} />
   </View>
)}

goToDetails=()=>{
    this.props.navigation.navigate('Details')
  }
</code>```

Independent function:

```<code>const MovieList = props =>{
const renderItem = ({item}) =>(
    <TouchableOpacity onPress={props.goToDetails()}>
        <Image source={{uri:`http://img.omdbapi.com/?apikey=&`}} style={{height:200, width:200}} />
        <Text>Title: {item.Title}</Text>
    </TouchableOpacity>)

return (<FlatList style={{flex:1}} renderItem={renderItem} data={props.results}  />) }
</code>```

UPDATE:
The class calling MovieList code, the TouhcableOpacity code

答:
You pass goToDetails callback inconsistently.

When you goToDetails={()=>this.goToDetails} this is a callback that returns a function, so in Movielist when it's attached to a handler as onPress={props.goToDetails()} it needs to be invoked immediately in order to get the returned function in order to again have a signature of onPress={callbackFn} or onPress={e => callbackFn(e)}.

```<code>render(){
  return (
   <View>
     <MovieList
       results={this.state.searchResults}
       goToDetails={this.goToDetails} /> // Pass callback as reference
   </View>
)}

goToDetails=()=>{
  this.props.navigation.navigate('Details')
}
</code>```

MovieList

```<code>const MovieList = ({ goToDetails }) =>{
  const renderItem = ({ item }) =>(
    <TouchableOpacity onPress={goToDetails}> // Attach callback to event handler
      <Image
        source={{ uri:`http://img.omdbapi.com/?apikey=&` }}
        style={{ height:200, width:200 }}
      />
      <Text>Title: {item.Title}</Text>
    </TouchableOpacity>
  );

  return (
    <FlatList
      style={{ flex:1 }}
      renderItem={renderItem}
      data={props.results}
    />
  );
}
</code>```

Body:
This TouchableOpacity component: <TouchableOpacity onPress={props.goToDetails()}> takes props from its parent function, in this code, when calling the function goToDetails my code only works and shows the right results when using parenthesis, while sometimes when I just use the name of the function -in the class-, the code works fine without parenthesis: onPress={this.goToDetails}.
This is the full code,

In the class:

render(){
  return (
   <View>
     <MovieList results ={this.state.searchResults} goToDetails={()=>this.goToDetails} />
   </View>
)}

goToDetails=()=>{
    this.props.navigation.navigate('Details')
  }

Independent function:

const MovieList = props =>{
const renderItem = ({item}) =>(
    <TouchableOpacity onPress={props.goToDetails()}>
        <Image source={{uri:`http://img.omdbapi.com/?apikey=&`}} style={{height:200, width:200}} />
        <Text>Title: {item.Title}</Text>
    </TouchableOpacity>)

return (<FlatList style={{flex:1}} renderItem={renderItem} data={props.results}  />) }

UPDATE:
The class calling MovieList code, the TouhcableOpacity code

Body:
You pass goToDetails callback inconsistently.

When you goToDetails={()=>this.goToDetails} this is a callback that returns a function, so in Movielist when it's attached to a handler as onPress={props.goToDetails()} it needs to be invoked immediately in order to get the returned function in order to again have a signature of onPress={callbackFn} or onPress={e => callbackFn(e)}.

render(){
  return (
   <View>
     <MovieList
       results={this.state.searchResults}
       goToDetails={this.goToDetails} /> // Pass callback as reference
   </View>
)}

goToDetails=()=>{
  this.props.navigation.navigate('Details')
}

MovieList

const MovieList = ({ goToDetails }) =>{
  const renderItem = ({ item }) =>(
    <TouchableOpacity onPress={goToDetails}> // Attach callback to event handler
      <Image
        source={{ uri:`http://img.omdbapi.com/?apikey=&` }}
        style={{ height:200, width:200 }}
      />
      <Text>Title: {item.Title}</Text>
    </TouchableOpacity>
  );

  return (
    <FlatList
      style={{ flex:1 }}
      renderItem={renderItem}
      data={props.results}
    />
  );
}


问:
MongoDB transactions clarification
So starting from 4.0 version MongoDB supports multi-document transaction and one thing I can not find answer to is the following. If i have a replica set consisting of a PRIMARY and SECONDARY instance on the SAME server, what would happen if an unexpected shutdown on the server or on the MongoDB instances occurs, while a transaction is running (for example the server shuts down in the middle of the transaction)? What would happen with the data after the shutdown and after I start the MongoDB instances again? I have tried replicating this where in the middle of a transaction my code executes a terminal script to stop both mongodb services, but I have the feeling there is a better way to replicate this scenario. The results I got from this test were  inconclusive. Thanks in advance !!! </p>

答: If the server process dies while there are in progress transactions, when the process starts again it should go through these transactions and abort them. Any data written as part of those transactions will be discarded.</p>

Title: MongoDB transactions clarification


问:
How to convert MERN app to mobile app using any framework
I enjoy MERN development and I actually prefer it to Meteor, etc.

With Meteor however, it is pretty convenient to convert the website into a mobile app with a few commands.

I was wondering if there is anyway to convert a MERN website into a mobile app using one of the "wrappers" available like PhoneGap, etc.?

What options do I have?
What do you suggest?

答: You could try using "Cordova" of Apache which is a mobile application development framework. This will help you port the web application to different mobile platform.</p>


问:
Same code but different results, how is it possible?
I have wrote matlab's code to python code, but it gives different "best_fitness" value, how is this possible? I want to write this matlab code to python, is it wrong method? Should i implement different method? matlabs best_fitness value is= 340, pytons best_fitness value= 17 ? how is this possible?
Here is python version.

```<code>import numpy as np
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.8 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
MR=0.5
MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)

population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
             fitness[0][i]=0
             for j in range(city-1):
                 # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
                 fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
                 fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
                 if best_fitness > fitness[0][i]:
                     best_solution=population[i][:]
                     best_fitness=fitness[0][i]

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.

</code>```

here is matlab version.

```<code>clc
clear
coord=[11 47 62;
       31 37 69;
       32 38 46;
       33 46 10;
       34 61 33;
       35 62 63;
       36 63 69;
       37 32 22;
       38 45 35;
       39 59 15;
       40 5 6;
       41 10 17;
       42 21 10;
       43 5 64;
       44 30 15;
       45 39 10;
       46 32 39;
       47 25 32;
       48 25 55;
       49 48 28;
       50 56 37;
       61 40 50];

  [city,~]=size(coord);

     best_solution=[];

   best_fitness=100000000;
 pop_size=1000;
  CR=0.8; %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
 MR=0.5;

  MaxIter=5000;

 %51x51 matriste her şehirden şehire uzaklıgı bul
   distance=[];
   for i=1:city
       for j=1:city
           distance(i,j)=sqrt((coord(i,2)-coord(j,2))^2+(coord(i,3)-coord(j,3))^2);
       end
   end
   %rastgele 100 tane cozum olusturdu.
   population=[];
for i=1:pop_size
    population(i,:)=randperm(city);
end
 %population

 for i=1:pop_size
    fitness(i)=0; %başta bos olusturuyor dikkat.
    for j=1:city-1
        %dk 32:48
        %mesela 14 ile 22. sutunun arasındaki mesafe
        %j+1 var diye city -1 yazdık.
        %sırayla 2 sehir arasındaki mesafe hesaplanıyor.

        fitness(i)=fitness(i)+distance(population(i,j),population(i,j+1));
    end
    %son sehirden bastaki sehire donme icin.
    fitness(i)=fitness(i)+distance(population(i,city),population(i,1));
    if  best_fitness>fitness(i)  %fitness(i)<best_fitness
        best_solution=population(i,:);
        best_fitness=fitness(i);
    end
 end

</code>```

答:
The best fitness is going to change in every iteration due to the random generation involved (randperm and np.random.permutation). But you are right that the Python script generates numbers around 10-20 whilst Matlab is in the hundreds.

in your python script your are calling:

fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]

in the same for loop, this doesnt happen in the Matlab script, remove an indentation in the python script like the following:

```<code>import numpy as np
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.8 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
MR=0.5
MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)
#print(distance)
population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
    fitness[0][i]=0
    for j in range(city-1):
        # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
        fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
    fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
    if best_fitness > fitness[0][i]:
        best_solution=population[i][:]
        best_fitness=fitness[0][i]

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.
</code>```

Body:
I have wrote matlab's code to python code, but it gives different "best_fitness" value, how is this possible? I want to write this matlab code to python, is it wrong method? Should i implement different method? matlabs best_fitness value is= 340, pytons best_fitness value= 17 ? how is this possible?
Here is python version.

import numpy as np
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.8 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
MR=0.5
MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)

population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
             fitness[0][i]=0
             for j in range(city-1):
                 # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
                 fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
                 fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
                 if best_fitness > fitness[0][i]:
                     best_solution=population[i][:]
                     best_fitness=fitness[0][i]

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.

here is matlab version.

clc
clear
coord=[11 47 62;
       31 37 69;
       32 38 46;
       33 46 10;
       34 61 33;
       35 62 63;
       36 63 69;
       37 32 22;
       38 45 35;
       39 59 15;
       40 5 6;
       41 10 17;
       42 21 10;
       43 5 64;
       44 30 15;
       45 39 10;
       46 32 39;
       47 25 32;
       48 25 55;
       49 48 28;
       50 56 37;
       61 40 50];

  [city,~]=size(coord);

     best_solution=[];

   best_fitness=100000000;
 pop_size=1000;
  CR=0.8; %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
 MR=0.5;

  MaxIter=5000;

 %51x51 matriste her şehirden şehire uzaklıgı bul
   distance=[];
   for i=1:city
       for j=1:city
           distance(i,j)=sqrt((coord(i,2)-coord(j,2))^2+(coord(i,3)-coord(j,3))^2);
       end
   end
   %rastgele 100 tane cozum olusturdu.
   population=[];
for i=1:pop_size
    population(i,:)=randperm(city);
end
 %population

 for i=1:pop_size
    fitness(i)=0; %başta bos olusturuyor dikkat.
    for j=1:city-1
        %dk 32:48
        %mesela 14 ile 22. sutunun arasındaki mesafe
        %j+1 var diye city -1 yazdık.
        %sırayla 2 sehir arasındaki mesafe hesaplanıyor.

        fitness(i)=fitness(i)+distance(population(i,j),population(i,j+1));
    end
    %son sehirden bastaki sehire donme icin.
    fitness(i)=fitness(i)+distance(population(i,city),population(i,1));
    if  best_fitness>fitness(i)  %fitness(i)<best_fitness
        best_solution=population(i,:);
        best_fitness=fitness(i);
    end
 end

Body:
The best fitness is going to change in every iteration due to the random generation involved (randperm and np.random.permutation). But you are right that the Python script generates numbers around 10-20 whilst Matlab is in the hundreds.

in your python script your are calling:

fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]

in the same for loop, this doesnt happen in the Matlab script, remove an indentation in the python script like the following:

import numpy as np
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.8 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
MR=0.5
MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)
#print(distance)
population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
    fitness[0][i]=0
    for j in range(city-1):
        # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
        fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
    fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
    if best_fitness > fitness[0][i]:
        best_solution=population[i][:]
        best_fitness=fitness[0][i]

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.