问:
Compare 7 input numbers with 7 Random Numbers
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..</p>

```<code>List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}
</code>```

答:
Try this tested and working example. If you run this method execRandomNumber();
You will get this output ::

The numbers returned are 18

The numbers matching are 18

The numbers returned are 15

The numbers matching are 15

The numbers returned are 17

The numbers returned are 19

The numbers matching are 19

The numbers returned are 16

The numbers matching are 16

The numbers returned are 14

The numbers returned are 20

Using directives ::

```<code>using System.Collections.Generic;
</code>```

Declarations ::

```<code>        public static List<int> lista1 = new List<int>();
        public static List<int> returnedRandomList = new List<int>();
        public static int[] myArrNums = new[] { 12, 25, 15, 16, 18, 19 };
        public static int[] myRandArr = new[] { 14, 15, 16, 17, 18, 19, 20 };
</code>```

Method 1 is for if you need to generate the random numbers ::

```<code>private void execRandomNumber()
{
    //==============Don't have the numbers but need to generate them?==============
    returnedRandomList = Gen(returnedRandomList, null);
    returnedRandomList.ForEach(delegate (int num)
    {
        Console.WriteLine(string.Concat("The numbers returned are ", num));
        if (numIsMatch(num) == true)
        {
            lista1.Add(num);
            Console.WriteLine(string.Concat("The numbers matching are ", num));
        }
    });
    //==============Generator will return list of random numbers, then we compared them==============
}
</code>```

Your number generator ::

```<code>    //==============Your number generator==============
    private List<int> Gen(List<int> randGenerator, Random ranNum)
    {
        ranNum = new Random();
        var rn = 0;
        returnedRandomList.Clear();
        do
        {
            if (randGenerator.Count == 7)
                    break;
            rn = ranNum.Next(14, 21);
            if (!(randGenerator.Contains(rn)) && randGenerator.Count <= 7)
                randGenerator.Add(rn);
        }
        while (randGenerator.Count <= 7);
        return randGenerator;
    }
</code>```

And for method two, assuming you have the numbers already generated and stored in a list or array of numbers, you can do the following ::

```<code>private void runArgs()
{
    //==============Already have the numbers? Loop through them and compare==============
    foreach (int i in myRandArr)
    {
        if (numIsMatch(i) == true)
        {
            lista1.Add(i);
        }
    }
    lista1.ForEach(delegate (int num)
    {
        Console.WriteLine(string.Concat("The numbers that match are ", num));
    });
}
</code>```

And to compare your numbers to see if they are a match, you could do something like this ::

```<code>//==============Check is numbers are a match==============
private bool numIsMatch(int inValue)
{
    foreach (int ii in myArrNums)
    {
        if (ii.Equals(inValue))
            return true;
        else
            continue;
    }
    return false;
}
</code>```

If you have any questions, I will get back to you tomorrow as it is rather late here now. Hope this helps.

Body:
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..

List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}

Body:
Try this tested and working example. If you run this method execRandomNumber();
You will get this output ::

The numbers returned are 18

The numbers matching are 18

The numbers returned are 15

The numbers matching are 15

The numbers returned are 17

The numbers returned are 19

The numbers matching are 19

The numbers returned are 16

The numbers matching are 16

The numbers returned are 14

The numbers returned are 20

Using directives ::

using System.Collections.Generic;

Declarations ::

        public static List<int> lista1 = new List<int>();
        public static List<int> returnedRandomList = new List<int>();
        public static int[] myArrNums = new[] { 12, 25, 15, 16, 18, 19 };
        public static int[] myRandArr = new[] { 14, 15, 16, 17, 18, 19, 20 };

Method 1 is for if you need to generate the random numbers ::

private void execRandomNumber()
{
    //==============Don't have the numbers but need to generate them?==============
    returnedRandomList = Gen(returnedRandomList, null);
    returnedRandomList.ForEach(delegate (int num)
    {
        Console.WriteLine(string.Concat("The numbers returned are ", num));
        if (numIsMatch(num) == true)
        {
            lista1.Add(num);
            Console.WriteLine(string.Concat("The numbers matching are ", num));
        }
    });
    //==============Generator will return list of random numbers, then we compared them==============
}

Your number generator ::

    //==============Your number generator==============
    private List<int> Gen(List<int> randGenerator, Random ranNum)
    {
        ranNum = new Random();
        var rn = 0;
        returnedRandomList.Clear();
        do
        {
            if (randGenerator.Count == 7)
                    break;
            rn = ranNum.Next(14, 21);
            if (!(randGenerator.Contains(rn)) && randGenerator.Count <= 7)
                randGenerator.Add(rn);
        }
        while (randGenerator.Count <= 7);
        return randGenerator;
    }

And for method two, assuming you have the numbers already generated and stored in a list or array of numbers, you can do the following ::

private void runArgs()
{
    //==============Already have the numbers? Loop through them and compare==============
    foreach (int i in myRandArr)
    {
        if (numIsMatch(i) == true)
        {
            lista1.Add(i);
        }
    }
    lista1.ForEach(delegate (int num)
    {
        Console.WriteLine(string.Concat("The numbers that match are ", num));
    });
}

And to compare your numbers to see if they are a match, you could do something like this ::

//==============Check is numbers are a match==============
private bool numIsMatch(int inValue)
{
    foreach (int ii in myArrNums)
    {
        if (ii.Equals(inValue))
            return true;
        else
            continue;
    }
    return false;
}

If you have any questions, I will get back to you tomorrow as it is rather late here now. Hope this helps.


来源: stackexchange

问:
Bash get the command that is piping into a script
Take the following example:

```<code>ls -l | grep -i readme | ./myscript.sh
</code>```

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

答:
I think you should pass it as one string parameter like this</p>

```<code>./myscript.sh "$(ls -l | grep -i readme)"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Take the following example:

ls -l | grep -i readme | ./myscript.sh

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

Body:
I think you should pass it as one string parameter like this

./myscript.sh "$(ls -l | grep -i readme)"


问:
Synchronous and asynchronous vs callback in mongoose
hi guys i am new in node and have this simple question , what is difference between this two sniped

Note: i know async / await functionality and also in front-end application it is best practice for handle async action but in node in working with mongoose i want know which approach better for handle

first solution

```<code>// for example we pass this function as controller to route handler

exports.myController = async (req, res, next) => {

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {

    next(e);
 }
}

</code>```

second solution

```<code>exports.myController = (req, res, next) => {

 const data = Model.find((err, data_) => {

  const some = new Model(data_);
  some.save((err, result) => {
  ....
})

});

}

</code>```

i want to know when i have an error from mongoose , in second way can throw error like this

```<code>// in callback function

if (err) {

throw Error();

}

</code>```

but how can i handle this in async/await solution

答:
you simply throw it or log it in your catch block:

```<code>try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {
     throw e;
     next(e);
 }
</code>```

the async/await is working like promises but without no nesting callbacks and it throws an error synchronous to what errors first and stop from executing the other lines.

Based in your edited Note:

you should always go for the async solution way in nodejs or even for anything related to javascript it's the best composable and reusable solution.

Body:
hi guys i am new in node and have this simple question , what is difference between this two sniped

Note: i know async / await functionality and also in front-end application it is best practice for handle async action but in node in working with mongoose i want know which approach better for handle

first solution

// for example we pass this function as controller to route handler

exports.myController = async (req, res, next) => {

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {

    next(e);
 }
}

second solution

exports.myController = (req, res, next) => {

 const data = Model.find((err, data_) => {

  const some = new Model(data_);
  some.save((err, result) => {
  ....
})

});

}

i want to know when i have an error from mongoose , in second way can throw error like this

// in callback function

if (err) {

throw Error();

}

but how can i handle this in async/await solution

Body:
you simply throw it or log it in your catch block:

try {
     const data = await Model.find();
     const some = await new Model(data).save();
   } catch(e) {
     throw e;
     next(e);
 }

the async/await is working like promises but without no nesting callbacks and it throws an error synchronous to what errors first and stop from executing the other lines.

Based in your edited Note:

you should always go for the async solution way in nodejs or even for anything related to javascript it's the best composable and reusable solution.


问:
MemoryError: Cannot allocate memory -- BDB2034 unable to allocate memory for mutex; resize mutex region
I've created a database based on turtle file (of size ~4.5Gb) using rdflib and started querying it using SPARQL, everything was working smoothly, but after a while I start getting this error:

MemoryError: (12, 'Cannot allocate memory -- BDB2034 unable to allocate memory for mutex; resize mutex region')

The full output:

```<code>File "/usr/local/lib/python3.6/site-packages/rdflib/graph.py", line 377, in open
    return self.__store.open(configuration, create)
  File "/usr/local/lib/python3.6/site-packages/rdflib/plugins/sleepycat.py", line 167, in open
    self.__namespace.open("namespace", dbname, dbtype, dbopenflags, dbmode)
MemoryError: (12, 'Cannot allocate memory -- BDB2034 unable to allocate memory for mutex; resize mutex region')
</code>```

The minimal script:

```<code>from rdflib import ConjunctiveGraph, Namespace, Literal
from rdflib.store import NO_STORE, VALID_STORE

db_path = "my_db"
g = ConjunctiveGraph('Sleepycat')
# Open the DB
g.open(db_path, create=False) # <--- this line causes the error
</code>```

I don't know the cause of the problem, I checked out if I have enough RAM, CPU usage and disk space, everything was OK, I restarted the PC but the error persisted.

答:
From the database directory, run the next command in console:

> db_recover
```

This is a temporary solution, as after some time the error rises again.

Body:
I've created a database based on turtle file (of size ~4.5Gb) using rdflib and started querying it using SPARQL, everything was working smoothly, but after a while I start getting this error:

MemoryError: (12, 'Cannot allocate memory -- BDB2034 unable to allocate memory for mutex; resize mutex region')

The full output:

File "/usr/local/lib/python3.6/site-packages/rdflib/graph.py", line 377, in open
    return self.__store.open(configuration, create)
  File "/usr/local/lib/python3.6/site-packages/rdflib/plugins/sleepycat.py", line 167, in open
    self.__namespace.open("namespace", dbname, dbtype, dbopenflags, dbmode)
MemoryError: (12, 'Cannot allocate memory -- BDB2034 unable to allocate memory for mutex; resize mutex region')

The minimal script:

from rdflib import ConjunctiveGraph, Namespace, Literal
from rdflib.store import NO_STORE, VALID_STORE

db_path = "my_db"
g = ConjunctiveGraph('Sleepycat')
# Open the DB
g.open(db_path, create=False) # <--- this line causes the error

I don't know the cause of the problem, I checked out if I have enough RAM, CPU usage and disk space, everything was OK, I restarted the PC but the error persisted.

Body:
From the database directory, run the next command in console:

> db_recover

This is a temporary solution, as after some time the error rises again.


问:
Is it possible to start counting from a specific div in Python using XPATH and Selenium?
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

```<code><div class="container">
    ... # dots signify the divs before it
    <div class="24">
        <div class="25"></div>
        <div class="26"></div>
    </div>
    <div class="27">
        <div class="28"></div>
        <div class="29"></div>
    </div>
    <div class="30">
        <div class="31"></div>
        <div class="32"></div>
    </div>
    ... # divs after it
</div>
</code>```

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1
```

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

答:
It turns out that you need to be in the node you want to have the sibling of (if you want to have the siblings of class="24", you need to be inside the node of class="24".

i.e.

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]/following-sibling::*"))
        print(len(divs_under_x))
        break
    x += 1

```

This will print out how many divs are under class="24" except its children.

Body:
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

    ... # dots signify the divs before it

    ... # divs after it

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

Body:
It turns out that you need to be in the node you want to have the sibling of (if you want to have the siblings of class="24", you need to be inside the node of class="24".

i.e.

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]/following-sibling::*"))
        print(len(divs_under_x))
        break
    x += 1

This will print out how many divs are under class="24" except its children.


问:
How do I accept a literal "*" as a command-line argument?
I am writing a very simple command line calculator in rust, getting a number ,an operator, then another number and do the calculation and print the result. To show what I am getting from command args, I have printed them in a loop before the main code. I works fine for plus, minus and division, but for multiplication I get unexpected result, as I print it, instead of a star (*) for multiplication, I get the files list on my current directory.
Here is my rust code, I will appreciate an explanation and if there is any workaround.</p>

```<code>use std::env;

fn main(){
    let args: Vec<String> = env::args().collect();

    for arg in args.iter(){
        println!("{}", arg);
    }

    let mut result = 0;
    let opt = args[2].to_string();
    let oper1 = args[1].parse::<i32>().unwrap();
    let oper2 = args[3].parse::<i32>().unwrap();
    match opt.as_ref(){
        "+" => result = oper1 + oper2,
        "-" => result = oper1 - oper2,
        "*" => result = oper1 * oper2,
        "/" => result = oper1 / oper2,
        _ => println!("Error")
    }

    println!("{} {} {} = {}", oper1, opt, oper2, result);

}
</code>```

答:
The wildcard (*) is expanding out. The shell is going to send this out to the program before it even sees what you actually typed

You can read more about here.

To avoid this, you can just wrap it in quotes, like so:

```<code>./program 1 "*" 1
</code>```

Body:
I am writing a very simple command line calculator in rust, getting a number ,an operator, then another number and do the calculation and print the result. To show what I am getting from command args, I have printed them in a loop before the main code. I works fine for plus, minus and division, but for multiplication I get unexpected result, as I print it, instead of a star (*) for multiplication, I get the files list on my current directory.
Here is my rust code, I will appreciate an explanation and if there is any workaround.

use std::env;

fn main(){
    let args: Vec<String> = env::args().collect();

    for arg in args.iter(){
        println!("{}", arg);
    }

    let mut result = 0;
    let opt = args[2].to_string();
    let oper1 = args[1].parse::<i32>().unwrap();
    let oper2 = args[3].parse::<i32>().unwrap();
    match opt.as_ref(){
        "+" => result = oper1 + oper2,
        "-" => result = oper1 - oper2,
        "*" => result = oper1 * oper2,
        "/" => result = oper1 / oper2,
        _ => println!("Error")
    }

    println!("{} {} {} = {}", oper1, opt, oper2, result);

}

Body:
The wildcard (*) is expanding out. The shell is going to send this out to the program before it even sees what you actually typed

You can read more about here.

To avoid this, you can just wrap it in quotes, like so:

./program 1 "*" 1


问:
I cannot solve "segmentation fault: 11"
I am studying the book , 2nd edition. I wrote the code in the book as below and compiled it but it is not working. The message "Segamentation fault: 11" is shown on my terminal.

Last time I had a similar problem and I solve it by adding '\0' at the end of the array. But this time I cannot know where the problem started.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define MAXWORD 100
#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getword(char *, int);
struct key *binsearch(char *, struct key *, int);
struct tnode *addtree(struct tnode *, char *);
struct tnode *talloc(void);
char *strdupH(char *);
void treeprint(struct tnode *);

struct key {
    char *word;
    int count;
};

struct key keytab[] = {
    "auto", 0,
    "break", 0,
    "case", 0,
    "char", 0,
    "const", 0,
    "continue", 0,
    "default", 0,
    "unsigned", 0,
    "void", 0,
    "volatile", 0,
    "while", 0
};

struct tnode {              /* the tree node */
    char *word;             /* points to the text */
    int count;              /* number of occurences */
    struct tnode *left;     /* left child */
    struct tnode *right;    /* right child */
};
// It is illegal for a structure to contain an instance of itself.
// struct tnode *left
// declares left to be a pointer to a tnode, not tnode itself

//
//  6_5SelfReferentialStructures.c
//
//
//  Created by Damian on 26/05/2019.
//

/* getword: get next word or character from input */
int getword(char *word, int lim)
{
    int c, getchH(void);
    void ungetchH(int);
    char *w = word;

    while (isspace(c = getchH()))
        ;
    if (c != EOF)
        *w++ = c;
    if (!isalpha(c)) {
        *w = '\0';
        return c;
    }
    for ( ; --lim > 0; w++)
        if (!isalnum(*w = getchH())) {
            ungetchH(*w);
            break;
        }
    *w = '\0';
    return word[0];
}

int getchH(void) /* get a (possibly pushed back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetchH(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

/* word frequency count */
int main(int argc, char *argv[])
{
    struct tnode *root;
    char word[MAXWORD];

    root = NULL;
    while (getword(word, MAXWORD) != EOF)
        if (isalpha(word[0])) {
            root = addtree(root, word);
        }
    treeprint(root);
    return 0;
}

/* addtree: add a node with w, at or below p */
struct tnode *addtree(struct tnode *p, char *w)
{
    int cond;
    if ((p = NULL)) {
        p = talloc();       /* make a new node */
        p->word = strdupH(w);
        p->count = 1;
        p->left = p->right = NULL;
    } else if ((cond = strcmp(w, p->word)) == 0)
        p->count++;         /* repeated word */
    else if (cond < 0)      /* less than into left subtree */
        p->left = addtree(p->left, w);
    else                    /* greater than into right substree */
        p->right = addtree(p->right, w);
    return p;
}

/* treeprint: in-order print of tree p */
void treeprint(struct tnode *p)
{
    if (!p) {
        treeprint(p->left);
        printf("%4d %s\n", p->count, p->word);
        treeprint(p->right);
    }

    return;
}

/* talloc: make a tnode */
struct tnode *talloc(void)
{
    return (struct tnode *) malloc(sizeof(struct tnode));
}

char *strdupH(char *s) /* make a duplicate of s */
{
    char *p;

    p = (char *) malloc(strlen(s) + 1); /* +1 for '\0' */
    if (p != NULL)
        strcpy(p, s);
    return p;
}
```

<p>The result of the above code is:</p>

```damian@James:~/t2/t2$ cc main.c -o main
damian@James:~/t2/t2$ ./main
Can you help me?
Segmentation fault: 11
```

Thanks for your time.

答:
your segmentation fault comes from the line

```<code>if ((p = NULL))
</code>```

it should be

```<code>if (p == NULL)
</code>```

Title: I cannot solve "segmentation fault: 11"

Body:
I am studying the book , 2nd edition. I wrote the code in the book as below and compiled it but it is not working. The message "Segamentation fault: 11" is shown on my terminal.

Last time I had a similar problem and I solve it by adding '\0' at the end of the array. But this time I cannot know where the problem started.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

#define MAXWORD 100
#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getword(char *, int);
struct key *binsearch(char *, struct key *, int);
struct tnode *addtree(struct tnode *, char *);
struct tnode *talloc(void);
char *strdupH(char *);
void treeprint(struct tnode *);

struct key {
    char *word;
    int count;
};

struct key keytab[] = {
    "auto", 0,
    "break", 0,
    "case", 0,
    "char", 0,
    "const", 0,
    "continue", 0,
    "default", 0,
    "unsigned", 0,
    "void", 0,
    "volatile", 0,
    "while", 0
};

struct tnode {              /* the tree node */
    char *word;             /* points to the text */
    int count;              /* number of occurences */
    struct tnode *left;     /* left child */
    struct tnode *right;    /* right child */
};
// It is illegal for a structure to contain an instance of itself.
// struct tnode *left
// declares left to be a pointer to a tnode, not tnode itself

//
//  6_5SelfReferentialStructures.c
//
//
//  Created by Damian on 26/05/2019.
//

/* getword: get next word or character from input */
int getword(char *word, int lim)
{
    int c, getchH(void);
    void ungetchH(int);
    char *w = word;

    while (isspace(c = getchH()))
        ;
    if (c != EOF)
        *w++ = c;
    if (!isalpha(c)) {
        *w = '\0';
        return c;
    }
    for ( ; --lim > 0; w++)
        if (!isalnum(*w = getchH())) {
            ungetchH(*w);
            break;
        }
    *w = '\0';
    return word[0];
}

int getchH(void) /* get a (possibly pushed back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetchH(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

/* word frequency count */
int main(int argc, char *argv[])
{
    struct tnode *root;
    char word[MAXWORD];

    root = NULL;
    while (getword(word, MAXWORD) != EOF)
        if (isalpha(word[0])) {
            root = addtree(root, word);
        }
    treeprint(root);
    return 0;
}

/* addtree: add a node with w, at or below p */
struct tnode *addtree(struct tnode *p, char *w)
{
    int cond;
    if ((p = NULL)) {
        p = talloc();       /* make a new node */
        p->word = strdupH(w);
        p->count = 1;
        p->left = p->right = NULL;
    } else if ((cond = strcmp(w, p->word)) == 0)
        p->count++;         /* repeated word */
    else if (cond < 0)      /* less than into left subtree */
        p->left = addtree(p->left, w);
    else                    /* greater than into right substree */
        p->right = addtree(p->right, w);
    return p;
}

/* treeprint: in-order print of tree p */
void treeprint(struct tnode *p)
{
    if (!p) {
        treeprint(p->left);
        printf("%4d %s\n", p->count, p->word);
        treeprint(p->right);
    }

    return;
}

/* talloc: make a tnode */
struct tnode *talloc(void)
{
    return (struct tnode *) malloc(sizeof(struct tnode));
}

char *strdupH(char *s) /* make a duplicate of s */
{
    char *p;

    p = (char *) malloc(strlen(s) + 1); /* +1 for '\0' */
    if (p != NULL)
        strcpy(p, s);
    return p;
}

The result of the above code is:

damian@James:~/t2/t2$ cc main.c -o main
damian@James:~/t2/t2$ ./main
Can you help me?
Segmentation fault: 11

Thanks for your time.

Body:
your segmentation fault comes from the line

if ((p = NULL))

it should be

if (p == NULL)


问:
Search text in fields in every table of a MySQL database
I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

```<code>SELECT * FROM * WHERE * LIKE '%stuff%'
</code>```

Is it possible to do something like this?

答:
I have done this using HeidiSQL.
It's not easy to find but by pressing Ctrl+Shift+F it displays the "table tools" dialogue. Then select what you want to search (Full database to single table) and enter the "Text to find" value and click "Find". I found it surprisingly fast (870MiB db in less than a minute)</p>

OwnerDisplayName: Armadillo

Body:
I want to search in all fields from all tables of a MySQL database a given string, possibly using syntax as:

SELECT * FROM * WHERE * LIKE '%stuff%'

Is it possible to do something like this?

LastEditorDisplayName: Ólafur Waage


问:
How to locate element in selenium for href
I am trying to locate the element for this:

```<code><a ng-if="showLink && customer.partnerType == 2 && customer.isDirectCustomer" class="cp_text_link ng-binding ng-scope" ng-href="/?orgId=77bc101729ad844e39c4c1e17231c7e4&orgName=Attunix" href="/?orgId=77bc101729ad844e39c4c1e17231c7e4&orgName=ABC">
  ABC
</a>
</code>```

I tried the XPath and CssSelector but its unable to locate element.
Can someone pls help me locate the element
TIA

答:
Try using class
driver.findElement(By.cssSelector("a.cp_text_link"))</p>

Body:
I am trying to locate the element for this:

  ABC

I tried the XPath and CssSelector but its unable to locate element.
Can someone pls help me locate the element
TIA


问:
Dtls client doesn't send ClientHello with cookie
I'm implementing dtls support for my sip client, using openssl. My SSL_connect returns SSL_ERROR_WANT_READ, my 'select' to handle it always timeout. In wireshark I saw a first ClientHello and HelloVerifyRequest, but second ClientHello with cookie never came.</p>

答: it turns out that there was another socket listening on the same port.  I fixed that and there was second ClientHello with cookie. I still have other problem later on, but will raise another question. Thanks.</p>


问:
Retrieve data according to the other data in the same database table in Laravel
I have created a database table named config_table that looks like below:

```<code>+----+-------------+--------------+---------+
| id | config_name | config_value | user_id |
+----+-------------+--------------+---------+
|  1 | status      | 1            |       1 |
|  2 | title       | Test Title   |       1 |
|  3 | token       | k12345abc    |       1 |
+----+-------------+--------------+---------+
</code>```

With Laravel Eloquent I can just create a model and then start retrieving data easily like:

```<code><?php

$configs = App\Config::all();

foreach ($configs as $config) {
    echo $config->config_name;
}
</code>```

And get an output:

```<code>status
title
token
</code>```

But I want to perform like:

Get the config_value collection by config_name considering as well the user_id

```<code>echo status;
echo title; //which is under the 'config_name' column
</code>```

And the expected output should be

```<code>1
Test Title //which is the config_value of the config_name 'title'
</code>```

答:
You can use 'where' to specify constraints like this:

Select 'config_value' where 'config_name' is 'status'. To get only the first row, use first()

```<code>$config = App\Config::select('config_value')->where('config_name', 'status')->first();

echo $config->config_value;
</code>```

Similarly, select 'config_value' where 'config_name' is 'title'. To get all the rows, use get(), then you can loop through it.

$configs = App\Config::select('config_value')->where('config_name', 'title')->get();

```<code>foreach ($configs as $config) {
    echo $config->config_value;
}
</code>```

You can chain this. Select all configs where "config_name" is either 'status' or 'title'.

```<code>$configs = App\Config::select('config_value')->where('config_name', 'status')->orWhere('config_name', 'title')->get();

foreach ($configs as $config) {
    echo $config->config_value;
}
</code>```

Also, you can use whereIn() to specify multiple values of a column. Select all configs where "config_name" is either 'status' or 'title'.

```<code>$configs = App\Config::select('config_value')->whereIn('config_name', ['status', 'title'])->get();

foreach ($configs as $config) {
    echo $config->config_value;
}
</code>```

Body:
I have created a database table named config_table that looks like below:

+----+-------------+--------------+---------+
| id | config_name | config_value | user_id |
+----+-------------+--------------+---------+
|  1 | status      | 1            |       1 |
|  2 | title       | Test Title   |       1 |
|  3 | token       | k12345abc    |       1 |
+----+-------------+--------------+---------+

With Laravel Eloquent I can just create a model and then start retrieving data easily like:

<?php

$configs = App\Config::all();

foreach ($configs as $config) {
    echo $config->config_name;
}

And get an output:

status
title
token

But I want to perform like:

Get the config_value collection by config_name considering as well the user_id

echo status;
echo title; //which is under the 'config_name' column

And the expected output should be

1
Test Title //which is the config_value of the config_name 'title'

Body:
You can use 'where' to specify constraints like this:

Select 'config_value' where 'config_name' is 'status'. To get only the first row, use first()

$config = App\Config::select('config_value')->where('config_name', 'status')->first();

echo $config->config_value;

Similarly, select 'config_value' where 'config_name' is 'title'. To get all the rows, use get(), then you can loop through it.

$configs = App\Config::select('config_value')->where('config_name', 'title')->get();

foreach ($configs as $config) {
    echo $config->config_value;
}

You can chain this. Select all configs where "config_name" is either 'status' or 'title'.

$configs = App\Config::select('config_value')->where('config_name', 'status')->orWhere('config_name', 'title')->get();

foreach ($configs as $config) {
    echo $config->config_value;
}

Also, you can use whereIn() to specify multiple values of a column. Select all configs where "config_name" is either 'status' or 'title'.

$configs = App\Config::select('config_value')->whereIn('config_name', ['status', 'title'])->get();

foreach ($configs as $config) {
    echo $config->config_value;
}


问:
Code with ?, Compile in Objective-C
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

```<code>NSString *city = @"Victoria";
</code>```

or

```<code>[MyClass myMethod]
</code>```

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.

答: You can write code natively for iOS, Android, and Windows 7 using C++.  The libraries you'll have available on the different platforms will vary of course, but it'll be a common syntax across the board.</p>

ContentLicense: CC BY-SA 3.0

Title: Code with ?, Compile in Objective-C

Body:
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

NSString *city = @"Victoria";

or

[MyClass myMethod]

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.


问:
How to fit contents perfectly under the flex property?
I have 2 containers that called .grid.left and .grid.right. Each .grids, especially .grid.left has some images dynamical ways and those.grids are wrapped by another div called .gallery.

The problem is when I give margin each of the image boxes, the browser makes a little gaps inside of the .gallery like this:

My expectation is to get rid of that gaps from my .gallery and to make the images fit completely no matter how much I set the margins on the images.

I intended to give the margins for the gallery looking better. I want to remain those margins and expand the .grid.right's image only to fit between the image and the .outer div.

Are there any proper ways to resolve this problem?

CodePen

Snippets:

* {
  margin: 0;
  padding: 0;
}

div,
section {
  position: relative;
}

.gallery {
  width: 1200px;
  height: 100%;
  border: 1px solid black;
  box-sizing: border-box;
}

.article {
  width: 100%;
  height: 100%;
  display: flex;
  flex-flow: row;
  align-items: center;
}

.grid {
  height: 100%;
}

.left {
  width: 60%;
}

.inset-contents {
  width: 100%;
  height: 50%;
}

.top {
  margin-bottom: 1rem;
  background-image: url('https://imgur.com/3ozQvk9.jpg');
  padding-bottom: 50%;
}

.bottom {
  display: flex;
  flex-flow: row;
}

.inner-contents {
  width: 50%;
}

.first {
  background-image: url('https://imgur.com/tOMRVDi.jpg');
  padding-bottom: 50%;
  margin-right: .5rem;
}

.second {
  background-image: url('https://imgur.com/4oewNdx.jpg');
  padding-bottom: 50%;
  margin-left: .5rem;
}

.right {
  width: 40%;
  background-image: url('https://imgur.com/7gB1jHR.jpg');
  padding-bottom: 60%;
  align-content: stretch;
  margin-left: 1rem;
}

.img {
  display: block;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gallery">
  <div class="article">
    <div class="grid left">

      <div class="inset-contents bottom">

      </div>
    </div>

  </div>
</div></code>```

答:
Found the solution. According to this article, I needed to add flex-shrink: 0; in .right like this:

  * {
    margin: 0;
    padding: 0;
  }
  div, section {
    position: relative;
  }
  .gallery {
    width: 1200px;
    height: 100%;
    border: 1px solid black;
    box-sizing: border-box;
  }
  .article {
    width: 100%;
    height: 100%;
    display: flex;
    flex-flow: row;
    align-items: center;
  }
  .grid {
    height: 100%;
  }
  .left {
    width: 60%;
  }
  .inset-contents {
    width: 100%;
    height: 50%;
  }
  .top {
    margin-bottom: 1rem;
    background-image: url('https://imgur.com/3ozQvk9.jpg');
    padding-bottom: 50%;
  }
  .bottom {
    display: flex;
    flex-flow: row;
  }
  .inner-contents {
    width: 50%;
  }
  .first {
    background-image: url('https://imgur.com/tOMRVDi.jpg');
    padding-bottom: 50%;
    margin-right: .5rem;
  }
  .second {
    background-image: url('https://imgur.com/4oewNdx.jpg');
    padding-bottom: 50%;
    margin-left: .5rem;
  }
  .right {
    width: 40%;
    background-image: url('https://imgur.com/7gB1jHR.jpg');
    padding-bottom: 60%;
    align-content: stretch;
    margin-left: 1rem;
    flex-shrink: 0;
  }
  .img {
    display: block;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="gallery">
      <div class="article">
        <div class="grid left">

          <div class="inset-contents bottom">

          </div>
        </div>

      </div>
    </div></code>```

Body:
Found the solution. According to this article, I needed to add flex-shrink: 0; in .right like this:

  * {
    margin: 0;
    padding: 0;
  }
  div, section {
    position: relative;
  }
  .gallery {
    width: 1200px;
    height: 100%;
    border: 1px solid black;
    box-sizing: border-box;
  }
  .article {
    width: 100%;
    height: 100%;
    display: flex;
    flex-flow: row;
    align-items: center;
  }
  .grid {
    height: 100%;
  }
  .left {
    width: 60%;
  }
  .inset-contents {
    width: 100%;
    height: 50%;
  }
  .top {
    margin-bottom: 1rem;
    background-image: url('https://imgur.com/3ozQvk9.jpg');
    padding-bottom: 50%;
  }
  .bottom {
    display: flex;
    flex-flow: row;
  }
  .inner-contents {
    width: 50%;
  }
  .first {
    background-image: url('https://imgur.com/tOMRVDi.jpg');
    padding-bottom: 50%;
    margin-right: .5rem;
  }
  .second {
    background-image: url('https://imgur.com/4oewNdx.jpg');
    padding-bottom: 50%;
    margin-left: .5rem;
  }
  .right {
    width: 40%;
    background-image: url('https://imgur.com/7gB1jHR.jpg');
    padding-bottom: 60%;
    align-content: stretch;
    margin-left: 1rem;
    flex-shrink: 0;
  }
  .img {
    display: block;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
  }

    <div class="gallery">
      <div class="article">
        <div class="grid left">
          <a class="inset-contents top img"></a>
          <div class="inset-contents bottom">
            <a class="inner-contents first img"></a>
            <a class="inner-contents second img"></a>
          </div>
        </div>
        <a class="grid right img"></a>
      </div>
    </div>


问:
how to set classpath for spring project in jshell
I'm learning to use spring framework and I can't seem to find a tool similar to Django shell_plus. I'd like to be in a java repl in which I have access to all my classes, dependencies and etc. I've googled and found j-shell and spring-shell but spring-shell doesn't seem to satisfy my needs since I need to be able to instantiate and play around with my classes, so I went with j-shell. my only problem is I don't know how to let j-shell know where my classes are. I've tried

$ jshell --classpath "~/Desktop/path/to/project/"

my project directory being:

```<code>Project
 |
 +-- build.gradle
 |
 +-- build
 |     |
 |     +-- libs and etc...
 +-- src
 |  |
 |  +-- main
 |        |
 |        +-- java
 |              |
 |              com
 |               |
 |               +-- MyClass.java
 |               |
 |               +-- MyOtherClass.java
 |
 +-- settings.gradle
 +-- gradlew
 +-- default.nix
</code>```

but when in j-shell I don't have access to spring framework or my classes. I'm using emacs on nixos if that matters and nix for dev environment dependencies. appreciate any kind of help, thanks.

i've also tried setting the classpath to the jars located in ~/home/.gradle/

I expect to be in jshell repl with access to springframework classes and ones i've coded myself.

答:
There are a few ways you could set the class path for a jshell session.

On startup, before you enter the REPL:

```<code>$jshell --class-path <your_classpath>
</code>```

After you're already in a running REPL session:

```<code>jshell>/env -class-path <your_classpath>
</code>```

Notice the difference between --class-path and -class-path? That's not a typo.

The old-fashioned way. Set a $CLASSPATH environment variable before you start jshell:

```<code>$export CLASSPATH=<your_classpath>
$jshell
</code>```

There is actually a fourth way which makes the class path persistent between jshell sessions so you don't have to set it every time. It involves creating a .jsh startup file, and setting and saving it. From within a jshell session, see /help to find out more.

Body:
I'm learning to use spring framework and I can't seem to find a tool similar to Django shell_plus. I'd like to be in a java repl in which I have access to all my classes, dependencies and etc. I've googled and found j-shell and spring-shell but spring-shell doesn't seem to satisfy my needs since I need to be able to instantiate and play around with my classes, so I went with j-shell. my only problem is I don't know how to let j-shell know where my classes are. I've tried

$ jshell --classpath "~/Desktop/path/to/project/"

my project directory being:

Project
 |
 +-- build.gradle
 |
 +-- build
 |     |
 |     +-- libs and etc...
 +-- src
 |  |
 |  +-- main
 |        |
 |        +-- java
 |              |
 |              com
 |               |
 |               +-- MyClass.java
 |               |
 |               +-- MyOtherClass.java
 |
 +-- settings.gradle
 +-- gradlew
 +-- default.nix

but when in j-shell I don't have access to spring framework or my classes. I'm using emacs on nixos if that matters and nix for dev environment dependencies. appreciate any kind of help, thanks.

i've also tried setting the classpath to the jars located in ~/home/.gradle/

I expect to be in jshell repl with access to springframework classes and ones i've coded myself.

Body:
There are a few ways you could set the class path for a jshell session.

On startup, before you enter the REPL:

$jshell --class-path <your_classpath>

After you're already in a running REPL session:

jshell>/env -class-path <your_classpath>

Notice the difference between --class-path and -class-path? That's not a typo.

The old-fashioned way. Set a $CLASSPATH environment variable before you start jshell:

$export CLASSPATH=<your_classpath>
$jshell

There is actually a fourth way which makes the class path persistent between jshell sessions so you don't have to set it every time. It involves creating a .jsh startup file, and setting and saving it. From within a jshell session, see /help to find out more.


问:
Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead
i am new to react , it would be great if someone can explain the problem , this question has been answered but i am still confused .

```<code>import React from 'react' ;
import Card from './Card.js';
const CardList = ({Friends}) =>{
    const Cardcomponent = Friends.map((user , i) => {
        return(
            <div>
                 <Card id={Friends[i].id} name={Friends[i].name} username={Friends[i].username} instagram={Friends[i].instagram}  />
            </div>
              )
    })
return(
          <div>
                {Cardcomponent}
          </div>
      )
}
export default CardList ;
</code>```

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

答:
The Problem was solved going back all the way to props that were used by function in another file when I added {} to properties in my Card.js file (some other file)

```<code>   const Card = ( id , email , name ) => { return( ...
                                             ....);
      to
   const Card = ( {id , email , name} ) => { return( ...
                                                     ...);
</code>```

This answer helped me to figure out the Solution
https://stackoverflow.com/a/33577681/11556916

Body:
i am new to react , it would be great if someone can explain the problem , this question has been answered but i am still confused .

import React from 'react' ;
import Card from './Card.js';
const CardList = ({Friends}) =>{
    const Cardcomponent = Friends.map((user , i) => {
        return(

                 <Card id={Friends[i].id} name={Friends[i].name} username={Friends[i].username} instagram={Friends[i].instagram}  />

              )
    })
return(

                {Cardcomponent}

      )
}
export default CardList ;

Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

Body:
The Problem was solved going back all the way to props that were used by function in another file when I added {} to properties in my Card.js file (some other file)

   const Card = ( id , email , name ) => { return( ...
                                             ....);
      to
   const Card = ( {id , email , name} ) => { return( ...
                                                     ...);

This answer helped me to figure out the Solution
https://stackoverflow.com/a/33577681/11556916


答:
There are the following things wrong

Incorrect if statement in addtree. Change if ((p = NULL)) to if ((p == NULL))

In the talloc function, you should initialize left and right with NULL

```<code>struct tnode *talloc(void)
{
    struct tnode *newnode;
    newnode = malloc(sizeof(struct tnode));
    newnode -> left = NULL;
    newnode -> right = NULL;
    return (newnode);
}
</code>```

The treeprint function should be if(p) instead of if(!p)

```<code>void treeprint(struct tnode *p)
{
    if (p) {
        treeprint(p->left);
        printf("%4d %s\n", p->count, p->word);
        treeprint(p->right);
    }

    return;
}
</code>```

You should initialize the keytab array by using braces.

```<code>struct key keytab[] = {
  {"auto", 0,},
  {"break", 0,},
  //etc
};
</code>```

Title: I cannot solve "segmentation fault: 11"

Body:
There are the following things wrong

Incorrect if statement in addtree. Change if ((p = NULL)) to if ((p == NULL))

In the talloc function, you should initialize left and right with NULL

struct tnode *talloc(void)
{
    struct tnode *newnode;
    newnode = malloc(sizeof(struct tnode));
    newnode -> left = NULL;
    newnode -> right = NULL;
    return (newnode);
}

The treeprint function should be if(p) instead of if(!p)

void treeprint(struct tnode *p)
{
    if (p) {
        treeprint(p->left);
        printf("%4d %s\n", p->count, p->word);
        treeprint(p->right);
    }

    return;
}

You should initialize the keytab array by using braces.

struct key keytab[] = {
  {"auto", 0,},
  {"break", 0,},
  //etc
};


问:
I need help centering text in the center of CSS Grid
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

```<code><title> Learning Grid </title>

<style>

    body {
        color: #fff;
        font-family: sans-serif;
        text-align: center;
    }

    #content {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-auto-rows: minmax(100px, auto);
        grid-gap: 10px;
        max-width: 960px;
        margin: 0 auto;
    }

    #content > * {
        padding: 30px;
        font-size: 30px;

    }

    header {
        grid-column: 1/13;
        text-align: center;
        background-color: hotpink;
    }

     main {
        grid-column: 4/13;
        grid-row: 2/4;
         background-color: darksalmon;
    }

      aside {
        grid-column: 1/4;
        grid-row: 2/3;
          background-color: cadetblue;
    }

     nav {
        grid-column: 1/4;
        grid-row: 3/4;
         text-align: center;
         font-size: 30px;
         background-color: aquamarine;
    }

     section {
        grid-column: 1/13;
        grid-row: 4/6;
         background-color: coral;
    }

    footer {
        grid-column: 1/13;
        grid-row: 6/7;
        background-color: cornflowerblue;
    }

</style>

</head>

<body>

    <div id="content">

        <header> Header </header>

        <main> Main </main>

        <section>Section </section>

        <aside>Aside </aside>

        <nav> Nav </nav>

        <footer> Footer</footer>

    </div>

</body>
</code>```

答:
For aligning text to center just use this property: display: flex; align-items: center; justify-content: center;

    body {
        color: #fff;
        font-family: sans-serif;
        text-align: center;
    }
    #content {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-auto-rows: minmax(100px, auto);
        grid-gap: 10px;
        max-width: 960px;
        margin: 0 auto;
    }
    #content > * {
        padding: 30px;
        font-size: 30px;
    }
    header {
        grid-column: 1/13;
        text-align: center;
        background-color: hotpink;
    }
    main {
        grid-column: 4/13;
        grid-row: 2/4;
        background-color: darksalmon;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    aside {
        grid-column: 1/4;
        grid-row: 2/3;
        background-color: cadetblue;
    }
    nav {
        grid-column: 1/4;
        grid-row: 3/4;
        text-align: center;
        font-size: 30px;
        background-color: aquamarine;
    }
    section {
        grid-column: 1/13;
        grid-row: 4/6;
        background-color: coral;
        display: flex;
        align-items: center;
        justify-content: center;
    }
 footer {
        grid-column: 1/13;
        grid-row: 6/7;
        background-color: cornflowerblue;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
        <header> Header </header>

        <main> Main </main>

        <section>Section </section>

        <aside>Aside </aside>

        <nav> Nav </nav>

        <footer> Footer</footer>
</div></code>```

Body:
I am unable to align text in the center of the grid, both vertical and horizontally, because nothing that I tried seems to work, so I wanted to know what is the problem with my code or how should I do it.

I tried using justify-items: center, align-items: center and even place-items: center center;

This is a my full, hopefully, you can give it a try and see what is wrong with it.

<title> Learning Grid </title>

         Header

         Main

Section

        Aside

         Nav

         Footer

Body:
For aligning text to center just use this property: display: flex; align-items: center; justify-content: center;

    body {
        color: #fff;
        font-family: sans-serif;
        text-align: center;
    }
    #content {
        display: grid;
        grid-template-columns: repeat(12, 1fr);
        grid-auto-rows: minmax(100px, auto);
        grid-gap: 10px;
        max-width: 960px;
        margin: 0 auto;
    }
    #content > * {
        padding: 30px;
        font-size: 30px;
    }
    header {
        grid-column: 1/13;
        text-align: center;
        background-color: hotpink;
    }
    main {
        grid-column: 4/13;
        grid-row: 2/4;
        background-color: darksalmon;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    aside {
        grid-column: 1/4;
        grid-row: 2/3;
        background-color: cadetblue;
    }
    nav {
        grid-column: 1/4;
        grid-row: 3/4;
        text-align: center;
        font-size: 30px;
        background-color: aquamarine;
    }
    section {
        grid-column: 1/13;
        grid-row: 4/6;
        background-color: coral;
        display: flex;
        align-items: center;
        justify-content: center;
    }
 footer {
        grid-column: 1/13;
        grid-row: 6/7;
        background-color: cornflowerblue;
    }

<div id="content">
        <header> Header </header>

        <main> Main </main>

        <section>Section </section>

        <aside>Aside </aside>

        <nav> Nav </nav>

        <footer> Footer</footer>
</div>


问:
VPS hosting and root access
I've got rather poor knowledge of *nix virtualization capabilities and trying to clarify one thing. If one has root on host machine, does it always mean that he has root on all VMs of that host? If yes, then could there be a bogus setup where this is not true?

I'm asking cause I heard two different answers to that question from two different admins. One said that he has root to everything, another claimed that he don't and he needs my password.

Please share your experience with VPS hosting providers, do they have roots to your environment?

It's not that I'm afraid to lose the data, just want to have some insights and words to google for ;-)
Thanks everyone!

答:
If you change your root password and don't give it to anyone, you are the only one that can log in as root.

If someone has ever had your root password, it is very hard (dang near impossible) to know that they didn't place some kind of backdoor on the system to allow them to regain privileges by any number of mechanisms.  That "someone" could be the tech at your host that setup your VPS, or anyone else, for that matter.

Just because someone has the root password to the host, does not mean they have the root password to your virtual machine - however, it likely does mean that they could do mean, nasty things to you in all kinds of painfully creative ways (changing the contents of your filesystem...presumably they could even bit-mangle enough to change your root password to something they do know.)

OwnerDisplayName: clorz

ContentLicense: CC BY-SA 2.5

Title: VPS hosting and root access

LastEditorDisplayName: clorz

OwnerDisplayName: Jared

LastEditorDisplayName: Jared


问:
Mouse click vs viewer.select function selection behave differently in Autodesk Forge multi models viewer
I have been working on multi-model from the last couple of weeks and found that selection of a model object using mouse click vs viewer select function behave differently.

I have two models one architectural and another mechanical. When I select a wall or room on the architectural model using mouse click, Object select with overlay without having any problem but when I try using viewer select function with same object, it hides behind the wall and overlay doesn't work. It is only happening with the architectural model and working fine with the mechanical model.

Please suggest me if I am doing something wrong with multi-model.

答:
To programmatically select components when working with multiple models use viewer.select(dbid, model):

```<code>let model = viewer.impl.modelQueue().getModels()[index] or viewer.impl.findModel(modelId);
viewer.select(dbid, model)
</code>```

And to get selected dbids use viewer.getAggregateSelection (see doc here) the event to subscribe to AGGREGATE_SELECTION_CHANGED_EVENT (doc here) to track selection changes:

If the issue persists can you send some screenshots and your models (links via a sharing service like weTransfer/Dropbox) for further investigation over to forge.help@autodesk.com?

Body:
To programmatically select components when working with multiple models use viewer.select(dbid, model):

let model = viewer.impl.modelQueue().getModels()[index] or viewer.impl.findModel(modelId);
viewer.select(dbid, model)

And to get selected dbids use viewer.getAggregateSelection (see doc here) the event to subscribe to AGGREGATE_SELECTION_CHANGED_EVENT (doc here) to track selection changes:

If the issue persists can you send some screenshots and your models (links via a sharing service like weTransfer/Dropbox) for further investigation over to forge.help@autodesk.com?


问:
Are there situations when self-assignment is useful?
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}
</code>```

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}
</code>```

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...

答:
I should admit I have never heard about the common knowledge like this. For a non-POD objects, a more strict approach is to forbid copying them with disabling copy constructor and the assignment operator. So that you don't have the problem at all.

If you still need to copy the class, but there is some data which is unsafe to copy to itself, you could only override assignment for that data, and when it is used as a field, it would be used by an automatic assignment implementation of the upper level class.

As for your question, if you only need to skip doing anything the automatic "self-assignment protection" is there already, in a way. If you don't define assignment operation explicitely and let compiler use the automatic one, after inlining self-assignment may become no-op.

For example, the following code:

```<code>class A {
    int a;
    double b;
};

A& foo(A& input)
{
    return (input = input);
}
</code>```

is compiled to (gcc 4.9, -O2):

```<code>_Z3fooR1A:
    .cfi_startproc
    movq    %rdi, %rax
    ret
    .cfi_endproc
</code>```

Which does not copy anything.

Body:
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...

Body:
I should admit I have never heard about the common knowledge like this. For a non-POD objects, a more strict approach is to forbid copying them with disabling copy constructor and the assignment operator. So that you don't have the problem at all.

If you still need to copy the class, but there is some data which is unsafe to copy to itself, you could only override assignment for that data, and when it is used as a field, it would be used by an automatic assignment implementation of the upper level class.

As for your question, if you only need to skip doing anything the automatic "self-assignment protection" is there already, in a way. If you don't define assignment operation explicitely and let compiler use the automatic one, after inlining self-assignment may become no-op.

For example, the following code:

class A {
    int a;
    double b;
};

A& foo(A& input)
{
    return (input = input);
}

is compiled to (gcc 4.9, -O2):

_Z3fooR1A:
    .cfi_startproc
    movq    %rdi, %rax
    ret
    .cfi_endproc

Which does not copy anything.


问:
Mongoose Plugins nestjs
How can I implement the mongoose plugin using nestjs?

```<code>import * as mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import mongoosePaginate from 'mongoose-paginate';
import mongoose_delete from 'mongoose-delete';

const UsuarioSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: [true, 'El nombre de usuario es requerido']
    },
    password: {
        type: String,
        required: [true, 'La clave es requerida'],
        select: false
    }
});

UsuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser único' });
UsuarioSchema.plugin(mongoosePaginate);
UsuarioSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, overrideMethods: true });
</code>```

Error: First param to schema.plugin() must be a function, got "undefined"

答:
Try this:

```<code>import * as mongoose from 'mongoose';
import * as uniqueValidator from 'mongoose-unique-validator';
import * as mongoosePaginate from 'mongoose-paginate';
import * as mongoose_delete from 'mongoose-delete';

const UsuarioSchema = new mongoose.Schema({
   username: {
    type: String,
    unique: true,
    required: [true, 'El nombre de usuario es requerido']
   },
   password: {
       type: String,
       required: [true, 'La clave es requerida'],
       select: false
   }
});

UsuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser único' });
UsuarioSchema.plugin(mongoosePaginate);
UsuarioSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, overrideMethods: true });

export default UsuarioSchema;
</code>```

Then you can use it like this:

```<code>import UsuarioSchema from './UsuarioSchema'
</code>```

Title: Mongoose Plugins nestjs

Body:
How can I implement the mongoose plugin using nestjs?

import * as mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import mongoosePaginate from 'mongoose-paginate';
import mongoose_delete from 'mongoose-delete';

const UsuarioSchema = new mongoose.Schema({
    username: {
        type: String,
        unique: true,
        required: [true, 'El nombre de usuario es requerido']
    },
    password: {
        type: String,
        required: [true, 'La clave es requerida'],
        select: false
    }
});

UsuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser único' });
UsuarioSchema.plugin(mongoosePaginate);
UsuarioSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, overrideMethods: true });

Error: First param to schema.plugin() must be a function, got "undefined"

Body:
Try this:

import * as mongoose from 'mongoose';
import * as uniqueValidator from 'mongoose-unique-validator';
import * as mongoosePaginate from 'mongoose-paginate';
import * as mongoose_delete from 'mongoose-delete';

const UsuarioSchema = new mongoose.Schema({
   username: {
    type: String,
    unique: true,
    required: [true, 'El nombre de usuario es requerido']
   },
   password: {
       type: String,
       required: [true, 'La clave es requerida'],
       select: false
   }
});

UsuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser único' });
UsuarioSchema.plugin(mongoosePaginate);
UsuarioSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, overrideMethods: true });

export default UsuarioSchema;

Then you can use it like this:

import UsuarioSchema from './UsuarioSchema'


问:
Is there a way to connect and view the files in a self Hosted Agent of Azure pipelines
I am pretty new to Azure Devops. Is there a way to connect and view the logs and the folders created in the self hosted agent of Azure devops pipeline.</p>

答:
You can do it in two ways

(i) While the build running on Azure devops  with Hosted Agent the only way to see the logs is to wait for console output.

(ii) After the build finished you can download the logs az zip

The logs are in the _diag folder (the folder exist in agnet root folder).

Also you can use the API to get the logs.


问:
Edit several hundred Protocol Buffer serialized messages read from database
For an operation on my application, I need to read from database & then edit several hundred Protocol Buffer serialized messages. In each PB message, there are actually 4 int fields and one boolean field, and in the new message only the the boolean field is required to be changed.

I am in doubt what would be the best way to accomplish this, and thus seeking your help & expert opinion.

I guess building the entire messages once again by creating builder objects would be rather too much expensive..

答:
The builder approach should be cheap enough, especially if you can execute near to the server to minimise latency. However, if the bit field has the first/last field number, it should be a single byte update in either the 2nd or last byte, so might be possible in SQL if you like. In fact, as long as you just want to skip the ints (i.e. you don't need to know what they were or change them), even picking out the bool in the middle would be fairly easy.

But try the route using the existing client first; it may be faster than you think.


问:
How can I check if there a problem in internet connection?
I want to check if there an internet connection on my device I already try the Connectivity but it doesn't help me because it check if the device is connecting to wifi or not, but doesn't discover if there an internet problem
my code :

```<code>import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutter/services.dart';
class WebviewUi extends StatefulWidget {

@override
_WebviewState createState() => _WebviewState();
}

class _WebviewState extends State<WebviewUi> {
String _connectionStatus;
final Connectivity _connectivity = new Connectivity();
StreamSubscription<ConnectivityResult> _connectivitySubscription;
@override
void initState() {
super.initState();
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.deepOrangeAccent)
);

_connectivitySubscription =
_connectivity.onConnectivityChanged.listen((ConnectivityResult result){
  setState(() {
    _connectionStatus = result.toString();
    print('Connection Status : $_connectionStatus');
  });
});
}

@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: PreferredSize(
      preferredSize: Size.fromHeight(0),
      child: AppBar(
      ),

    ),
    body: (_connectionStatus == "ConnectivityResult.mobile" ||
_connectionStatus == "ConnectivityResult.wifi") ?
    WebviewScaffold(
      /*appBar: AppBar(
    title: Text(''),
    backgroundColor: Colors.deepOrangeAccent,

  ),*/

      url: "https://www.google.net/",

      withJavascript: true,
    )

        :
    Container(
        child: Image.asset(
          'assets/Internet-Access-Error.jpg',
        )
    )

);
}
}
</code>```

when I tried this code  on the emulator I  switched to airplane mode on my labtop it's show:

```<code>net::ERR_NAME_NOT_RESOLVED
</code>```

but I want to display an widget that tell the there's an internet problem or no internet. How can I preform this I searched a lot  over the websites and facebook groups I didn't find any solution

答:
Use connectivity package Flutter team. This package can identify whether wifi or mobile data is enabled or not. But if internet actualy can reach or not cannot be identified. In that case @Günter solution is great. Note that you can also use http package http.get() in a try catch block and identify SocketException(Im not sure that this is reusable great solution.).

Simple example:

```<code>import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  BuildContext ctx;
  bool canProceed = true;

  bool isOffline = false;
  bool dialogIsVisible = false;

  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  @override
  void initState() {
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    super.initState();
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<void> initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    if (!mounted) {
      return;
    }

    _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.mobile:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.none:
        setState(() => isOffline = true);
        buildAlertDialog("Internet connection cannot be establised!");
        break;
      default:
        setState(() => isOffline = true);
        break;
    }
  }

  void buildAlertDialog(String message) {
    SchedulerBinding.instance.addPostFrameCallback((_) => setState(() {
      if (isOffline && !dialogIsVisible) {
        dialogIsVisible = true;
        showDialog(
            barrierDismissible: false,
            context: ctx,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(message, textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0),),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Icon(Icons.portable_wifi_off, color: Colors.redAccent, size: 36.0,),
                    canProceed ? Text(
                      "Check your internet connection before proceeding.", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0),) : Text(
                      "Please! proceed by connecting to a internet connection", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0, color: Colors.red),),
                  ],
                ),
                actions: <Widget>[
                  RaisedButton(
                    onPressed: () {
                      SystemChannels.platform
                          .invokeMethod('SystemNavigator.pop');
                    },
                    child: Text(
                      "CLOSE THE APP",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (isOffline) {
                        setState(() {
                          canProceed = false;
                        });
                      } else {
                        Navigator.pop(ctx);
                        //your code
                      }
                    },
                    child: Text(
                      "PROCEED",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
              );
            });
      }
    }));
  }

  @override
  Widget build(BuildContext context) {
    ctx = context;
    return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
    );
  }
}
</code>```

Body:
I want to check if there an internet connection on my device I already try the Connectivity but it doesn't help me because it check if the device is connecting to wifi or not, but doesn't discover if there an internet problem
my code :

import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutter/services.dart';
class WebviewUi extends StatefulWidget {

@override
_WebviewState createState() => _WebviewState();
}

class _WebviewState extends State<WebviewUi> {
String _connectionStatus;
final Connectivity _connectivity = new Connectivity();
StreamSubscription<ConnectivityResult> _connectivitySubscription;
@override
void initState() {
super.initState();
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.deepOrangeAccent)
);

_connectivitySubscription =
_connectivity.onConnectivityChanged.listen((ConnectivityResult result){
  setState(() {
    _connectionStatus = result.toString();
    print('Connection Status : $_connectionStatus');
  });
});
}

@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: PreferredSize(
      preferredSize: Size.fromHeight(0),
      child: AppBar(
      ),

    ),
    body: (_connectionStatus == "ConnectivityResult.mobile" ||
_connectionStatus == "ConnectivityResult.wifi") ?
    WebviewScaffold(
      /*appBar: AppBar(
    title: Text(''),
    backgroundColor: Colors.deepOrangeAccent,

  ),*/

      url: "https://www.google.net/",

      withJavascript: true,
    )

        :
    Container(
        child: Image.asset(
          'assets/Internet-Access-Error.jpg',
        )
    )

);
}
}

when I tried this code  on the emulator I  switched to airplane mode on my labtop it's show:

net::ERR_NAME_NOT_RESOLVED

but I want to display an widget that tell the there's an internet problem or no internet. How can I preform this I searched a lot  over the websites and facebook groups I didn't find any solution

Body:
Use connectivity package Flutter team. This package can identify whether wifi or mobile data is enabled or not. But if internet actualy can reach or not cannot be identified. In that case @Günter solution is great. Note that you can also use http package http.get() in a try catch block and identify SocketException(Im not sure that this is reusable great solution.).

Simple example:

import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  BuildContext ctx;
  bool canProceed = true;

  bool isOffline = false;
  bool dialogIsVisible = false;

  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  @override
  void initState() {
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    super.initState();
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<void> initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    if (!mounted) {
      return;
    }

    _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.mobile:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.none:
        setState(() => isOffline = true);
        buildAlertDialog("Internet connection cannot be establised!");
        break;
      default:
        setState(() => isOffline = true);
        break;
    }
  }

  void buildAlertDialog(String message) {
    SchedulerBinding.instance.addPostFrameCallback((_) => setState(() {
      if (isOffline && !dialogIsVisible) {
        dialogIsVisible = true;
        showDialog(
            barrierDismissible: false,
            context: ctx,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(message, textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0),),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Icon(Icons.portable_wifi_off, color: Colors.redAccent, size: 36.0,),
                    canProceed ? Text(
                      "Check your internet connection before proceeding.", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0),) : Text(
                      "Please! proceed by connecting to a internet connection", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0, color: Colors.red),),
                  ],
                ),
                actions: <Widget>[
                  RaisedButton(
                    onPressed: () {
                      SystemChannels.platform
                          .invokeMethod('SystemNavigator.pop');
                    },
                    child: Text(
                      "CLOSE THE APP",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (isOffline) {
                        setState(() {
                          canProceed = false;
                        });
                      } else {
                        Navigator.pop(ctx);
                        //your code
                      }
                    },
                    child: Text(
                      "PROCEED",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
              );
            });
      }
    }));
  }

  @override
  Widget build(BuildContext context) {
    ctx = context;
    return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
    );
  }
}


问:
How to format a chrono::time_point as a string
I need to get current date and time in c++. I can use chrono to get the system time but I also need to save this in json file as string. Moreover the chrono time which I have tried gives below format:

```<code>auto time = std::chrono::system_clock::now();
</code>```

output:

```<code>Thu Oct 11 19:10:24 2012
</code>```

But I need date time format in below format:

```<code>2016-12-07T00:52:07
</code>```

Also I need this date time in string so that I can save it in Json file. Can anyone please suggest a good way to achieve this. Thanks.

答:
```<code>#include <iostream>
#include <chrono>
#include <ctime>

std::string getTimeStr(){
    std::time_t now =     std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());

    std::string s(30, '\0');
    std::strftime(&s[0], s.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
    return s;
}
int main(){

    std::cout<<getTimeStr()<<std::endl;
    return 0;

}
</code>```

Body:
I need to get current date and time in c++. I can use chrono to get the system time but I also need to save this in json file as string. Moreover the chrono time which I have tried gives below format:

auto time = std::chrono::system_clock::now();

output:

Thu Oct 11 19:10:24 2012

But I need date time format in below format:

2016-12-07T00:52:07

Also I need this date time in string so that I can save it in Json file. Can anyone please suggest a good way to achieve this. Thanks.


问:
How to Notify User that Asynchronous Task is Completed?
I am using threading library for a long-running process in Django. When the process is completed, I want to keep updating progress status on the front-end. I am unable to post anything to the ajax.get() from my thread function.

View.py

```<code>def upload_handler(request, file_loc, filename):
    // do something with uploaded
    // I want to notify user that this process is complete via a post
class Uploader(View):
    def get(self, request):
        file=UploadForm()
        return render(request,'template.html',{'form':file}) #,'files':files})
    def post(self, request):
        file = UploadForm(data=request.POST, files=request.FILES)
        if file.is_valid():
            x = request.FILES['file']
            file.save()
            filename = str(request.FILES['file'])
            file_loc = os.path.join(BASE_DIR, 'media', 'images', filename)
            upload_thread = Thread(target=upload_handler, args=(request, file_loc, filename))
            upload_thread.start()
            return HttpResponseRedirect(reverse('imageupload'))
</code>```

urls.py

```<code>urlpatterns = [
    path('', Uploader.as_view(), name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

ajax call script

```<code>{
    $.ajax({
      type:"get",
      url:"/uploader",
      datatype:"json",
      success:function(data)
      {
        console.log(data);
        alert("Your file is processed now!");
      }
    });
}, 1000);
</code>```

Assume that file uploaded page will remain open till the long process completes.

答: AJAX option datatype is "json", but the View does not return a "json".</p>

Body:
I am using threading library for a long-running process in Django. When the process is completed, I want to keep updating progress status on the front-end. I am unable to post anything to the ajax.get() from my thread function.

View.py

def upload_handler(request, file_loc, filename):
    // do something with uploaded
    // I want to notify user that this process is complete via a post
class Uploader(View):
    def get(self, request):
        file=UploadForm()
        return render(request,'template.html',{'form':file}) #,'files':files})
    def post(self, request):
        file = UploadForm(data=request.POST, files=request.FILES)
        if file.is_valid():
            x = request.FILES['file']
            file.save()
            filename = str(request.FILES['file'])
            file_loc = os.path.join(BASE_DIR, 'media', 'images', filename)
            upload_thread = Thread(target=upload_handler, args=(request, file_loc, filename))
            upload_thread.start()
            return HttpResponseRedirect(reverse('imageupload'))

urls.py

urlpatterns = [
    path('', Uploader.as_view(), name='imageupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

ajax call script

{
    $.ajax({
      type:"get",
      url:"/uploader",
      datatype:"json",
      success:function(data)
      {
        console.log(data);
        alert("Your file is processed now!");
      }
    });
}, 1000);

Assume that file uploaded page will remain open till the long process completes.


问:
How to combine path with WebRootPath
I need to upload some files to server using my app and I need to deliver a full path of the folder where I want to save files.
I am using Path.Combine method with webHostEnvironment.WebRootPath additional folders path from appsettings.json and file name.
The code looks like this:

```<code>var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
var path = Path.Combine(webHostEnvironment.WebRootPath, pathString, picture.Name);
</code>```

And the problem is that the webHostEnvironment.WebRootPath is just ommited in the path variable (path looks like pathString + picture.Name).

Any idea how to get proper path?

答:
If you are using Asp.net core 3  then use IWebHostEnvironment instead of IHostingEnvironment.
Inject IWebHostEnvironment as a dependency into the dependent class.https://github.com/aspnet/AspNetCore/issues/7749

```<code>public class HomeController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment= webHostEnvironment;
    }

    public IActionResult Index()
    {
        return Content(_webHostEnvironment.WebRootPath + "\n" + _webHostEnvironment.ContentRootPath);
    }
}
</code>```

When Microsoft.Extensions.Hosting was introduced in 2.1 some types
  like IHostingEnvironment and IApplicationLifetime were copied from
  Microsoft.AspNetCore.Hosting. Some 3.0 changes cause apps to include
  both the Microsoft.Extensions.Hosting and Microsoft.AspNetCore.Hosting
  namespaces. Any use of those duplicate types causes an "ambiguous
  reference" compiler error when both namespaces are referenced.

This error has been addressed in 3.0.0-preview3 by marking the
  following types obsolete and replacing them with new types. There have
  not been any behavioral changes made for the new types, only naming.

```<code>Obsolete types (warning):

Microsoft.Extensions.Hosting.IHostingEnvironment
Microsoft.AspNetCore.Hosting.IHostingEnvironment
Microsoft.Extensions.Hosting.IApplicationLifetime
Microsoft.AspNetCore.Hosting.IApplicationLifetime
Microsoft.Extensions.Hosting.EnvironmentName
Microsoft.AspNetCore.Hosting.EnvironmentName

New types:

Microsoft.Extensions.Hosting.IHostEnvironment
Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
Microsoft.Extensions.Hosting.IHostApplicationLifetime
Microsoft.Extensions.Hosting.Environments
</code>```

Note the new IHostEnvironment IsDevelopment, IsProduction, etc.
  extension methods are in the Microsoft.Extensions.Hosting namespace
  which may need to be added to your app.

For 3.0 both the old and new types will be available from HostBulder's
  and WebHostBuilder's dependency injection containers. The old types
  will be removed in 4.0.

Title: How to combine path with WebRootPath

Body:
I need to upload some files to server using my app and I need to deliver a full path of the folder where I want to save files.
I am using Path.Combine method with webHostEnvironment.WebRootPath additional folders path from appsettings.json and file name.
The code looks like this:

var pathString = configuration.GetValue<string>("UploadPaths:Pictures");
var path = Path.Combine(webHostEnvironment.WebRootPath, pathString, picture.Name);

And the problem is that the webHostEnvironment.WebRootPath is just ommited in the path variable (path looks like pathString + picture.Name).

Any idea how to get proper path?

Body:
If you are using Asp.net core 3  then use IWebHostEnvironment instead of IHostingEnvironment.
Inject IWebHostEnvironment as a dependency into the dependent class.https://github.com/aspnet/AspNetCore/issues/7749

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment= webHostEnvironment;
    }

    public IActionResult Index()
    {
        return Content(_webHostEnvironment.WebRootPath + "\n" + _webHostEnvironment.ContentRootPath);
    }
}

When Microsoft.Extensions.Hosting was introduced in 2.1 some types
  like IHostingEnvironment and IApplicationLifetime were copied from
  Microsoft.AspNetCore.Hosting. Some 3.0 changes cause apps to include
  both the Microsoft.Extensions.Hosting and Microsoft.AspNetCore.Hosting
  namespaces. Any use of those duplicate types causes an "ambiguous
  reference" compiler error when both namespaces are referenced.

This error has been addressed in 3.0.0-preview3 by marking the
  following types obsolete and replacing them with new types. There have
  not been any behavioral changes made for the new types, only naming.

Obsolete types (warning):

Microsoft.Extensions.Hosting.IHostingEnvironment
Microsoft.AspNetCore.Hosting.IHostingEnvironment
Microsoft.Extensions.Hosting.IApplicationLifetime
Microsoft.AspNetCore.Hosting.IApplicationLifetime
Microsoft.Extensions.Hosting.EnvironmentName
Microsoft.AspNetCore.Hosting.EnvironmentName

New types:

Microsoft.Extensions.Hosting.IHostEnvironment
Microsoft.AspNetCore.Hosting.IWebHostEnvironment : IHostEnvironment
Microsoft.Extensions.Hosting.IHostApplicationLifetime
Microsoft.Extensions.Hosting.Environments

Note the new IHostEnvironment IsDevelopment, IsProduction, etc.
  extension methods are in the Microsoft.Extensions.Hosting namespace
  which may need to be added to your app.

For 3.0 both the old and new types will be available from HostBulder's
  and WebHostBuilder's dependency injection containers. The old types
  will be removed in 4.0.


问:
C++ overriding virtual templated method
I am trying to override a virtual function in C++. After I override the function, it does not actually override it and thus makes the class abstract.
The code below will give you a good understanding of the problem.

As you can see below, the code works fine for non-pointer templates like an int but fails with an int pointer.

I thought that maybe since it was a problem with references to pointers, I took out the & in the implementation of Derived2 but that did not fix it.

```<code>template<class T>
class Base {
    virtual void doSomething(const T& t) = 0;
};
class Derived1: public Base<int>{
    void doSomething(const int& t) {
    } // works perfectly
};
class Derived2: public Base<int*>{
    void doSomething(const int*& t) {
    }
// apparently parent class function doSomething is still unimplemented, making Derived2 abstract???
};

int main(){
    Derived1 d1;
    Derived2 d2; // does not compile, "variable type 'Derived2' is an abstract class"
}
</code>```

答:
Note that for the parameter type const T&, const is qualified on T itself, then when T is a pointer like int *, the const should be qualified on the pointer itself (i.e. int* const), not the pointee (i.e. const int*).

The correct type should be

```<code>void doSomething(int* const & t)
</code>```

BTW: You can use the keyword override to confirm whether the virtual function is overrided correctly.

BTW2: Change the style for const T& to T const& might make it more clear.

LIVE

Title: C++ overriding virtual templated method

Body:
I am trying to override a virtual function in C++. After I override the function, it does not actually override it and thus makes the class abstract.
The code below will give you a good understanding of the problem.

As you can see below, the code works fine for non-pointer templates like an int but fails with an int pointer.

I thought that maybe since it was a problem with references to pointers, I took out the & in the implementation of Derived2 but that did not fix it.

template<class T>
class Base {
    virtual void doSomething(const T& t) = 0;
};
class Derived1: public Base<int>{
    void doSomething(const int& t) {
    } // works perfectly
};
class Derived2: public Base<int*>{
    void doSomething(const int*& t) {
    }
// apparently parent class function doSomething is still unimplemented, making Derived2 abstract???
};

int main(){
    Derived1 d1;
    Derived2 d2; // does not compile, "variable type 'Derived2' is an abstract class"
}

Body:
Note that for the parameter type const T&, const is qualified on T itself, then when T is a pointer like int *, the const should be qualified on the pointer itself (i.e. int* const), not the pointee (i.e. const int*).

The correct type should be

void doSomething(int* const & t)

BTW: You can use the keyword override to confirm whether the virtual function is overrided correctly.

BTW2: Change the style for const T& to T const& might make it more clear.

LIVE


问:
Set background image on grid in WPF using C#
I have a problem: I want to set the image of my grid through code behind.

Can anybody tell me how to do this?

答:
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.</p>

```<code>  ImageBrush myBrush = new ImageBrush();
  Image image = new Image();
  image.Source = new BitmapImage(
      new Uri(
         "pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
  myBrush.ImageSource = image.Source;
  Grid grid = new Grid();
  grid.Background = myBrush;
</code>```

Body:
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.

  ImageBrush myBrush = new ImageBrush();
  Image image = new Image();
  image.Source = new BitmapImage(
      new Uri(
         "pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
  myBrush.ImageSource = image.Source;
  Grid grid = new Grid();
  grid.Background = myBrush;