问:
React Google Analytics - How to check if initialized?
I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).

So, I would like to create a text field in backoffice which value is saved in database.

Then in the front side, I initialize react-ga only if I have a value in database.

To achieve this, I'm trying do this in componentDidUpdate in App.jsx.

I retrieve all my data set in backoffice via :

```<code>componentDidMount() {
    // I get my data in this.props.data_admin
    this.props.list_admin();
}
</code>```

Then in componentDidUpdate(prevProps, prevState) I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :

```<code>componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin) {
        // this.props.data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(this.props.data_admin.trackingNumber);
    }
}
</code>```

But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done.
How can I check if react-ga is already initialized ?

Thanks for your help

答:
I think you should not be doing this in componentDidUpdate but in componentDidMount after you have retrieved your data.

Your data retrieval process is an asynchronous call to your backend/database, it should return a Promise that resolves with the data retrieved. You can then initialize react-ga.

```<code>componentDidMount() {
    // I am assuming this.props.list_admin() returns your data
    this.props.list_admin().then((data_admin) => {
      if (data_admin) {
        // data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(data_admin.trackingNumber);
      }
    });
}
</code>```

Body:
I'm trying to implement react-ga but only in production server (I have my local / dev and prod servers).

So, I would like to create a text field in backoffice which value is saved in database.

Then in the front side, I initialize react-ga only if I have a value in database.

To achieve this, I'm trying do this in componentDidUpdate in App.jsx.

I retrieve all my data set in backoffice via :

componentDidMount() {
    // I get my data in this.props.data_admin
    this.props.list_admin();
}

Then in componentDidUpdate(prevProps, prevState) I check if this.props.data_admin is set and not null, and when I got values I would like to initialize react-ga :

componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.data_admin) {
        // this.props.data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(this.props.data_admin.trackingNumber);
    }
}

But this gonna be done a lot of times (each time App.jsx is updated). So I should check before initialize if it's already done.
How can I check if react-ga is already initialized ?

Thanks for your help

Body:
I think you should not be doing this in componentDidUpdate but in componentDidMount after you have retrieved your data.

Your data retrieval process is an asynchronous call to your backend/database, it should return a Promise that resolves with the data retrieved. You can then initialize react-ga.

componentDidMount() {
    // I am assuming this.props.list_admin() returns your data
    this.props.list_admin().then((data_admin) => {
      if (data_admin) {
        // data_admin.trackingNumber = UA-XXXXXXXXX
        ReactGA.initialize(data_admin.trackingNumber);
      }
    });
}


来源: stackexchange

问:
Git stash pop- needs merge, unable to refresh index
I can't pop my stash because I merged a branch which apparently conflicts with my stash and now my stash is seemingly unable to be popped.

```<code>app.coffee: needs merge
unable to refresh index
</code>```

Anyone know how to resolve this?

答:
You need to add app.coffee to staging.

Do git add app.coffee and then you will be able to apply your stash (after that commit and push).

ContentLicense: CC BY-SA 4.0

Body:
I can't pop my stash because I merged a branch which apparently conflicts with my stash and now my stash is seemingly unable to be popped.

app.coffee: needs merge
unable to refresh index

Anyone know how to resolve this?


问:
XML element holds non xml elements (not wrapped in cdata)
I am using simple xml for php and trying to parse the <content> element that is a part of following tree:

<entry>

...<title>

...<link>

...

...<content>

The problem is that <content> element cannot be read as a string because it has "non string" content that is not wrapped in CDATA:

```<code><content type="xhtml" xml:lang="en-US" xml:base="...">
<div xmlns="http://www.w3.org/1999/xhtml"><p><strong>text... text...</strong> text <a     href="..."
target="_self">LINK</a>. text</p>
</content>
</code>```

I use the following code:

```<code>$xml = simplexml_load_file($feed_uri);
</code>```

and then:

```<code>foreach($xml->entry as $entry){
$item = new RSSItem();
$item->title = (string) $entry->title;
$item->content = (string)$entry->content;
$item->date = (string) $entry->published;
</code>```

My content member var is empty. The others are as expected
If I change $item->content = (string)$entry->content; to $item->content = $entry->content; then I get another object nested in $item->content variable

Any ide how to force parser not to interpret elements found in content element (div, p etc.) as nested elements?

Thanks in advance,
L

答:
Try $entry->content->asXML().

See http://php.net/simplexmlelement.asxml

ContentLicense: CC BY-SA 3.0

Body:
I am using simple xml for php and trying to parse the <content> element that is a part of following tree:

<entry>

...<title>

...<link>

...

...<content>

The problem is that <content> element cannot be read as a string because it has "non string" content that is not wrapped in CDATA:

<content type="xhtml" xml:lang="en-US" xml:base="...">

text... text... text LINK. text

</content>

I use the following code:

$xml = simplexml_load_file($feed_uri);

and then:

foreach($xml->entry as $entry){
$item = new RSSItem();
$item->title = (string) $entry->title;
$item->content = (string)$entry->content;
$item->date = (string) $entry->published;

My content member var is empty. The others are as expected
If I change $item->content = (string)$entry->content; to $item->content = $entry->content; then I get another object nested in $item->content variable

Any ide how to force parser not to interpret elements found in content element (div, p etc.) as nested elements?

Thanks in advance,
L


问:
Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?
Using MSSQL2005, can I truncate a table with a foreign key constraint if I first truncate the child table (the table with the primary key of the FK relationship)?

I know that I can either

Use a DELETE without a where clause and then RESEED the identity (or)

Remove the FK, truncate the table, and recreate the FK.

I thought that as long as I truncated the child table before the parent, I'd be okay without doing either of the options above, but I'm getting this error:

Cannot truncate table 'TableName' because it is being referenced by a FOREIGN KEY constraint.

答:
Delete then reset auto-increment:

```<code>delete from tablename;
</code>```

then

```<code>ALTER TABLE tablename AUTO_INCREMENT = 1;
</code>```

OwnerDisplayName: ctrlShiftBryan

LastEditorDisplayName: Dave DuPlantis

Body:
Delete then reset auto-increment:

delete from tablename;

then

ALTER TABLE tablename AUTO_INCREMENT = 1;


问:
Is there a way to score a list that have its members in another list?
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

```<code>score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']
</code>```

I expect the score list to contain the score for each member of the phrase list.

```<code>phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]
</code>```

答:
You can write a scoring function that accumulates the scores, and returns them:

```<code>def scoring(phrase, check):
    scores = []
    for block in phrase:
        tokens = block.split()
        score = 0
        for word in check:
            if word in tokens:
                score += 1 / len(tokens)
        scores.append(score)
    return scores

score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']

# score = [0.5, 1, 1, 1, 0.33]

scoring(phrase, check)
</code>```

output:

```<code>[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]
</code>```

Body:
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']

I expect the score list to contain the score for each member of the phrase list.

phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]

Body:
You can write a scoring function that accumulates the scores, and returns them:

def scoring(phrase, check):
    scores = []
    for block in phrase:
        tokens = block.split()
        score = 0
        for word in check:
            if word in tokens:
                score += 1 / len(tokens)
        scores.append(score)
    return scores

score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']

# score = [0.5, 1, 1, 1, 0.33]

scoring(phrase, check)

output:

[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]


问:
Arithmatic overflow error converting varchar to data type numeric (SQL)
I have an MS SQL 2017 database setup and I am sending RFID tags to a table and then querying the table later to see if a user exists on the system.

I am getting error:

'Arithmatic overflow error converting varchar to data type numeric'.

I have tried to change the 'rfid_id' type to VARCHAR(MAX) but no success.

My table:

```<code>CREATE TABLE worker_table ('worker_id INT IDENTITY(1,1) PRIMARY KEY,
rfid_id VARCHAR(30) NOT NULL,
worker_customer_name VARCHAR(30) NOT NULL,
site_id INTEGER NOT NULL REFERENCES site_table(site_id))
</code>```

This works fine.

Data that I insert into the table for a given RFID:

```<code>INSERT INTO worker_table(rfid_id, worker_customer_name, site_id, worker_id
VALUES ($'10103967375$', $'USER_1$', $'1$', $'1'))
</code>```

This also works fine for most RFID tags.

However, some tags are different length e.g 330004531017 or 9600007487626. Some tags write in OK to the data base but some return the error.

Also if I query the data base with:

```<code>SELECT CASE WHEN EXISTS(SELECT * FROM worker_table WHERE rfid_id =9600007487626) THEN 100 ELSE 200 END)
</code>```

This works fine for most tags but returns the same error for some.

PS I am currently sending rfid_id as a string from my PLC.

My knowledge is limited in SQL so any help would be greatly appreciated, please and thank you.

答:
Use single quotes, because your tag is a string:

```<code>SELECT (CASE WHEN EXISTS (SELECT 1
                          FROM worker_table
                          WHERE rfid_id = '9600007487626'
                         )
            THEN 100 ELSE 200
        END)
</code>```

When you leave out the single quotes, the value is a number, and rfid_id is converted to a number -- hence the overflow.

Just use string comparisons.

Body:
I have an MS SQL 2017 database setup and I am sending RFID tags to a table and then querying the table later to see if a user exists on the system.

I am getting error:

'Arithmatic overflow error converting varchar to data type numeric'.

I have tried to change the 'rfid_id' type to VARCHAR(MAX) but no success.

My table:

CREATE TABLE worker_table ('worker_id INT IDENTITY(1,1) PRIMARY KEY,
rfid_id VARCHAR(30) NOT NULL,
worker_customer_name VARCHAR(30) NOT NULL,
site_id INTEGER NOT NULL REFERENCES site_table(site_id))

This works fine.

Data that I insert into the table for a given RFID:

INSERT INTO worker_table(rfid_id, worker_customer_name, site_id, worker_id
VALUES ($'10103967375$', $'USER_1$', $'1$', $'1'))

This also works fine for most RFID tags.

However, some tags are different length e.g 330004531017 or 9600007487626. Some tags write in OK to the data base but some return the error.

Also if I query the data base with:

SELECT CASE WHEN EXISTS(SELECT * FROM worker_table WHERE rfid_id =9600007487626) THEN 100 ELSE 200 END)

This works fine for most tags but returns the same error for some.

PS I am currently sending rfid_id as a string from my PLC.

My knowledge is limited in SQL so any help would be greatly appreciated, please and thank you.

Body:
Use single quotes, because your tag is a string:

SELECT (CASE WHEN EXISTS (SELECT 1
                          FROM worker_table
                          WHERE rfid_id = '9600007487626'
                         )
            THEN 100 ELSE 200
        END)

When you leave out the single quotes, the value is a number, and rfid_id is converted to a number -- hence the overflow.

Just use string comparisons.


问:
How to rename multiple dataframes in one loop with a shared dictionary?
I have multiple dataframes which all share the same number of columns with the same names. For some reason, I would like to rename all these columnes with a dictionary.

I know how to do it for one dataframe at a time using the rename function of pandas such as:

```<code>df = df.rename(columns={"1": "a", etc.})
</code>```

I would like to add a loop for each dataframe from a list of dataframes (df_list) but for some reason it does not act as I would expect it to.

```<code>df_list = (df1, df2)

for i in df_list:

   i = i.rename(columns={
    '1':'a',
    '2':'b',
    '3':'c', etc.})
</code>```

The code above does not provide any error, nor change anything. Again, both df1 and df2 share the exact same structure (columns = "1", "2", "3", etc.).

I would happily read any suggestion as to how I can proceed to automate the renaming of these columns... Thanks !

答:
You are trying to modify a tuple, which is immutable. Use a list instead:</p>

```<code>df_list = [df1, df2]

for i in df_list:

   i = i.rename(columns={
  '1':'a',
  '2':'b',
  '3':'c', ...})
</code>```

Body:
I have multiple dataframes which all share the same number of columns with the same names. For some reason, I would like to rename all these columnes with a dictionary.

I know how to do it for one dataframe at a time using the rename function of pandas such as:

df = df.rename(columns={"1": "a", etc.})

I would like to add a loop for each dataframe from a list of dataframes (df_list) but for some reason it does not act as I would expect it to.

df_list = (df1, df2)

for i in df_list:

   i = i.rename(columns={
    '1':'a',
    '2':'b',
    '3':'c', etc.})

The code above does not provide any error, nor change anything. Again, both df1 and df2 share the exact same structure (columns = "1", "2", "3", etc.).

I would happily read any suggestion as to how I can proceed to automate the renaming of these columns... Thanks !

Body:
You are trying to modify a tuple, which is immutable. Use a list instead:

df_list = [df1, df2]

for i in df_list:

   i = i.rename(columns={
  '1':'a',
  '2':'b',
  '3':'c', ...})


问:
How to enable .NET Core 3 preview SDK in VS2019?
I wanted to try out Blazor. I've installed .NET Core 3.0 preview 5 SDK, Blazor VS extension to enable project templates. I can create Blazor project, but I can't run it - I constantly get this notification.

In some tutorials I see that there should be a checkbox in VS options - to enable using of preview SDKs.

But it's not there in VS2019! Version is 16.1.1

答: Thanks to @Kirk Woll. They moved this checkbox indeed.


问:
Relation and inverse relation not working together Adonis JS
I have 3 model Country, State, City
country.js

```<code>  state () {
    return this.hasMany(State, 'id', 'country_id')
  }
</code>```

state.js

```<code> city () {
    return this.hasMany(City, 'id', 'state_id')
  }
</code>```

```<code>  stateCountry () {
    return this.belongsTo(Country, 'country_id', 'id')
  }
</code>```

city.js

```<code>cityState () {
    return this.belongsTo(State, 'state_id', 'id')
  }
</code>```

Now I'm trying to get two type of data
1. From country > state > city ( normal relation )
2. From city > state > country ( inverse relation )

```<code>case 1:
const countries = await Country.query()
          .with('state.city')
          .fetch()
</code>```

```<code>case 2:
const citties = await City.query()
      .with('cityState.stateCountry')
      .fetch()
</code>```

Now whichever I run first will work and give me proper result however running second case throw 500 Error

this.RelatedModel.query is not a function

Now If I restart the server and run the second case it'll work and the first one will stop working. Kindly help we're facing this issue. look like some kind of caching in issue in a query or in model ORM.

答:
When defining a relation, you need to give the namespace and not an instance of your model.
Your State model will become:

```<code>const Model = use('Model')

class State extends Model {

  city () {

    return this.hasMany('App/Models/City', 'id', 'state_id')

  }

  stateCountry () {

  return this.belongsTo('App/Models/Country', 'country_id', 'id')

  }

}
</code>```

Update all your model and everything should work fine.

Body:
I have 3 model Country, State, City
country.js

  state () {
    return this.hasMany(State, 'id', 'country_id')
  }

state.js

 city () {
    return this.hasMany(City, 'id', 'state_id')
  }

  stateCountry () {
    return this.belongsTo(Country, 'country_id', 'id')
  }

city.js

cityState () {
    return this.belongsTo(State, 'state_id', 'id')
  }

Now I'm trying to get two type of data
1. From country > state > city ( normal relation )
2. From city > state > country ( inverse relation )

case 1:
const countries = await Country.query()
          .with('state.city')
          .fetch()

case 2:
const citties = await City.query()
      .with('cityState.stateCountry')
      .fetch()

Now whichever I run first will work and give me proper result however running second case throw 500 Error

this.RelatedModel.query is not a function

Now If I restart the server and run the second case it'll work and the first one will stop working. Kindly help we're facing this issue. look like some kind of caching in issue in a query or in model ORM.

Body:
When defining a relation, you need to give the namespace and not an instance of your model.
Your State model will become:

const Model = use('Model')

class State extends Model {

  city () {

    return this.hasMany('App/Models/City', 'id', 'state_id')

  }

  stateCountry () {

  return this.belongsTo('App/Models/Country', 'country_id', 'id')

  }

}

Update all your model and everything should work fine.


问:
FileWriter not writing to file with protocol in URL
I am using the code below to write to file.

```<code>FileWriter writer = new FileWriter(outputPath);
writer.append(prettyJson);
writer.flush();
writer.close();
</code>```

I notice that the content is not written to the file path starts with "file://". Any specific reason for this ?

答:
The javadoc says:

public FileWriter(String fileName)
             throws IOException

Constructs a FileWriter object given a file name.

Thus: when using this interface, you can not pass an URL, or URI or anything that legally could start with file://.

In other words: this works as designed. This constructor expects a file name, plain and simple.

If you have a URL-like string, try something like this:

```<code>URL fileURL = new URL("file://C:/whatever.txt");
InputStream is = fileURL.openStream();
</code>```

Or simply create a File object from that UIR you got. To then pass that file object to a the slightly different constructor of FileWriter.

Body:
I am using the code below to write to file.

FileWriter writer = new FileWriter(outputPath);
writer.append(prettyJson);
writer.flush();
writer.close();

I notice that the content is not written to the file path starts with "file://". Any specific reason for this ?

Body:
The javadoc says:

public FileWriter(String fileName)
             throws IOException

Constructs a FileWriter object given a file name.

Thus: when using this interface, you can not pass an URL, or URI or anything that legally could start with file://.

In other words: this works as designed. This constructor expects a file name, plain and simple.

If you have a URL-like string, try something like this:

URL fileURL = new URL("file://C:/whatever.txt");
InputStream is = fileURL.openStream();

Or simply create a File object from that UIR you got. To then pass that file object to a the slightly different constructor of FileWriter.


问:
How to get the table name that contains a certain ID?
I have several tables that contain an ID with the word "MRCPUBSY"
(Example: TABLE ID="_MIPS-MRCPUBSY").

How  can I get this table if I only know a part of the ID NAME?

I thought to use something like:
var MyTable = document.getElementById('MRCPUBSY'.value)
but this is not okay because the NAME of the ID is _MIPS-MRCPUBSY and not just MRCPUBSY.

答:
You can use an attribute contains selector, [id*=MRCPUBSY].

For instance, to get the first such table:

```<code>var myTable = document.querySelector("[id*=MRCPUBSY]");
</code>```

Body:
You can use an attribute contains selector, [id*=MRCPUBSY].

For instance, to get the first such table:

var myTable = document.querySelector("[id*=MRCPUBSY]");


问:
Add AdBanner globally to all screens
Is there a way to add on AdBanner for the whole App? For example like with a PageViewController to all its childs.

But is it possible to add one AdBanner globally?

If so, is there a way to additionally skip one?

答:
You can add it as a subview to app window

```<code>let wind = (UIApplication.shared.delegate as! AppDelegate).window!
adBanner.tag = 22
wind.addSubview(adBanner)
</code>```

Then you can access the ad inside the one you need to hide and do

```<code>let ad = wind.viewWithTag(22) as! AdBanner
ad.isHidden = true/false
</code>```

Title: Add AdBanner globally to all screens

Body:
You can add it as a subview to app window

let wind = (UIApplication.shared.delegate as! AppDelegate).window!
adBanner.tag = 22
wind.addSubview(adBanner)

Then you can access the ad inside the one you need to hide and do

let ad = wind.viewWithTag(22) as! AdBanner
ad.isHidden = true/false


问:
How to change a file input's FileList programmatically?
I have this input of type "file", and I want to change its files list.  Example:

```<code><input type = "file" id = "fileinput" />
<script type = "text/javascript">
  document.getElementById("fileinput").files = [10];
</script>
</code>```

The problem is that the fileinput element's files list is not set. How do I do it?

答:
For security reasons, browsers prevent javascript from changing the files which will be uploaded: only the user can select files via the user interface. This is to prevent an evil script to upload /etc/passwd, for example, without the user knowing.

The one exception is that calling "reset" on the form will clear the file or filelist, but you can never add to programmatically.

Body:
I have this input of type "file", and I want to change its files list.  Example:

<input type = "file" id = "fileinput" />

The problem is that the fileinput element's files list is not set. How do I do it?


问:
how to convert date to date drop down and drop down could be separate day, month,year
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

```

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table

答:
In your Django form, set the widget for your DateField to the SelectDateWidget (import it from django.forms.widgets). Then you only need to do {{ form.date_of_birth }} in your template.

```<code>class ProfileUpdateView(UpdateView):
    form_class = MyProfileForm

class MyProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        widgets = {'date_of_birth': SelectDateWidget()}
</code>```

Body:
]2

  Date of birth:
  <input type="date" name="date_of_birth" value="2019-06-14" id="id_date_of_birth">

i am getting data from database by using django and i am trying to show in drop down date but i am getting date table

Body:
In your Django form, set the widget for your DateField to the SelectDateWidget (import it from django.forms.widgets). Then you only need to do {{ form.date_of_birth }} in your template.

class ProfileUpdateView(UpdateView):
    form_class = MyProfileForm

class MyProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        widgets = {'date_of_birth': SelectDateWidget()}


答:
If you are trying to use a relative path go for:</p>

```<code>FileWriter fw = new FileWriter("./" + fileName, true);
</code>```

Title: FileWriter not writing to file with protocol in URL

Body:
If you are trying to use a relative path go for:

FileWriter fw = new FileWriter("./" + fileName, true);


答:
When Java talks about filenames in the form of String, the documentation usually says

The system-dependent filename

and thus it is expecting an "everyday" filename, like filename.ext, or something like c:\some\path\filename.ext on Windows, or /some/path/filename.ext on Unix-likes (this one actually works on both, Java accepts / as path separator on Windows too)

For a filename with file:// protocol, use URI and wrap it into a File:

```<code>FileWriter writer = new FileWriter(new File(new URI(outputPath)));
</code>```

Body:
When Java talks about filenames in the form of String, the documentation usually says

The system-dependent filename

and thus it is expecting an "everyday" filename, like filename.ext, or something like c:\some\path\filename.ext on Windows, or /some/path/filename.ext on Unix-likes (this one actually works on both, Java accepts / as path separator on Windows too)

For a filename with file:// protocol, use URI and wrap it into a File:

FileWriter writer = new FileWriter(new File(new URI(outputPath)));


问:
linked list the head always is set to NULL
I'm trying to add domino tales into a linked list but each time I make a call to the function add_domino(struct Domino *list, int a ,int b) the head always stays NULL:

```<code>void add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
}
</code>```

答:
You're missing the return with the updated pointer to the head.   </p>

```<code>struct Domino* add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
        return list;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
  return list;
}
</code>```

Body:
I'm trying to add domino tales into a linked list but each time I make a call to the function add_domino(struct Domino *list, int a ,int b) the head always stays NULL:

void add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
}

Body:
You're missing the return with the updated pointer to the head.

struct Domino* add_domino(struct Domino *list, int a ,int b) {
    struct Domino *D = malloc(sizeof(struct Domino));
    D->a = a;
    D->b = b;
    D->next = NULL;

    if(list == NULL) {
        list = D;
        return list;
    } else {
        struct Domino *p;
        p = list;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = D;
    }
  return list;
}


问:
How do you add tags to AWS security groups through Ansible?
I'm trying to manage AWS security groups through Ansible and want to add tags to them.
Can someone give me an example on how to do this?

For example I have a security group 'test_security_group' and I want to add a tag 'foo' to that security group.

According to Ansible documentation the ec2_tag module will work but I have not been successful in using it with security groups so far.

答:
As of ansible 2.4 you can specify tags directly</p>

```<code>- name: Create ec2 security group
  ec2_group:
    name: SSH
    description: SSH
    vpc_id: "{{ default_vpc_id }}"
    region: "{{ aws_region }}"
    tags:
      Name: SSH
      Tag1: Value1
      Tag2: Value2
    rules:
      - proto: tcp
        ports:
          - 22
        cidr_ip: 0.0.0.0/0
</code>```

Body:
As of ansible 2.4 you can specify tags directly

- name: Create ec2 security group
  ec2_group:
    name: SSH
    description: SSH
    vpc_id: "{{ default_vpc_id }}"
    region: "{{ aws_region }}"
    tags:
      Name: SSH
      Tag1: Value1
      Tag2: Value2
    rules:
      - proto: tcp
        ports:
          - 22
        cidr_ip: 0.0.0.0/0


问:
Solving linear equations where each matrix element itself is matrix (2D) and each variables are 1D vectors
The simple example of the problem is:

In my case:

Any idea/suggestion is highly appreciated.

答:
As long as the dimensions conform, A is actually "just" a matrix, even if it is built out of smaller matrices.  Here's a relatively general example showing how the dimensions must go:</p>

```<code>import numpy
import numpy.linalg

l, m, n, k = 2, 3, 4, 5

# if these are known, obviously just define them here.
A11 = numpy.random.random((l, m))
A12 = numpy.random.random((l, n))
A21 = numpy.random.random((k, m))
A22 = numpy.random.random((k, n))
x1 = numpy.random.random((m,))
x2 = numpy.random.random((n,))

A = numpy.bmat([[A11, A12],
                [A21, A22]])
x = numpy.concatenate([x1, x2])

b = numpy.linalg.solve(A, x)
</code>```

Body:
As long as the dimensions conform, A is actually "just" a matrix, even if it is built out of smaller matrices.  Here's a relatively general example showing how the dimensions must go:

import numpy
import numpy.linalg

l, m, n, k = 2, 3, 4, 5

# if these are known, obviously just define them here.
A11 = numpy.random.random((l, m))
A12 = numpy.random.random((l, n))
A21 = numpy.random.random((k, m))
A22 = numpy.random.random((k, n))
x1 = numpy.random.random((m,))
x2 = numpy.random.random((n,))

A = numpy.bmat([[A11, A12],
                [A21, A22]])
x = numpy.concatenate([x1, x2])

b = numpy.linalg.solve(A, x)


问:
How do I add a column to my data table that shows the sum of multiple other columns' values?
I have 8 age categories, with each of them having its own column (i.e. residents_under_5, residents_6_to_12, etc. Each column has a value between 0 and 3, for the number of people in that household in that specific age category.
What I want is a new column with which I can plot the total distribution of age of my population on a histogram. So I was thinking of a column that has 66 rows of residents_under_5, 32 rows of residents_6_to_12, etc., for the sum of those categories.

My data looks like this:

```<code>a b c d
0 3 2 1
1 3 2 1
2 0 2 1
3 1 0 0
</code>```

What I want is a column e that shows:

```<code>e
a
a
a
a
b
b
b
b
b
c
c
c
d
d
d
</code>```

For the total number of occurences in the other columns.

I've tried declaring new columns with sum(residents_under_5), but that will give me 1 row with 66 (as the sum of that category). I can't plot a histogram with such a column. I hope someone can figure it out!

This is the dput() of the relevant columns

```<code>residents_under_5 = c(0, 0, 0, 1, 1, 2),
residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
        residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
residents_19_to_24 = c(0,
        0, 0, 0, 0, 0),
residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
       residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
residents_50_to_64 = c(0,
        1, 0, 0, 0, 0),
residents_65_and_older = c(2, 0, 0, 0, 1,
        0)
</code>```

答:
An option in tidyverse would be to get the sum of all columns with summarise_all, gather into 'long' format and uncount the 'value' column

```<code>library(tidyverse)
df1 %>%
   summarise_all(sum) %>%
   gather %>%
   uncount(value)
</code>```

data

```<code>df1 <- structure(list(a = 0:3, b = c(3L, 3L, 0L, 1L), c = c(2L, 2L,
2L, 0L), d = c(1L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA,
  -4L))
</code>```

Body:
I have 8 age categories, with each of them having its own column (i.e. residents_under_5, residents_6_to_12, etc. Each column has a value between 0 and 3, for the number of people in that household in that specific age category.
What I want is a new column with which I can plot the total distribution of age of my population on a histogram. So I was thinking of a column that has 66 rows of residents_under_5, 32 rows of residents_6_to_12, etc., for the sum of those categories.

My data looks like this:

a b c d
0 3 2 1
1 3 2 1
2 0 2 1
3 1 0 0

What I want is a column e that shows:

e
a
a
a
a
b
b
b
b
b
c
c
c
d
d
d

For the total number of occurences in the other columns.

I've tried declaring new columns with sum(residents_under_5), but that will give me 1 row with 66 (as the sum of that category). I can't plot a histogram with such a column. I hope someone can figure it out!

This is the dput() of the relevant columns

residents_under_5 = c(0, 0, 0, 1, 1, 2),
residents_6_to_12 = c(0, 0, 0, 0, 0, 0),
        residents_13_to_18 = c(0, 0, 0, 0, 0, 0),
residents_19_to_24 = c(0,
        0, 0, 0, 0, 0),
residents_25_to_34 = c(0, 1, 2, 0, 1, 0),
       residents_35_to_49 = c(0, 0, 0, 2, 1, 2),
residents_50_to_64 = c(0,
        1, 0, 0, 0, 0),
residents_65_and_older = c(2, 0, 0, 0, 1,
        0)

Body:
An option in tidyverse would be to get the sum of all columns with summarise_all, gather into 'long' format and uncount the 'value' column

library(tidyverse)
df1 %>%
   summarise_all(sum) %>%
   gather %>%
   uncount(value)

data

df1 <- structure(list(a = 0:3, b = c(3L, 3L, 0L, 1L), c = c(2L, 2L,
2L, 0L), d = c(1L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA,
  -4L))


答:
Use the attribute contains selector:</p>

```<code>document.querySelector("[id*='MRCPUBSY']").value;
</code>```

Title: How to get the table name that contains a certain ID?

Body:
I have several tables that contain an ID with the word "MRCPUBSY"
(Example: TABLE ID="_MIPS-MRCPUBSY").

How  can I get this table if I only know a part of the ID NAME?

I thought to use something like:
var MyTable = document.getElementById('MRCPUBSY'.value)
but this is not okay because the NAME of the ID is _MIPS-MRCPUBSY and not just MRCPUBSY.

Body:
Use the attribute contains selector:

document.querySelector("[id*='MRCPUBSY']").value;


问:
Why does pandas.where() returning 'None'
I was trying to use pandas.where() to remove negative values from a column in a data frame.

The most obvious way to remove the negative values is to simply run pandas.abs() on the column.  So:

```<code>import pandas as pd

frame = pd.DataFrame([-1,-1,-3,-4,-5],columns=["amount"])

frame.amount = frame.amount.abs()
</code>```

But I wanted to try the same thing using pandas.where().  So I tried the following:

```<code>frame.amount = frame["amount"].where(frame["amount"] < 0, frame["amount"].abs(), inplace=True)
</code>```

Which returns:

```<code>Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  amount
0   None
1   None
2   None
3   None
4   None
</code>```

Two things confused me:

I was surprised I had to assign each expression (frame.amount = ...) because I thought calling the operation in either case would mutate the Dataframe (isn't that what 'inplace' should do?) and

why does pandas.where() return 'None'

答:
Try with:

```<code>frame["amount"].where(~(frame["amount"] < 0), frame["amount"].abs(), inplace=True)
#frame["amount"].mask(frame["amount"] < 0, frame["amount"].abs(), inplace=True)
print(frame)
</code>```

series.where() says:

Where cond is True, keep the original value. Where False, replace with corresponding value from other.

So the condition has to be false for assigning.
Similar is series.mask() which says:

Replace values where the condition is True.

So we can use the same as well.

Regarding inplace=True, when you use this, there is no need to assign the results back as inplace=True does the operation inplace which is as good as not using inplace and assigning the results back. inplace=True returns None which if you assign back to the series, you will be left will None

Body:
I was trying to use pandas.where() to remove negative values from a column in a data frame.

The most obvious way to remove the negative values is to simply run pandas.abs() on the column.  So:

import pandas as pd

frame = pd.DataFrame([-1,-1,-3,-4,-5],columns=["amount"])

frame.amount = frame.amount.abs()

But I wanted to try the same thing using pandas.where().  So I tried the following:

frame.amount = frame["amount"].where(frame["amount"] < 0, frame["amount"].abs(), inplace=True)

Which returns:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
  amount
0   None
1   None
2   None
3   None
4   None

Two things confused me:

I was surprised I had to assign each expression (frame.amount = ...) because I thought calling the operation in either case would mutate the Dataframe (isn't that what 'inplace' should do?) and

why does pandas.where() return 'None'

Body:
Try with:

frame["amount"].where(~(frame["amount"] < 0), frame["amount"].abs(), inplace=True)
#frame["amount"].mask(frame["amount"] < 0, frame["amount"].abs(), inplace=True)
print(frame)

series.where() says:

Where cond is True, keep the original value. Where False, replace with corresponding value from other.

So the condition has to be false for assigning.
Similar is series.mask() which says:

Replace values where the condition is True.

So we can use the same as well.

Regarding inplace=True, when you use this, there is no need to assign the results back as inplace=True does the operation inplace which is as good as not using inplace and assigning the results back. inplace=True returns None which if you assign back to the series, you will be left will None


问:
how to count a 0 modulus in a list
I have created a list and an iteration loop for this list. I am trying to count all the even numbers using the modulus operator.  I have initialised the count variable and used the count increment and an if statement to catch all the even numbers in a nested loop. However all I get is the number one. count equals 1, is this because of using modulus incorrectly, and item = 10 , is this because of the iteration loop reaching its end of the list?

I don't know what to change, the code structure all looks ok to me.  I tried indenting the print function. This showed me that the modulus is catching the even numbers but the count is not totalling these.

```<code>list = [1,2,3,4,5,6,7,8,9,10]
for item in list:
    count = 0
    if (item % 2 == 0):
        count = count + 1
print(count)
print(item)
print(list)
</code>```

I expect the number 5 as the result of the program as there are 5 even numbers in the list

答:
You can use Python generators and sum built-in function instead of manual iteration through the list:

```<code>lst = [1,2,3,4,5,6,7,8,9,10]
count = sum(n % 2 == 0 for n in lst)
print(lst)
print(count)
</code>```

will print you:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5

Title: how to count a 0 modulus in a list

Body:
I have created a list and an iteration loop for this list. I am trying to count all the even numbers using the modulus operator.  I have initialised the count variable and used the count increment and an if statement to catch all the even numbers in a nested loop. However all I get is the number one. count equals 1, is this because of using modulus incorrectly, and item = 10 , is this because of the iteration loop reaching its end of the list?

I don't know what to change, the code structure all looks ok to me.  I tried indenting the print function. This showed me that the modulus is catching the even numbers but the count is not totalling these.

list = [1,2,3,4,5,6,7,8,9,10]
for item in list:
    count = 0
    if (item % 2 == 0):
        count = count + 1
print(count)
print(item)
print(list)

I expect the number 5 as the result of the program as there are 5 even numbers in the list

Body:
You can use Python generators and sum built-in function instead of manual iteration through the list:

lst = [1,2,3,4,5,6,7,8,9,10]
count = sum(n % 2 == 0 for n in lst)
print(lst)
print(count)

will print you:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

5


问:
How to store values of an input_tag in a variable?
I am trying to send data from an input_tag when I press a button with the templates in mojolicious.

```<code>use Mojolicious::Lite;

get '/' => 'index';

app->start;
__DATA__

@@ index.html.ep
<html lang="es">
  <head>
    <meta charset="utf-8"/>
    <title>Graphs</title>
  </head>
  <body>
    <%= tag div => (id => 'inputs') => begin %>
        <h1>Grafos dirigidos</h1>
        %= input_tag 'nodes', placeholder => '#Nodos', id => 'nodes'
        %= input_tag 'edges', placeholder => '#Edges', id => 'edges'
        %= input_tag 'start', placeholder => 'Start', id => 'start'
        %= submit_button 'Generate', id => 'render', onclick => 'renderGraph()'
        %= tag 'br'
        %= text_area 'dijkstra', cols => 40, rows => 40, id => 'dijkstra'
    <% end %>
</code>```

When I press the "generate" button I want to send that data in the inputs to another perl script.

答:
Add a form, grab the input values and send them e.g. as arguments to the perl script.</p>

```<code>use Mojolicious::Lite;

get '/' => 'index';

post '/' => sub {
    my $c = shift;

    my ($nodes, $edges, $start) = map { $c->param($_) } qw(nodes edges start);

    system 'script.pl', '--nodes', $nodes, '--edges', $edges, '--start', $start;

    $c->render(text => 'done');
};

app->start;
__DATA__

@@ index.html.ep
<html lang="es">
  <head>
    <meta charset="utf-8"/>
    <title>Graphs</title>
  </head>
  <body>
    <form method="post">
        <%= tag div => (id => 'inputs') => begin %>
            <h1>Grafos dirigidos</h1>
            %= input_tag 'nodes', placeholder => '#Nodos', id => 'nodes'
            %= input_tag 'edges', placeholder => '#Edges', id => 'edges'
            %= input_tag 'start', placeholder => 'Start', id => 'start'
            %= submit_button 'Generate', id => 'render', onclick => 'renderGraph()'
            %= tag 'br'
            %= text_area 'dijkstra', cols => 40, rows => 40, id => 'dijkstra'
        <% end %>
    </form>
</code>```

Body:
I am trying to send data from an input_tag when I press a button with the templates in mojolicious.

use Mojolicious::Lite;

get '/' => 'index';

app->start;
__DATA__

@@ index.html.ep

    <meta charset="utf-8"/>
    <title>Graphs</title>

    <%= tag div => (id => 'inputs') => begin %>

Grafos dirigidos

        %= input_tag 'nodes', placeholder => '#Nodos', id => 'nodes'
        %= input_tag 'edges', placeholder => '#Edges', id => 'edges'
        %= input_tag 'start', placeholder => 'Start', id => 'start'
        %= submit_button 'Generate', id => 'render', onclick => 'renderGraph()'
        %= tag 'br'
        %= text_area 'dijkstra', cols => 40, rows => 40, id => 'dijkstra'
    <% end %>

When I press the "generate" button I want to send that data in the inputs to another perl script.

Body:
Add a form, grab the input values and send them e.g. as arguments to the perl script.

use Mojolicious::Lite;

get '/' => 'index';

post '/' => sub {
    my $c = shift;

    my ($nodes, $edges, $start) = map { $c->param($_) } qw(nodes edges start);

    system 'script.pl', '--nodes', $nodes, '--edges', $edges, '--start', $start;

    $c->render(text => 'done');
};

app->start;
__DATA__

@@ index.html.ep
<html lang="es">
  <head>
    <meta charset="utf-8"/>
    <title>Graphs</title>
  </head>
  <body>
    <form method="post">
        <%= tag div => (id => 'inputs') => begin %>
            <h1>Grafos dirigidos</h1>
            %= input_tag 'nodes', placeholder => '#Nodos', id => 'nodes'
            %= input_tag 'edges', placeholder => '#Edges', id => 'edges'
            %= input_tag 'start', placeholder => 'Start', id => 'start'
            %= submit_button 'Generate', id => 'render', onclick => 'renderGraph()'
            %= tag 'br'
            %= text_area 'dijkstra', cols => 40, rows => 40, id => 'dijkstra'
        <% end %>
    </form>


问:
How to get type of ERRORS in TypeScript?
I used yaml
https://www.npmjs.com/package/yaml
I want to catch the error and to check the insatnce

```<code>    import * as yaml from 'yaml';
    try{
        const yamlParse: any = yaml.parse(data);
    } catch(err){
    if ( err instanceof YAMLError)
...
    }
</code>```

The problem that the compile doesn't know YAMLError
I tried also
yaml.YAMLError

I define in package.json

```<code>"@types/yaml": "1.0.2",
    "yaml": "^1.5.1"
</code>```

答: you are probably missing the import  import { YAMLError } from '@types/yaml'; on top

Body:
I used yaml
https://www.npmjs.com/package/yaml
I want to catch the error and to check the insatnce

    import * as yaml from 'yaml';
    try{
        const yamlParse: any = yaml.parse(data);
    } catch(err){
    if ( err instanceof YAMLError)
...
    }

The problem that the compile doesn't know YAMLError
I tried also
yaml.YAMLError

I define in package.json

"@types/yaml": "1.0.2",
    "yaml": "^1.5.1"


问:
ASP.NET: Implementing Init and Dispose methods
Can an ASP.NET web application have only one Init and one Dispose method or can I implement these per class for those which I want to associate such methods?

More specifically I have Customer component and a CustomerRecord classes and would like to implement Init and Dispose methods in both of them.

What is the proper way to do this?

Requirement:

I want to have independent Init and Dispose methods for each aforementioned class.

答:
You can create a base class with the Init and Dispose method as you wish and then make the other classes to inherit from it. For example:

```<code>public class BaseClass
{
    public void Init()
    {
        //Some code
    }

    public void Dispose()
    {
        //Some code
    }
}

public class Customer : BaseClass
{
    //Some code
}
</code>```

That might help you.

Body:
You can create a base class with the Init and Dispose method as you wish and then make the other classes to inherit from it. For example:

public class BaseClass
{
    public void Init()
    {
        //Some code
    }

    public void Dispose()
    {
        //Some code
    }
}

public class Customer : BaseClass
{
    //Some code
}

That might help you.


问:
How can i apply Unit Testing on my simple algorithm?
I have a maven project that draws Christmas tree. I need to implement Unit tests on it but i have no idea how to do it :/  </p>

<p>I already set up , JUnit on my Maven project </p>

```<code>for (int i = 0; i < 4; i++) {
   for (int j = 0; j < 10 - i; j++)
    System.out.print(" ");
   for (int k = 0; k < (2 * i + 1); k++)
    System.out.print("*");
   System.out.println();
  }
</code>```

答:
At a high level: the purpose of that code is to print a tree or triangle made of asterisks.  The test is simple, run the code and see of it generates the desired output.

Since the code is printing to System.out you will need to redirect System.out to a file or a string (see this) then compare the generated output to the desired output to see of the code is operating properly.

Body:
I have a maven project that draws Christmas tree. I need to implement Unit tests on it but i have no idea how to do it :/

I already set up , JUnit on my Maven project

for (int i = 0; i < 4; i++) {
   for (int j = 0; j < 10 - i; j++)
    System.out.print(" ");
   for (int k = 0; k < (2 * i + 1); k++)
    System.out.print("*");
   System.out.println();
  }


问:
Is it possible to read GML or KML files with Fiona?
I'd like to know if it's possible to read/write GML files (or even KML files) using Fiona.

Fiona documents don't specify what drivers we can use. I read some answers about the drivers that are avalaible but I still haven't figured out the right answer.

These two different sentences print a different number of drivers. The first one doesn't include GML o KML (in fact there are very few formats supported).

```<code>print(fiona.supported_drivers)
</code>```

vs

```<code>print('\n'.join(sorted(fiona.drivers().drivers())))
</code>```

I know how to do it using GDAL/OGR but I want to do the same using Fiona if it's possible.

答: I've just found out that the newest version of Fiona added support to read and write GML files.</p>

Body:
I'd like to know if it's possible to read/write GML files (or even KML files) using Fiona.

Fiona documents don't specify what drivers we can use. I read some answers about the drivers that are avalaible but I still haven't figured out the right answer.

These two different sentences print a different number of drivers. The first one doesn't include GML o KML (in fact there are very few formats supported).

print(fiona.supported_drivers)

vs

print('\n'.join(sorted(fiona.drivers().drivers())))

I know how to do it using GDAL/OGR but I want to do the same using Fiona if it's possible.


问:
Setting many to many relationship in laravel with stock attribute
I'm working on an e-commerce web where you can buy some items, say shirts... I have three models Item, ItemColor and ItemSize. I have set up a many to many relationship where an item in the shop can have many colors and many sizes available but each of these items will have a stock on its own, here is where things get complicated for me.

If I create an item, for example a shirt X, I can attach to that shirt different colors and sizes available (many to many), a shirt with black color and size M will have three in stock, but how can I set up so each type of shirt has a stock?? I'm failing to see this in a clear way...

Where should I put stock attribute? in pivot table maybe?

Here are my models and migrations:

```<code>//item model
protected $table = 'items';

    public function colors()
    {
        return $this->belongsToMany('App\Models\ItemColor');
    }

    public function sizes()
    {
        return $this->belongsToMany('App\Models\ItemSize');
    }

//tiemsize model

protected $table = 'item_sizes';

    public function items()
    {
        return $this->belongsToMany('App\Models\Item');
    }

//item colors

protected $table = 'item_colors';

    public function items()
    {
        return $this->belongsToMany('App\Models\Item');
    }
</code>```

And migrations

```<code>
//pivot table
Schema::create('item_size_color', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index();
            $table->foreign('item_id')->references('id')->on('items');
            $table->unsignedInteger('item_size_id')->index();
            $table->foreign('item_size_id')->references('id')->on('item_sizes');
            $table->unsignedInteger('item_color_id')->index();
            $table->foreign('item_color_id')->references('id')->on('item_sizes');
            $table->timestamps();
        });

//items table
Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

//items color table
Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

//items size table
Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
</code>```

Mock up controller method, how can I set stock?

```<code>public function create(Create $request)
    {
        $item = new Item();
        $item->colors->attach($request->input('availableColors'));
        $item->sizes->attach($request->input('availableSizes'));
        $item->sizes = $request->input('color');
        $title = $request('title');
        if($request->hasFile('image')){ $item->image = $this->uploadFile($request, 'image'); }
        $item->save();

        $item->load('sizes');
        $item->load('colors');

        return response()->json([
            'item' => $item,
        ]);

    }
</code>```

答:
I think belongsToMany doesn't fit for you, and you should add independent entity ItemOption and work with it in controller, view, requests.

Models:

```<code>class ItemOption extens Model
{
    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }
}

class Item extens Model
{
    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }
}
</code>```

Controller:

```<code>public function create(Create $request)
{
    $item = new Item();
    $item->title = $request->input('title');;

    if($request->hasFile('image')){
        $item->image = $this->uploadFile($request, 'image');
    }

    $item->save();

    foreach($request->input('options') as $option){
        $option = $item->options()->firstOrNew([
            'item_size_id' = $option['size_id'],
            'item_color_id' = $option['color_id']
        ]);

        $option->stock = $option['stock'];
        $option->save();
    }

    $item->load('options');
    $item->load('sizes');
    $item->load('colors');

    //or $item->load(['options.size', 'options.color']);

    return response()->json([
        'item' => $item,
    ]);
}
</code>```

Body:
I'm working on an e-commerce web where you can buy some items, say shirts... I have three models Item, ItemColor and ItemSize. I have set up a many to many relationship where an item in the shop can have many colors and many sizes available but each of these items will have a stock on its own, here is where things get complicated for me.

If I create an item, for example a shirt X, I can attach to that shirt different colors and sizes available (many to many), a shirt with black color and size M will have three in stock, but how can I set up so each type of shirt has a stock?? I'm failing to see this in a clear way...

Where should I put stock attribute? in pivot table maybe?

Here are my models and migrations:

//item model
protected $table = 'items';

    public function colors()
    {
        return $this->belongsToMany('App\Models\ItemColor');
    }

    public function sizes()
    {
        return $this->belongsToMany('App\Models\ItemSize');
    }

//tiemsize model

protected $table = 'item_sizes';

    public function items()
    {
        return $this->belongsToMany('App\Models\Item');
    }

//item colors

protected $table = 'item_colors';

    public function items()
    {
        return $this->belongsToMany('App\Models\Item');
    }

And migrations

//pivot table
Schema::create('item_size_color', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('item_id')->index();
            $table->foreign('item_id')->references('id')->on('items');
            $table->unsignedInteger('item_size_id')->index();
            $table->foreign('item_size_id')->references('id')->on('item_sizes');
            $table->unsignedInteger('item_color_id')->index();
            $table->foreign('item_color_id')->references('id')->on('item_sizes');
            $table->timestamps();
        });

//items table
Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

//items color table
Schema::create('item_colors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

//items size table
Schema::create('item_sizes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });

Mock up controller method, how can I set stock?

public function create(Create $request)
    {
        $item = new Item();
        $item->colors->attach($request->input('availableColors'));
        $item->sizes->attach($request->input('availableSizes'));
        $item->sizes = $request->input('color');
        $title = $request('title');
        if($request->hasFile('image')){ $item->image = $this->uploadFile($request, 'image'); }
        $item->save();

        $item->load('sizes');
        $item->load('colors');

        return response()->json([
            'item' => $item,
        ]);

    }

Body:
I think belongsToMany doesn't fit for you, and you should add independent entity ItemOption and work with it in controller, view, requests.

Models:

class ItemOption extens Model
{
    protected $fillable = ['item_id', 'item_color_id', 'item_size_id', 'stock'];

    public function color()
    {
        return $this->belongsTo(ItemColor::class);
    }

    public function size()
    {
        return $this->belongsTo(ItemSize::class);
    }
}

class Item extens Model
{
    public function options()
    {
        return $this->hasMany(ItemOption::class);
    }

    public function sizes()
    {
        return $this->hasManyThrough(ItemSize::class, ItemOption::class);
    }

    public function colors()
    {
        return $this->hasManyThrough(ItemColor::class, ItemOption::class);
    }
}

Controller:

public function create(Create $request)
{
    $item = new Item();
    $item->title = $request->input('title');;

    if($request->hasFile('image')){
        $item->image = $this->uploadFile($request, 'image');
    }

    $item->save();

    foreach($request->input('options') as $option){
        $option = $item->options()->firstOrNew([
            'item_size_id' = $option['size_id'],
            'item_color_id' = $option['color_id']
        ]);

        $option->stock = $option['stock'];
        $option->save();
    }

    $item->load('options');
    $item->load('sizes');
    $item->load('colors');

    //or $item->load(['options.size', 'options.color']);

    return response()->json([
        'item' => $item,
    ]);
}


问:
How to get a system date change notification in .NET core on linux?
I'm trying to get a notification event in .NET core/Standard (as I need to do plan  future actions). I'm porting a piece of existing .NET4.5x code to .NET core 2.2 or .NETStandard2.

Originally I was using:

```<code>SystemEvents.TimeChanged += SystemEvents_TimeChanged; //my handler
</code>```

But in .NETCore or .NETStandard, this is not implemented.

What is the most elegant way to overcome that?

答:
OK, so finally I did it that way (pseudo code):

```<code>public TimeSpan CheckInterval { get; private set; } = TimeSpan.FromMinutes(1);
public TimeSpan MaxAllowedDeviation { get; private set; } = TimeSpan.FromSeconds(1);

private async Task CheckTimeUpdate()
{
    while (cancelToken.IsCancellationRequested == false)
    {
        DateTimeOffset beforeTimer = DateTimeOffset.Now;

        await Task.Delay(CheckInterval, cancelToken);

        DateTimeOffset afterTimer = DateTimeOffset.Now;

        if ((afterTimer.UtcDateTime - beforeTimer.UtcDateTime).Duration() > MaxAllowedDeviation + CheckInterval)
        {
            //raises the event
            TimeChanged?.Invoke();
        }
    }
}
</code>```

But this only works for manual time change, not for daylight saving nor time zone updates!!

Body:
I'm trying to get a notification event in .NET core/Standard (as I need to do plan  future actions). I'm porting a piece of existing .NET4.5x code to .NET core 2.2 or .NETStandard2.

Originally I was using:

SystemEvents.TimeChanged += SystemEvents_TimeChanged; //my handler

But in .NETCore or .NETStandard, this is not implemented.

What is the most elegant way to overcome that?

Body:
OK, so finally I did it that way (pseudo code):

public TimeSpan CheckInterval { get; private set; } = TimeSpan.FromMinutes(1);
public TimeSpan MaxAllowedDeviation { get; private set; } = TimeSpan.FromSeconds(1);

private async Task CheckTimeUpdate()
{
    while (cancelToken.IsCancellationRequested == false)
    {
        DateTimeOffset beforeTimer = DateTimeOffset.Now;

        await Task.Delay(CheckInterval, cancelToken);

        DateTimeOffset afterTimer = DateTimeOffset.Now;

        if ((afterTimer.UtcDateTime - beforeTimer.UtcDateTime).Duration() > MaxAllowedDeviation + CheckInterval)
        {
            //raises the event
            TimeChanged?.Invoke();
        }
    }
}

But this only works for manual time change, not for daylight saving nor time zone updates!!


问:
Wordpress author page link redirets to top page
I'm trying to figure out whats wrong with this website's author page link. The author.php is placed on the theme folder correctly.

This is the only code I have to link it:

```<code><p class="autor">por <?php get_the_author_posts_link(); ?></p>
</code>```

Here is an example of author page link:
https://aoriente.com/news/author/goncaloasm/

And here is a post. The author link is just bellow the tittle:
https://aoriente.com/news/688/

What might be wrong?

答:
We have used your plugin where Wordpress author page link redirets to top page

```<code>plugin- https://wordpress.org/plugins/wordpress-seo/

https://wordpress.org/plugins/redirection/

https://wordpress.org/plugins/simple-301-redirects/
</code>```

Redirect old domain to a new domain

```<code>Here’s the code that you will need to add to the .htaccess file of the
old domain.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$
RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
</IfModule>
</code>```

Body:
I'm trying to figure out whats wrong with this website's author page link. The author.php is placed on the theme folder correctly.

This is the only code I have to link it:

por <?php get_the_author_posts_link(); ?>

Here is an example of author page link:
https://aoriente.com/news/author/goncaloasm/

And here is a post. The author link is just bellow the tittle:
https://aoriente.com/news/688/

What might be wrong?

Body:
We have used your plugin where Wordpress author page link redirets to top page

plugin- https://wordpress.org/plugins/wordpress-seo/

https://wordpress.org/plugins/redirection/

https://wordpress.org/plugins/simple-301-redirects/

Redirect old domain to a new domain

Here’s the code that you will need to add to the .htaccess file of the
old domain.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.olddomain\.com$
RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
</IfModule>


问:
Is it OK for Xcode project names to contains dashes? Are underscores preferred?
Are dashes or underbars preferred in Xcode project names? Does it matter? Should I use neither?
I want to break out my project into several sub-projects and use a workspace.

MyApp-iOS-UI

MyApp-iOS-Model

vs.

MyApp_iOS_UI

MyApp_iOS_Model

vs.

MyAppiOSUI

MyAppiOSModel

I haven't easily been able to find a definitive answer. It's my first Xcode project and I don't want to hit a snag.

I want to support back to iOS 9, if possible. The app will also need to interact with a macOS app at some point, so I'll need a macOS project folder too.

答: This SO question might help. Basically, underscore is preferred, as non-alphanumeric characters are replaced with underscore anyway.</p>


问:
error while setting image in imageView in iphone
I have written a code for setting imageview ...as per the button clicked...but my problem is when i press the button it is giving me the error like...too many arguments to function ImageNamed...while executing this line...

UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];

the whole code is....

```<code>-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView]; }
</code>```

答:
use UIImage* photo = [UIImage imageNamed:[NSString stringWithFormat:@"robort de nero%d.jpg",x]];

cheers :)

Body:
I have written a code for setting imageview ...as per the button clicked...but my problem is when i press the button it is giving me the error like...too many arguments to function ImageNamed...while executing this line...

UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];

the whole code is....

-(void)buttonClicked:(UIButton*)button
{
NSLog(@"%d",button.tag);
int x;
x=button.tag;
// Create the image view.
UIImage* photo = [UIImage imageNamed:@"robort %d.jpg",x];
NSLog(@"%d",x);
CGSize photoSize = [photo size];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)];
[imageView setImage:photo];
[self.view addSubview:imageView]; }


问:
How to convert AT TIME ZONE return value to actual datetime value in SQL Server 2016?
I want to convert UTC value to Eastern Time Zone (any time zone) in SQL directly. I am trying below query but getting DATETIMEOFFSET.

I am trying to convert below UTC DateTime into Eastern time zone.

```<code>SELECT CONVERT(DATETIME,'2019-05-27 13:00:00' AT TIME ZONE 'Eastern Standard Time'
</code>```

I am expecting output for above query is '2019-05-27 09:00:00' but the actual output is coming like '2019-05-27 13:00:00 -04:00'

答:
You're close. So far, you've told SQL Server the native time zone for the datetime that you've passed in. Now you need to tell it to convert it to something else. This should do the trick:

```<code>SELECT CONVERT(DATETIME,'2019-05-27 13:00:00')
   AT TIME ZONE 'Eastern Standard Time'
   AT TIME ZONE 'UTC';
</code>```

This should give you something with the -00:00 offset. If you don't want that, cast the result back to a time zone-less datatype.

Body:
I want to convert UTC value to Eastern Time Zone (any time zone) in SQL directly. I am trying below query but getting DATETIMEOFFSET.

I am trying to convert below UTC DateTime into Eastern time zone.

SELECT CONVERT(DATETIME,'2019-05-27 13:00:00' AT TIME ZONE 'Eastern Standard Time'

I am expecting output for above query is '2019-05-27 09:00:00' but the actual output is coming like '2019-05-27 13:00:00 -04:00'

Body:
You're close. So far, you've told SQL Server the native time zone for the datetime that you've passed in. Now you need to tell it to convert it to something else. This should do the trick:

SELECT CONVERT(DATETIME,'2019-05-27 13:00:00')
   AT TIME ZONE 'Eastern Standard Time'
   AT TIME ZONE 'UTC';

This should give you something with the -00:00 offset. If you don't want that, cast the result back to a time zone-less datatype.


问:
Get avalue from json list from API response in postman
Need to get Value of Id for DisplayName": "Samsung XCover 4 from API response
I tried this but not working.

```<code>    var response = JSON.parse(responseBody);
    {
    var count = Object.keys(response.Offerings[0]);
    console.log(count);
    for(var x =0; x <=count.length ; x++)
    {
    if(count[x] == 'Id')
    {
    var val =
    console.log(response.Offerings[0].count[x]);
    // console.log(pm.environment.get(count['Id']));
    }
    }
    }
</code>```

Response from API:

```<code>   {
   "Offerings": [
    {
            "Amount": 292,
            "CurrencyCode": "CAD",
            "DisplayName": "Samsung XCover 4",
            "Id": 1910256761716000500,
            "Language": "en-CA",
            "LineOfBusinesses": [
                10048
            ],
            "MarketingViews": [],
            "Name": "Samsung XCover 4",
            "OfferType": 1,
            "ShortDescription": "Offering bundle includes:\n- Airtime Product\n- Samsung XCover 4 device\n- SIM Card\n- & optional device protection",
</code>```

I have a log list of DisplayName & Id but i need to use the Id for "DisplayName": "Samsung XCover 4" in body of other API.

答:
var response = JSON.parse(responseBody); for(var i=0; i<=response.Offerings.length ; i++) { if(response.Offerings[i].DisplayName == 'Samsung Galaxy S9+') { console.log(response.Offerings[i].Id); } }
I am getting Is as 1910256760591000600 but it's automatically round off.

Is there any way to stop the rounding off and get the exact Id from response?

Body:
Need to get Value of Id for DisplayName": "Samsung XCover 4 from API response
I tried this but not working.

    var response = JSON.parse(responseBody);
    {
    var count = Object.keys(response.Offerings[0]);
    console.log(count);
    for(var x =0; x <=count.length ; x++)
    {
    if(count[x] == 'Id')
    {
    var val =
    console.log(response.Offerings[0].count[x]);
    // console.log(pm.environment.get(count['Id']));
    }
    }
    }

Response from API:

   {
   "Offerings": [
    {
            "Amount": 292,
            "CurrencyCode": "CAD",
            "DisplayName": "Samsung XCover 4",
            "Id": 1910256761716000500,
            "Language": "en-CA",
            "LineOfBusinesses": [
                10048
            ],
            "MarketingViews": [],
            "Name": "Samsung XCover 4",
            "OfferType": 1,
            "ShortDescription": "Offering bundle includes:\n- Airtime Product\n- Samsung XCover 4 device\n- SIM Card\n- & optional device protection",

I have a log list of DisplayName & Id but i need to use the Id for "DisplayName": "Samsung XCover 4" in body of other API.


问:
Traefik HA with persistent volume
Is there currently any way to utilize kubernetes persistent volumes instead of a KV store in order to store Let's encrypt certificates?

From the documentation, storing let's encrypt information inside a json file cannot be used to share info across traefik pods. But I was wondering about other solutions, maybe boltdb on a shared volume?

答:
According the official document of Traefik HA, it seems you have only one option in order traefik detect those certificates within a cluster mode.

As a Key Value Store Entry

ACME certificates can be stored in a KV Store entry. This kind of storage is mandatory in cluster mode.

Title: Traefik HA with persistent volume


问:
I am trying to do a group by with two fields and sum but can not seem to be able to make it work for me. Any help would be much appreciated
I want to transform XML to JSON below are my details and requirement.

I have below XMl:

```<code>    <Message>
    <OrderList>
        <Order>
            <PaymentMethods>
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="1111" CreditCardType="VISA" AmountToRefund="10" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="2222" CreditCardType="MASTER" AmountToRefund="20" />
            </PaymentMethods>
        </Order>
        <Order>
            <PaymentMethods>
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="1111" CreditCardType="VISA" AmountToRefund="10" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="2222" CreditCardType="MASTER" AmountToRefund="20" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="3333" CreditCardType="VISA" AmountToRefund="12" />
            </PaymentMethods>
        </Order>
    </OrderList>
</Message>
</code>```

I have tried below by using groupBy and sum using below code but didn't get expected output, as shown in below:

```<code>    {
    "template_attributes": {
        "payment_methods": payload.Message.OrderList..*PaymentMethod groupBy ($.CreditCardType ++ $.CreditCardNo) map ((paymentMethod, index) -> {
            "first_name": paymentMethod.@FirstName,
            "last_name": paymentMethod.@LastName,
            "card_type": paymentMethod.@CreditCardType,
            "card_no": paymentMethod.@CreditCardNo,
            "amount_to_refund": paymentMethod.@AmountToRefund,
            "payment_type": sum paymentMethod.@PaymentType

        })
        }
}
</code>```

I want below Output, where all the payment methods should be combined based on the card_type and credit_card_no:

```<code> template_attributes:{
    payment_methods:[
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "1111",
            card_type: "VISA",
            amount: "20"
        },
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "2222",
            card_type: "MASTER",
            amount: "40"
        },
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "3333",
            card_type: "VISA",
            amount: "12"
        }
    ]
}
</code>```

答:
Hi I think you are using mule 3.x so dw 1.0. Then the solution for your problem is. Use the pluck operator to work over an object as if it were an array of key value pairs. </p>

```<code>{
  "template_attributes": {
    "payment_methods":
        payload.Message.OrderList..*PaymentMethod
            groupBy ((value) -> value.@CreditCardType ++ value.@CreditCardNo)
            pluck ((paymentMethod, key) -> {
                "first_name": paymentMethod[0].@FirstName,
                "last_name": paymentMethod[0].@LastName,
                "card_type": paymentMethod[0].@CreditCardType,
                "card_no": paymentMethod[0].@CreditCardNo,
                "amount_to_refund": sum paymentMethod.@AmountToRefund,
                "payment_type": paymentMethod[0].@PaymentType
            })
  }
}
</code>```

Body:
I want to transform XML to JSON below are my details and requirement.

I have below XMl:

    <Message>
    <OrderList>
        <Order>
            <PaymentMethods>
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="1111" CreditCardType="VISA" AmountToRefund="10" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="2222" CreditCardType="MASTER" AmountToRefund="20" />
            </PaymentMethods>
        </Order>
        <Order>
            <PaymentMethods>
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="1111" CreditCardType="VISA" AmountToRefund="10" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="2222" CreditCardType="MASTER" AmountToRefund="20" />
                <PaymentMethod FirstName="Avnish" LastName="Singh" PaymentType="Card" CreditCardNo="3333" CreditCardType="VISA" AmountToRefund="12" />
            </PaymentMethods>
        </Order>
    </OrderList>
</Message>

I have tried below by using groupBy and sum using below code but didn't get expected output, as shown in below:

    {
    "template_attributes": {
        "payment_methods": payload.Message.OrderList..*PaymentMethod groupBy ($.CreditCardType ++ $.CreditCardNo) map ((paymentMethod, index) -> {
            "first_name": paymentMethod.@FirstName,
            "last_name": paymentMethod.@LastName,
            "card_type": paymentMethod.@CreditCardType,
            "card_no": paymentMethod.@CreditCardNo,
            "amount_to_refund": paymentMethod.@AmountToRefund,
            "payment_type": sum paymentMethod.@PaymentType

        })
        }
}

I want below Output, where all the payment methods should be combined based on the card_type and credit_card_no:

 template_attributes:{
    payment_methods:[
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "1111",
            card_type: "VISA",
            amount: "20"
        },
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "2222",
            card_type: "MASTER",
            amount: "40"
        },
        {
            first_name: "Avnish",
            last_name: "Singh",
            credit_card_no: "3333",
            card_type: "VISA",
            amount: "12"
        }
    ]
}

Body:
Hi I think you are using mule 3.x so dw 1.0. Then the solution for your problem is. Use the pluck operator to work over an object as if it were an array of key value pairs.

{
  "template_attributes": {
    "payment_methods":
        payload.Message.OrderList..*PaymentMethod
            groupBy ((value) -> value.@CreditCardType ++ value.@CreditCardNo)
            pluck ((paymentMethod, key) -> {
                "first_name": paymentMethod[0].@FirstName,
                "last_name": paymentMethod[0].@LastName,
                "card_type": paymentMethod[0].@CreditCardType,
                "card_no": paymentMethod[0].@CreditCardNo,
                "amount_to_refund": sum paymentMethod.@AmountToRefund,
                "payment_type": paymentMethod[0].@PaymentType
            })
  }
}