问:
React setState - Add array to nested object with multiple arrays
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

```<code>export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}
</code>```

In my createPromotion component it's created as followed

```<code>let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};
</code>```

I can add a new period with the following:

```<code>addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}
</code>```

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

```<code>addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}
</code>```

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

```<code>{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}
</code>```

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

```<code>constructor(props) {
      super(props);

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}
</code>```

Method:

```<code>addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}
</code>```

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

```<code>this.props.addVariant( this.props.periodKey );
</code>```

Even when I call it as:

```<code>this.props.addVariant(2);
</code>```

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

```<code>case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;
</code>```

Add a period variant

```<code>case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;
</code>```

The following case:
Add a new variant, works, state:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

```<code>{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}
</code>```

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

```<code>case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;
</code>```

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

```<code>state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};
</code>```

Thank you all so much for your help!!

答:
Rather destruct your state object and avoid mutating it directly. This also happens to be a bad pattern.

Whenever you need to add a new item to the array:

const state = {
  arrayProp: [{ prop1: 'prop1', prop2: 'prop2' }]
}

const newItem = {
  prop1: 'value1',
  prop2: 'value2',
}

const newState = {
  ...state,
  arrayProp: [
     ...state.arrayProp,
     newItem,
  ]
}

console.log('newState', newState)```
</div>
</div>
</p>

<p>Same applies for nested properties within your state:
Redux also uses this very same approach</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const state = {
  objectProp: {
    arrayPropWithinArray: [
      { id: '0', otherProp: 123, yetAnotherProp: 'test' },
      { id: '1', otherProp: 0, yetAnotherProp: '' }
    ]
  }
}

const { objectProp } = state

const index = objectProp.arrayPropWithinArray.findIndex(obj => obj.id === '1')

const newSubItem = {
  otherProp: 1,
  yetAnotherProp: '2',
}

const newState = {
  ...state,
  objectProp: {
    ...objectProp,
    arrayPropWithinArray: [
      ...objectProp.arrayPropWithinArray.slice(0, index),
      {
        ...objectProp.arrayPropWithinArray[index],
        ...newSubItem,
      },
      ...objectProp.arrayPropWithinArray.slice(index + 1),
    ]
  }
}

console.log('newState', newState)</code>```

Your specific case (as described in your comment)

```<code>const periodKey = '2' // your periodKey var. Get it from the right place, it can be your action for example
const index = state.periods.findIndex(period => period.id === periodKey) // find which index has to be updated

state = {
  ...state, // propagates current state
  periods: [
    ...state.periods.slice(0, index), // propagates everything before index
    {
      ...state.periods[index],
      variants: [
        ...state.periods[index].variants,
        api.promotions.defaultPromotion.periods[0].variants[0],
      ],
    },
    ...state.periods.slice(0, index + 1) // propagates everything after index
  ]
}
</code>```

Body:
I'm currently working on a new application in React. This is the first time I'm creating something in React. The application will display our own promotions.

My initial state is as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510558814960,
        "endDateTimeStamp": 1510558814960,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

This is created from my defaultPromotion constant. This constant is stored in a separate file, which I call api.js

export const defaultPromotion = {
  name: '',
  campaign: '',
  url: 'https://',
  position: 0,
  periods: [
    {
      startDateTimeStamp: Date.now(),
      endDateTimeStamp: Date.now(),
      variants: [
        {
          title: '',
          text: '',
          image: '',
        },
      ]
    },
  ]
}

In my createPromotion component it's created as followed

let promotionState = api.promotions.defaultPromotion;

this.state = {
  promotion: promotionState
};

I can add a new period with the following:

addPromotion() {
    let promotion = this.state.promotion;
    promotion.periods.push( api.promotions.defaultPromotion.periods[0] );
    this.forceUpdate();
}

After that, a new period is added as expected. Suggestions to do this with setState() are very welcome! So, my new state is now:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Now, I want to add a new variant for this promotion period, this is where I'm stuck for 2 days now.

I'm adding a new period as follows:

addVariant( periodKey ) {
  const promotion = this.state.promotion;
  promotion.periods[periodKey].variants.push(api.promotions.defaultPromotion.periods[0].variants[0]);
  this.setState({ promotion: promotion });
}

periodKey is here "1", so, I'm expecting that there will be added a new variant for periods[1], but, it's added to both periods. State is now as follows:

{
  "promotion": {
    "name": "",
    "campaign": "",
    "url": "https://",
    "position": 0,
    "periods": [
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      },
      {
        "startDateTimeStamp": 1510559984421,
        "endDateTimeStamp": 1510559984421,
        "variants": [
          {
            "title": "",
            "text": "",
            "image": ""
          },
          {
            "title": "",
            "text": "",
            "image": ""
          }
        ]
      }
    ]
  }
}

Can someone explain me why this is happening and how I can add a new variant the right way?

Many, many thanks in advance!

UPDATE 1

Based on the answers from bennygenel and Patrick Hübl-Neschkudla, my implementation is now as follows:

Setting the initial state:

constructor(props) {
      super(props);

      let promotionState = api.promotions.defaultPromotion;
      this.state = { ...promotionState };

}

Method:

addVariant( periodKey ) {
  this.setState((prevState) => {
    const { periods } = prevState;

    periods[periodKey].variants.push(
      Object.assign({}, { ...periods[periodKey].variants, api.promotions.defaultPromotion.periods[0].variants[0]})
    );

    return { periods };
  });
}

But this still is setting the new variant in all the periods. I've also tried the exact code from Benny, but with the same results. The method is called as

this.props.addVariant( this.props.periodKey );

Even when I call it as:

this.props.addVariant(2);

The same behaviour is happening.

UPDATE 2

I now have rewritten everything to redux, this is so I have access to my promotion in every component the easy way, instead off passing them through certain components. Based on the answer of @mersocarlin, I now have the following reducer cases:

Add period

case PROMOTION_ADD_PERIOD:
    const { periods } = { ...state };
    periods.push(api.promotions.defaultPromotion.periods[0]);

    state = {
        ...state,
        periods: periods
    };
    break;

Add a period variant

case PROMOTION_ADD_PERIOD_VARIANT :

  state = {
    ...state,
    periods: [
      ...state.periods[action.payload.period],
      {
        variants: [
          ...state.periods[action.payload.period].variants,
          api.promotions.defaultPromotion.periods[0].variants[0]
        ]
      }
    ]
  };

  break;

The following case:
Add a new variant, works, state:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "startDateTimeStamp": 1510599968588,
      "endDateTimeStamp": 1510599968588,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    },
    {
      "startDateTimeStamp": 1510599968594,
      "endDateTimeStamp": 1510599968594,
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

After that, adding a new variant, kinda works, well, the variant is added, but I'm losing my 2nd period. State:

{
  "name": "",
  "campaign": "",
  "url": "https://",
  "position": 0,
  "periods": [
    {
      "variants": [
        {
          "title": "",
          "text": "",
          "image": ""
        },
        {
          "title": "",
          "text": "",
          "image": ""
        }
      ]
    }
  ]
}

I think this is a small thing I'm not see'ing. Does someone have the solution for the "PROMOTION_ADD_PERIOD_VARIANT" case?

Update 3
Changed the "PROMOTION_ADD_PERIOD" case as follows:

case PROMOTION_ADD_PERIOD:
    state = {
        ...state,
        periods: [
            ...state.periods,
            initialState.periods[0]
        ]
    };

    break;

Update 4
Finaly found the solution. See the final code for PROMOTION_ADD_PERIOD_VARIANT below:

state = {
  ...state,
  periods: [
    ...state.periods.map((item, index) => {
      if ( index !== action.payload.period ) {
        return item;
      }

      return {
        ...item,
        variants: [
          ...item.variants,
          initialState.periods[0].variants[0]
        ]
      }
    })
  ]
};

Thank you all so much for your help!!

Body:
Rather destruct your state object and avoid mutating it directly. This also happens to be a bad pattern.

Whenever you need to add a new item to the array:

const state = {
  arrayProp: [{ prop1: 'prop1', prop2: 'prop2' }]
}

const newItem = {
  prop1: 'value1',
  prop2: 'value2',
}

const newState = {
  ...state,
  arrayProp: [
     ...state.arrayProp,
     newItem,
  ]
}

console.log('newState', newState)

Same applies for nested properties within your state:
Redux also uses this very same approach

const state = {
  objectProp: {
    arrayPropWithinArray: [
      { id: '0', otherProp: 123, yetAnotherProp: 'test' },
      { id: '1', otherProp: 0, yetAnotherProp: '' }
    ]
  }
}

const { objectProp } = state

const index = objectProp.arrayPropWithinArray.findIndex(obj => obj.id === '1')

const newSubItem = {
  otherProp: 1,
  yetAnotherProp: '2',
}

const newState = {
  ...state,
  objectProp: {
    ...objectProp,
    arrayPropWithinArray: [
      ...objectProp.arrayPropWithinArray.slice(0, index),
      {
        ...objectProp.arrayPropWithinArray[index],
        ...newSubItem,
      },
      ...objectProp.arrayPropWithinArray.slice(index + 1),
    ]
  }
}

console.log('newState', newState)

Your specific case (as described in your comment)

const periodKey = '2' // your periodKey var. Get it from the right place, it can be your action for example
const index = state.periods.findIndex(period => period.id === periodKey) // find which index has to be updated

state = {
  ...state, // propagates current state
  periods: [
    ...state.periods.slice(0, index), // propagates everything before index
    {
      ...state.periods[index],
      variants: [
        ...state.periods[index].variants,
        api.promotions.defaultPromotion.periods[0].variants[0],
      ],
    },
    ...state.periods.slice(0, index + 1) // propagates everything after index
  ]
}


来源: stackexchange

问:
Python Pandas - Take first value from column and put into a variable
I have a DataFrame (df) that I get from an input (uses SQL to get data):

```<code>| Grant      | Summary     |
|:-----------|------------:|
| J0014/1    |  foobar     |
</code>```

It will only ever be one row.

How do I get the value from the Summary column into a variable to use later i.e. I dont want the column header, I want a situation where this happens:

aVar = foobar

Apologies if this is a simple question, but for some reason my brain isnt working this morning. Thank you

答:
Simpliest is select first value of column by Series.iat:

```<code>aVar = df['Summary'].iat[0]
</code>```

Solutions with iloc,
loc, because ix indexer is deprecated:

iloc is for select by positions, so need position of column Summary by get_loc:

```<code>aVar = df.iloc[0, df.columns.get_loc('Summary')]
</code>```

loc select by names, so use:

```<code>#default index - first value is 0
aVar = df.loc[0, 'Summary']
#general solution with unique index - seelct first value by `[0]`
aVar = df.loc[df.index[0], 'Summary']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a DataFrame (df) that I get from an input (uses SQL to get data):

| Grant      | Summary     |
|:-----------|------------:|
| J0014/1    |  foobar     |

It will only ever be one row.

How do I get the value from the Summary column into a variable to use later i.e. I dont want the column header, I want a situation where this happens:

aVar = foobar

Apologies if this is a simple question, but for some reason my brain isnt working this morning. Thank you

Body:
Simpliest is select first value of column by Series.iat:

aVar = df['Summary'].iat[0]

Solutions with iloc,
loc, because ix indexer is deprecated:

iloc is for select by positions, so need position of column Summary by get_loc:

aVar = df.iloc[0, df.columns.get_loc('Summary')]

loc select by names, so use:

#default index - first value is 0
aVar = df.loc[0, 'Summary']
#general solution with unique index - seelct first value by `[0]`
aVar = df.loc[df.index[0], 'Summary']


问:
How to change counter in bash to appending different strings to file
i need to get information, which users have connected to facebook from my proxy. I have a 2 loops.

```<code>#i have format og logs, like squid.log.12.10.2017
#with `ls squid.log*` i am working with all squid logs, day by day
for i in `ls squid.log*`; do
    echo "There is log $i, that we need to check"
    #i am getting count of ip addresses, that were on fb.com and i am writing them to ~/temp_cache
    # like this:
    # 25 192.168.110.5
    # 41 192.168.110.2
    # where 192.168.110.5 have connected to fb.com 25 times
    # and 192.168.110.2 have connected to fb.com 41 times
    zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 >> ~/temp_cache

    #i am getting only list of ip, without count of connections to facebook
    # like this:
    # 192.168.110.5
    # 192.168.110.2
    ip=$(zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 | awk '{print $2}')
    for y in $ip; do
        echo "Users from $y:"
        # i have system, that we are using for projects, in this system we have log ip-addresses and logins, from these ip addresses
        # like for this ip 192.168.110.5, i am getting name of user duke
        # main result, like this:
        # duke
        # the_rock
        redmine_users=$(tail -n 500000 /usr/share/redmine/log/production.log | grep -A 3 "$y" | grep "Current user" | awk '{print $3}' | head -n 1)

        # i am appending to lines, name of users for these lines
        # in a result it should be like this:
        # 25 192.168.110.5 duke
        # 41 192.168.110.2 the rock
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
    done
    # Delimiter for each day of logs
    echo "------------------------------------------------" >> ~/temp_cache
done
</code>```

For the first looking it works. But it works only for one day. If script is going to second log, i mean squid.log.13.10.2017, it make something like this:

```<code>        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________ hogan
        33 192.168.110.1
</code>```

But i want to do this:

```<code>        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________
        33 192.168.110.1 hogan
</code>```

I tried to run script manually for one day, with existsing line ______________________________ and with changing

```<code>        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

to

```<code>        counter=1
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

But in a result i have:

```<code>        ______________________________
        25 192.168.110.5 duke the rock
        41 192.168.110.2
</code>```

How to do, what i want, at least:

```<code>        ______________________________
        25 192.168.110.5 duke
        41 192.168.110.2 the rock
</code>```

How to change counter in this construction:

```<code>        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
</code>```

答: i have found. the counter should be in first loop. thanks for attention</p>

Body:
i need to get information, which users have connected to facebook from my proxy. I have a 2 loops.

#i have format og logs, like squid.log.12.10.2017
#with `ls squid.log*` i am working with all squid logs, day by day
for i in `ls squid.log*`; do
    echo "There is log $i, that we need to check"
    #i am getting count of ip addresses, that were on fb.com and i am writing them to ~/temp_cache
    # like this:
    # 25 192.168.110.5
    # 41 192.168.110.2
    # where 192.168.110.5 have connected to fb.com 25 times
    # and 192.168.110.2 have connected to fb.com 41 times
    zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 >> ~/temp_cache

    #i am getting only list of ip, without count of connections to facebook
    # like this:
    # 192.168.110.5
    # 192.168.110.2
    ip=$(zgrep fb.com /var/log/$i | cut -d " " -f1 | sort | uniq -c | sort -n -k 1 | awk '{print $2}')
    for y in $ip; do
        echo "Users from $y:"
        # i have system, that we are using for projects, in this system we have log ip-addresses and logins, from these ip addresses
        # like for this ip 192.168.110.5, i am getting name of user duke
        # main result, like this:
        # duke
        # the_rock
        redmine_users=$(tail -n 500000 /usr/share/redmine/log/production.log | grep -A 3 "$y" | grep "Current user" | awk '{print $3}' | head -n 1)

        # i am appending to lines, name of users for these lines
        # in a result it should be like this:
        # 25 192.168.110.5 duke
        # 41 192.168.110.2 the rock
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache
    done
    # Delimiter for each day of logs
    echo "------------------------------------------------" >> ~/temp_cache
done

For the first looking it works. But it works only for one day. If script is going to second log, i mean squid.log.13.10.2017, it make something like this:

        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________ hogan
        33 192.168.110.1

But i want to do this:

        25 192.168.110.5 duke
        41 192.168.110.2 the rock
        ______________________________
        33 192.168.110.1 hogan

I tried to run script manually for one day, with existsing line ______________________________ and with changing

        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache

to

        counter=1
        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache

But in a result i have:

        ______________________________
        25 192.168.110.5 duke the rock
        41 192.168.110.2

How to do, what i want, at least:

        ______________________________
        25 192.168.110.5 duke
        41 192.168.110.2 the rock

How to change counter in this construction:

        counter=$((counter+1))
        sed -i "$counter s|$|   $redmine_users |" ~/temp_cache


问:
PGI Flang github disappeared
Does anyone know where Flang or PGI/LLNL/Nvidia's Fortran for LLVM (not dragonegg) went to? I found some documentation to a github page that no longer exists. </p>

答:
Flang has been released under Apache 2.0 license: https://github.com/flang-compiler/flang
Here is the announcement.</p>

Title: PGI Flang github disappeared


问:
Navigating via anchor tag causes empty ajax GET request
During navigation via links with anchor tag (#) an emty ajax GET request to the current page is generated

I have ajax dialogs which are shown by clicking  on links
But I cant understand why an empty ajax GET request is generated

Here is the javascript code which is binded to link

```<code> $(document).on('click', '[data-js-click]', function (event) {
    if ($(event.target).prop("tagName") != 'A') {
        var $self = $(this),
            $target = $($self.data('js-click') || 'a:first', $self);
        if ($target.length && typeof $target[0].click === "function") {
            var docId = $(this).find("input[name='Filter.DocIds']").val();
            window.location.hash = 'edit_docid=' + docId;
            $target[0].click();
            return false;
        }
    }
});
</code>```

Commenting the line "window.location.hash = 'edit_docid=' + docId;" code fixes the problem, but I need to add this hash tag

答: use custom data-href tag for #navigation and for the default href use javascript void.</p>

Body:
During navigation via links with anchor tag (#) an emty ajax GET request to the current page is generated

I have ajax dialogs which are shown by clicking  on links
But I cant understand why an empty ajax GET request is generated

Here is the javascript code which is binded to link

 $(document).on('click', '[data-js-click]', function (event) {
    if ($(event.target).prop("tagName") != 'A') {
        var $self = $(this),
            $target = $($self.data('js-click') || 'a:first', $self);
        if ($target.length && typeof $target[0].click === "function") {
            var docId = $(this).find("input[name='Filter.DocIds']").val();
            window.location.hash = 'edit_docid=' + docId;
            $target[0].click();
            return false;
        }
    }
});

Commenting the line "window.location.hash = 'edit_docid=' + docId;" code fixes the problem, but I need to add this hash tag


问:
tfs 2015 (vNext) build task: unable to Run powershell script on remote machine ( win 7)
Here is the simple tfs powershell build task, i couldn't make it work, trying to run the script on windows 7 machine.

i am getting the below error:

2017-11-11T21:46:00.4972350Z ##[error]Connecting to remote server
  ryhel-d8x7frd failed with the following error message : The client
  cannot connect to the destination specified in the request. Verify
  that the service on the destination is running and is accepting
  requests. Consult the logs and documentation for the WS-Management
  service running on the destination, most commonly IIS or WinRM. If the
  destination is the WinRM service, run the following command on the
  destination to analyze and configure the WinRM service: "winrm
  quickconfig". For more information, see the
  about_Remote_Troubleshooting Help topic. For more info please refer to
  http://aka.ms/powershellontargetmachinesreadme

i referred the Same question & answer , but i have no clue how to overcome this error from build task. any help would be appreciated ? Thanks.

答:
PowerShell on Target Machines task uses Windows Remote Management (WinRM) to access on-premises physical computers or virtual computers.

Based on the error message, generally WinRM/Remote Powershell service isn't configured correctly will cause that issue. So just try to reconfigure the service.

You can Test the Connection with the command Test-WsMan COMPUTER first for the target machine, build task of course will be failed to connect to the remote server if the service is not avaiable.

Following the step in this article to configure the WinRM: WinRM configuration

Also make sure WinRM service is started : Enable-PSRemoting -Force


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答:
Depends what you're designing.  If it's a complex algorithm thats going to be the next video compression standard, you can iteratate and refactor 'till the cows come home and it isn't going to get any faster.  The perfomance comes from design.

Similarly, if you are writing a very large application, that will grow through regular releases, you need to put in place an architecture that will support growth, and this will be by design.  You can go down a long road by jumping head first into code just to discover a dead end.

Am I wrong?

IMHO, pretty much.

Edit: The reason I make many design decisions early in the process rather than mid flow is this can often be the cheapest time to do so.  For example, if we start writing an application using platform dependent technology early on, it may be a very expensive decision to reverse.  If we take time to consider the platforms we want to support before starting to code, it is much cheaper.  We can't and won't get everything right first time, but this does not relieve us of the duty of exploring all important design choices up front.  Every tried refactoring a MS MDI program to MVC?  I have, and wouldn't recommend it ;)

OwnerDisplayName: Phil H

ContentLicense: CC BY-SA 2.5

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: smacl

LastEditorDisplayName: smacl


问:
Dependency Injection in Azure WebJobs SDK when using NoAutomaticTrigger?
I am building an Azure WebJob that will run continuously. I want the WebJob to use the same style of DI as ASP.NET Core. I found this answer (Dependency injection using Azure WebJobs SDK?) on how to get DI/IoC working by using a custom IJobActivator. I also found this answer (Azure WebJobs - No functions found - How do I make a trigger-less job?) on using NoAutomaticTrigger to configure a continuously running Web Job.

The problem is that the NoAutomaticTrigger approach uses static methods, which is not compatible with DI/IoC. I assume that is because there is nothing that would cause the service with the NoAutomaticTrigger method to get resolved (like a queue message). I feel like ITypeLocator might be a path forward, but that is just a hunch.

The JobHost.Call method used in other NoAutomaticTrigger examples is limited to a static method. How do I have a service that is resolved via DI that gets resolved and called from a call on JobHost (or some other method) in Program.cs?

The solution that Iza Eddi-son Atsou suggested below works, with one wrinkle. I am used to registering my services via an interface on the service. Something like

```<code>serviceCollection.AddSingleton<IApplication, Application>();
</code>```

The problem with this is that if the NoAutomaticTrigger attribute is on the interface, the SDK blows up. The solution is to add the attribute to the class, and register the class as itself.

```<code>serviceCollection.AddSingleton<Application>();
</code>```

Once that change is made, the solution in the answer works great.

答:
AFAIK, The NoAutomaticTrigger attribute is useful in two cases: Functions with triggers Prevents automatic invocation of the triggers, allowing manual polling. Functions without other attributes Flags the function as an available job function. In both cases, functions marked with this attribute are never called automatically by JobHost (during RunAndBlock). Instead, they must be invoked manually using the Call method. And, this attribute can also used in the non-static method.

here are some related articles about using Azure WebJobs and Dependency Injection, you could refer to them:
http://www.ryansouthgate.com/2016/05/10/azure-webjobs-and-dependency-injection/
and http://www.jerriepelser.com/blog/using-autofac-and-common-service-locator-with-azure-webjobs

Body:
I am building an Azure WebJob that will run continuously. I want the WebJob to use the same style of DI as ASP.NET Core. I found this answer (Dependency injection using Azure WebJobs SDK?) on how to get DI/IoC working by using a custom IJobActivator. I also found this answer (Azure WebJobs - No functions found - How do I make a trigger-less job?) on using NoAutomaticTrigger to configure a continuously running Web Job.

The problem is that the NoAutomaticTrigger approach uses static methods, which is not compatible with DI/IoC. I assume that is because there is nothing that would cause the service with the NoAutomaticTrigger method to get resolved (like a queue message). I feel like ITypeLocator might be a path forward, but that is just a hunch.

The JobHost.Call method used in other NoAutomaticTrigger examples is limited to a static method. How do I have a service that is resolved via DI that gets resolved and called from a call on JobHost (or some other method) in Program.cs?

The solution that Iza Eddi-son Atsou suggested below works, with one wrinkle. I am used to registering my services via an interface on the service. Something like

serviceCollection.AddSingleton<IApplication, Application>();

The problem with this is that if the NoAutomaticTrigger attribute is on the interface, the SDK blows up. The solution is to add the attribute to the class, and register the class as itself.

serviceCollection.AddSingleton<Application>();

Once that change is made, the solution in the answer works great.


问:
How to make an input have more than one event?
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

```<code>$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});
</code>```

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

答:
You can trigger the click event of #i_btn in the change event of #i_sel</p>

```<code>$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
     $("#i_btn").trigger("click");
});
</code>```

Body:
I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

Body:
You can trigger the click event of #i_btn in the change event of #i_sel

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
     $("#i_btn").trigger("click");
});


问:
CSS3 selector for next matching sibling
I am trying to come up with a CSS3 selector for the below HTML:

```<code><input data-type="fillpart" type="checkbox" name="cough, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“fever, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>
</code>```

All of the elements are siblings, and there might be additional elements where ... are. The elements in question are always in a sequence of three (3). Currently, I have CSS as below:

```<code>fillpart {
  background: #a5d2a5;
}
</code>```

It colors the text inside <fillpart>, while the tag itself is obviously ignored, since it is not something that browsers support. I want to alternate the background value depending on whether previous tag matches input[checked='true'] or false.

Is this possible with CSS3?

Thank you

答:
To style elements after a checked input-field, you can use the CSS next-selector (+):

```<code>fillpart {
    background-color: #a5d2a5;
}

input:checked + ignore + fillpart {
    background-color: red;
}
</code>```

this will make the fillpart after the ignore, after the checked input-field have a red background-color

EDIT:

Actually, you can use the ~-selector, which selects every fillpart element that are preceded by a checked input-field:

```<code>fillpart {
    background-color: #a5d2a5;
}

input:checked ~ fillpart {
    background-color: red;
}
</code>```

Title: CSS3 selector for next matching sibling

Body:
I am trying to come up with a CSS3 selector for the below HTML:

<input data-type="fillpart" type="checkbox" name="cough, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“fever, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
...
<input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
<ignore></ignore>
<fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>

All of the elements are siblings, and there might be additional elements where ... are. The elements in question are always in a sequence of three (3). Currently, I have CSS as below:

fillpart {
  background: #a5d2a5;
}

It colors the text inside <fillpart>, while the tag itself is obviously ignored, since it is not something that browsers support. I want to alternate the background value depending on whether previous tag matches input[checked='true'] or false.

Is this possible with CSS3?

Thank you

Body:
To style elements after a checked input-field, you can use the CSS next-selector (+):

fillpart {
    background-color: #a5d2a5;
}

input:checked + ignore + fillpart {
    background-color: red;
}

this will make the fillpart after the ignore, after the checked input-field have a red background-color

EDIT:

Actually, you can use the ~-selector, which selects every fillpart element that are preceded by a checked input-field:

fillpart {
    background-color: #a5d2a5;
}

input:checked ~ fillpart {
    background-color: red;
}


问:
Syntax highlighting for whole projects is broken
As you can see, the syntax highlighting of a whole project is gone. Actually I use Eclipse Oxygen with the EGit-Plugin. It is important because at the moment it seems that the problem is hidden somewhere in the project itself.

What i have tried so far:
 - reset settings from eclipse
 - uninstall "Darkest Theme"
 - change the color-scheema
 - manualy change colors for the Java-Editor

Nothing happened. After this I Downloaded a new Eclipse EE, imported the project from Bitbucket and the problem was all the same.
After this I tried to change the computer but it was all the same. That means to me, there was pushed something to the project that causes this changes.

One more special thing about it: there are a few highlights that changed the way they have to...

Some pictures:

Here Is the plain view of some code

An here is a picture with the Code compared to the way it should look

I hope you can help me. The last chance should be copying all the classes or code and the rest of the project into a new project...

I hope i gave you as much information as needed.

答:
OK, its solved now.
The problem was, the .classpath disappeared and it wasn't recognised as a Java-project anymore. I don't know how this happened, but my problem is solved now.
I created a new project, copied the neccessary files and added the classpaths to the right directories again.

So thanks for the hint with the Icon. I would never have noticed it.


问:
How can I replace a file if already exists in the destination folder?
I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name.

I have two folders /src and /dst.

In folder /src I have:

'access.log.1.txt'

and in folder /dst :

'access.log.1.20171110_115840565311.txt'

'access.log.1.20171110_115940565311.txt'

'access.log.2.20171110_115940565311.txt'

When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst.

So the /dst folder should look like this after the execution:

'access.log.1.txt'

'access.log.2.20171110_115940565311.txt'

This is the code I have to move files from /src to /dst:

```<code>entrada = ENTRADA   #This 3 are the paths to the folders  /src
salida = SALIDA     #                                     /dst
error=ERROR         #                                     /err
files=glob.glob(entrada)
for file in files:
   fichero=open(file,encoding='utf-8')
   try:
       for line in fichero:
          la=line.replace("-","")
          li=la.replace('”'+chr(10),'')
          li=li.split('"')
          line_DB(li)
       fichero.close()
       if TIME_RENAME=='True':
          execution=str(datetime.now())
          execution=execution.replace('.','')
          execution=execution.replace('-','')
          execution=execution.replace(' ','_')
          execution_time=execution.replace(':','')
          base = os.path.splitext(file)[0]
          base=base+'.'+execution_time+'.txt'
          os.rename(file,base)
          file=base
       else:
          print('Hello')
          #This is where I need the code

       shutil.move(file, salida)
       con.commit()
   except:
       logging.error(sys.exc_info())
       print(sys.exc_info())
       fichero.close()
       shutil.move(file, error)
</code>```

Anyone could help me?

Thanks!!

答:
Remove all the file with a matching regex.
Just navigate to destination folder and delete all files with your regex
In your case use

```<code>rm access.log.1.[0-9,_]*.txt
</code>```

It removes all the file with name access.log.1..txt
Now, You can copy the file using

```<code>cp filename.txt /dst/filename.txt
</code>```

Body:
I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name.

I have two folders /src and /dst.

In folder /src I have:

'access.log.1.txt'

and in folder /dst :

'access.log.1.20171110_115840565311.txt'

'access.log.1.20171110_115940565311.txt'

'access.log.2.20171110_115940565311.txt'

When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst.

So the /dst folder should look like this after the execution:

'access.log.1.txt'

'access.log.2.20171110_115940565311.txt'

This is the code I have to move files from /src to /dst:

entrada = ENTRADA   #This 3 are the paths to the folders  /src
salida = SALIDA     #                                     /dst
error=ERROR         #                                     /err
files=glob.glob(entrada)
for file in files:
   fichero=open(file,encoding='utf-8')
   try:
       for line in fichero:
          la=line.replace("-","")
          li=la.replace('”'+chr(10),'')
          li=li.split('"')
          line_DB(li)
       fichero.close()
       if TIME_RENAME=='True':
          execution=str(datetime.now())
          execution=execution.replace('.','')
          execution=execution.replace('-','')
          execution=execution.replace(' ','_')
          execution_time=execution.replace(':','')
          base = os.path.splitext(file)[0]
          base=base+'.'+execution_time+'.txt'
          os.rename(file,base)
          file=base
       else:
          print('Hello')
          #This is where I need the code

       shutil.move(file, salida)
       con.commit()
   except:
       logging.error(sys.exc_info())
       print(sys.exc_info())
       fichero.close()
       shutil.move(file, error)

Anyone could help me?

Thanks!!

Body:
Remove all the file with a matching regex.
Just navigate to destination folder and delete all files with your regex
In your case use

rm access.log.1.[0-9,_]*.txt

It removes all the file with name access.log.1..txt
Now, You can copy the file using

cp filename.txt /dst/filename.txt


问:
I want to read from text file that displays which character appears most or least often (keyboard or text file) ? :)
Here's my code:

```<code>include <stdio.h>

int main()
{
   char str[1000], ch;
   int i, frequency = 0;

   printf("Enter a string: ");
   gets(str);

   printf("Enter a character to find the frequency: ");
   scanf("%c",&ch);

   for(i = 0; str[i] != '\0'; ++i)
   {
       if(ch == str[i])
           ++frequency;
   }

   printf("Frequency of %c = %d", ch, frequency);

   return 0;
</code>```

I figured that the frequency of characters code I came up with is similar. How to implement the character which appears more / less often in standard input or text file?

Also, should I use StreamReader sr = new StreamReader("example.txt") for reading normal text files for this code?

EDIT: Have to use Switch /M for most often and /L for least often.

答:
Never, never, never use gets. It is so insecure and so susceptible to buffer overrun, it has been removed from the C standard library. Use fgets instead, just be aware that fgets will read and include the trailing '\n' in the buffer it fills (just as all legitimate line oriented input functions do, such as POSIX getline). This prevents leaving a '\n' unread in the input buffer (e.g. stdin) following each user input.

You risk Undefined Behavior because you do not validate the contents of str in any way and then you fail to validate the return of scanf to insure a character was read. (the user could cancel input in either case by generating an EOF with Ctrl+d on *nix systems of with Ctrl+z on windoze).

Further, you must understand that scanf will leave characters in the input buffer (as will fgets if the line is longer than the amount of storage you have allocated). That is one of the most common pitfalls new C programmers fall victim to. (failing to validate a complete line of input was read and failing to handle characters that remain in the input buffer)

When taking user input with fgets (which is recommended), since it reads and includes the '\n' in the buffer it fills, you simply check the length of the buffer read with strlen and then make sure the last character is a '\n'.

scanf is full of pitfalls when used for user input. While it can be used, if used correctly with it's return validated and any remaining characters emptied from stdin before your next call to scanf, you have to approach it use that way. In your case ch is the last input for your file, but try taking input for ch before reading the string and see what happens...

Putting it altogether, and adding validations for both str and ch, and adding additional comments in-line below, you could do something similar to the following:

```<code>#include <stdio.h>
#include <string.h>

#define MAXS 1024       /* if you need a constant, define one */

int main (void) {

    int frequency = 0;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch;

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')      /* just use a pointer to str */
        if (*p++ == ch)     /* compare to ch and increment to next char */
            frequency++;    /* increment frequency if they are equal */

    printf ("\nFrequency of %c = %d\n", ch, frequency);

    return 0;
}
</code>```

(note: you could declare char ch[3] = ""; and use fgets to read fgets (ch, sizeof ch, stdin) and then simply compare if (*p++ == *ch) to prevent leaving the '\n' in stdin (but you would still need to validate that it was the final character read, and if not manually empty stdin))

Exammple Use/Output

```<code>$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: a

Frequency of a = 10

$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: p

Frequency of p = 2

$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: z

Frequency of z = 0
</code>```

Look things over, think about the validations that were made, and let me know if you have any further questions.

Using a Frequency Array to Capture Count of all Chars

Using a frequency array allows you to capture the frequency of all characters (or the independent count of any element of a set). Essentially, you use an array initialized to zero with one element for each member of the set you want to count the frequency of each occurrence. Since there are 128 ASCII Characters, you can simply use an array of 128 elements, e.g. int frequency[128] = {0};.

If you look at the link provided, you see the ASCII value of each character corresponds to a value between 0-127, so when looping over each character in the input string, if you increment the array index that corresponds to the character, you end up with the total count for each character in its corresponding element. For example, if p is a pointer to the beginning of str, then you can loop over each character in the string capturing their frequency in the frequency[*p] element of the array:

```<code>while (*p != '\n') {
    frequency[*p]++;   /* increments element corresponding to char *p */
    p++;               /* note: cast to (int)*p intentional omitted   */
}
</code>```

Now that you have the frequency for every character stored in the frequency, you can simply loop over the elements you are concerned about to determine max/min, etc... Note: the normal printable characters begin with 'space' (ASCII 32, or hex 0x20) and end with '~' (ASCII 126 or hex 0x7e`). So just limit your check of values to the printable range, e.g.

```<code>    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];     /* save least frequent count */
            minc = i;               /* save least frequent char */
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];     /* save same for max */
            maxc = i;
        }
    }
</code>```

(note: you can further micro-divide ranges for only lowercase, uppercase, digits, etc..)

Putting that altogether, you can do something similar to the following to report the number of occurrence if the wanted char, the max occurring char, the min occurring char (and then summarize by dumping the frequency of all chars):

```<code>#include <stdio.h>
#include <string.h>
#include <limits.h>

#define MAXS 1024   /* if you need a constant, define one */
#define NASCII 128  /* number of ASCII chars (includes non-printing) */

int main (void) {

    int frequency[NASCII] = {0},
        max = INT_MIN,
        min = INT_MAX;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch,
        minc = 0,
        maxc = 0;

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')              /* just use a pointer to str */
        frequency[(int)*p++]++;     /* increment element representing ch */

    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];     /* save least frequent count */
            minc = i;               /* save least frequent char */
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];     /* save same for max */
            maxc = i;
        }
    }

    /* ouput requested char freq, and max/min chars */
    printf ("\nFrequency of %c = %d\n"
            "least frequent occurrence: %c = %d\n"
            " most frequent occurrence: %c = %d\n\n",
            ch, frequency[(int)ch], minc, min, maxc, max);

    /* output frequency of all printable chars */
    printf ("frequency of all printable characters:\n");
    for (int i = ' '; i < '~'; i++)
        if (frequency[i])
            printf ("  '%c'  :  %d\n", i, frequency[i]);

    return 0;
}
</code>```

Exammple Use/Output

```<code>$ ./bin/freqofc2
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: m

Frequency of m = 2
least frequent occurrence: c = 1
 most frequent occurrence: a = 10

frequency of all printable characters:
  ' '  :  6
  'a'  :  10
  'c'  :  1
  'l'  :  2
  'm'  :  2
  'n'  :  4
  'p'  :  2
</code>```

Adding /L or /M Switches for Least/Max Occurrences

To add command line switches, for a minimum number in a known order, you can simply use the allowable argument count and argument vector parameters to main(), e.g. int main (int argc, char **argv). Example:

```<code>int main (int argc, char **argv) {
    ...
    /* validate "/L" or "/M" provided as an argument */
    if (argc != 2 || (argv[1][1] != 'L' && argv[1][1] != 'M')) {
        fprintf (stderr, "error: insufficient input, req'd /M or /L.\n");
        return 1;
    }
</code>```

To test and output either the least or minimum, you simply test which character is present and act accordingly, e.g.

```<code>    ...
    if (argv[1][1] == 'L')  /* output requested lease or max */
        printf ("requested least frequent occurrence: %c = %d\n\n",
                minc, min);
    else
        printf ("requested most frequent occurrence: %c = %d\n\n",
                maxc, max);
</code>```

Putting that together an a complete example would be:

```<code>#include <stdio.h>
#include <string.h>
#include <limits.h>

#define MAXS 1024   /* if you need a constant, define one */
#define NASCII 128  /* number of ASCII chars (includes non-printing) */

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

    int frequency[NASCII] = {0},
        max = INT_MIN,
        min = INT_MAX;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch,
        minc = 0,
        maxc = 0;

    /* validate "/L" or "/M" provided as an argument */
    if (argc != 2 || (argv[1][1] != 'L' && argv[1][1] != 'M')) {
        fprintf (stderr, "error: insufficient input, req'd /M or /L.\n");
        return 1;
    }

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')              /* just use a pointer to str */
        frequency[(int)*p++]++;     /* increment element representing ch */

    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];
            minc = i;
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];
            maxc = i;
        }
    }

    /* ouput requested char freq, and max/min chars */
    printf ("\nFrequency of %c = %d\n"
            "least frequent occurrence: %c = %d\n"
            " most frequent occurrence: %c = %d\n\n",
            ch, frequency[(int)ch], minc, min, maxc, max);

    if (argv[1][1] == 'L')  /* output requested lease or max */
        printf ("requested least frequent occurrence: %c = %d\n\n",
                minc, min);
    else
        printf ("requested most frequent occurrence: %c = %d\n\n",
                maxc, max);

    /* output frequency of all printable chars */
    printf ("frequency of all printable characters:\n");
    for (int i = ' '; i < '~'; i++)
        if (frequency[i])
            printf ("  '%c'  :  %d\n", i, frequency[i]);

    return 0;
}
</code>```

Let me know if you have any questions.

Body:
Here's my code:

include <stdio.h>

int main()
{
   char str[1000], ch;
   int i, frequency = 0;

   printf("Enter a string: ");
   gets(str);

   printf("Enter a character to find the frequency: ");
   scanf("%c",&ch);

   for(i = 0; str[i] != '\0'; ++i)
   {
       if(ch == str[i])
           ++frequency;
   }

   printf("Frequency of %c = %d", ch, frequency);

   return 0;

I figured that the frequency of characters code I came up with is similar. How to implement the character which appears more / less often in standard input or text file?

Also, should I use StreamReader sr = new StreamReader("example.txt") for reading normal text files for this code?

EDIT: Have to use Switch /M for most often and /L for least often.

Body:
Never, never, never use gets. It is so insecure and so susceptible to buffer overrun, it has been removed from the C standard library. Use fgets instead, just be aware that fgets will read and include the trailing '\n' in the buffer it fills (just as all legitimate line oriented input functions do, such as POSIX getline). This prevents leaving a '\n' unread in the input buffer (e.g. stdin) following each user input.

You risk Undefined Behavior because you do not validate the contents of str in any way and then you fail to validate the return of scanf to insure a character was read. (the user could cancel input in either case by generating an EOF with Ctrl+d on *nix systems of with Ctrl+z on windoze).

Further, you must understand that scanf will leave characters in the input buffer (as will fgets if the line is longer than the amount of storage you have allocated). That is one of the most common pitfalls new C programmers fall victim to. (failing to validate a complete line of input was read and failing to handle characters that remain in the input buffer)

When taking user input with fgets (which is recommended), since it reads and includes the '\n' in the buffer it fills, you simply check the length of the buffer read with strlen and then make sure the last character is a '\n'.

scanf is full of pitfalls when used for user input. While it can be used, if used correctly with it's return validated and any remaining characters emptied from stdin before your next call to scanf, you have to approach it use that way. In your case ch is the last input for your file, but try taking input for ch before reading the string and see what happens...

Putting it altogether, and adding validations for both str and ch, and adding additional comments in-line below, you could do something similar to the following:

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

#define MAXS 1024       /* if you need a constant, define one */

int main (void) {

    int frequency = 0;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch;

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')      /* just use a pointer to str */
        if (*p++ == ch)     /* compare to ch and increment to next char */
            frequency++;    /* increment frequency if they are equal */

    printf ("\nFrequency of %c = %d\n", ch, frequency);

    return 0;
}

(note: you could declare char ch[3] = ""; and use fgets to read fgets (ch, sizeof ch, stdin) and then simply compare if (*p++ == *ch) to prevent leaving the '\n' in stdin (but you would still need to validate that it was the final character read, and if not manually empty stdin))

Exammple Use/Output

$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: a

Frequency of a = 10

$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: p

Frequency of p = 2

$ ./bin/freqofc
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: z

Frequency of z = 0

Look things over, think about the validations that were made, and let me know if you have any further questions.

Using a Frequency Array to Capture Count of all Chars

Using a frequency array allows you to capture the frequency of all characters (or the independent count of any element of a set). Essentially, you use an array initialized to zero with one element for each member of the set you want to count the frequency of each occurrence. Since there are 128 ASCII Characters, you can simply use an array of 128 elements, e.g. int frequency[128] = {0};.

If you look at the link provided, you see the ASCII value of each character corresponds to a value between 0-127, so when looping over each character in the input string, if you increment the array index that corresponds to the character, you end up with the total count for each character in its corresponding element. For example, if p is a pointer to the beginning of str, then you can loop over each character in the string capturing their frequency in the frequency[*p] element of the array:

while (*p != '\n') {
    frequency[*p]++;   /* increments element corresponding to char *p */
    p++;               /* note: cast to (int)*p intentional omitted   */
}

Now that you have the frequency for every character stored in the frequency, you can simply loop over the elements you are concerned about to determine max/min, etc... Note: the normal printable characters begin with 'space' (ASCII 32, or hex 0x20) and end with '~' (ASCII 126 or hex 0x7e`). So just limit your check of values to the printable range, e.g.

    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];     /* save least frequent count */
            minc = i;               /* save least frequent char */
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];     /* save same for max */
            maxc = i;
        }
    }

(note: you can further micro-divide ranges for only lowercase, uppercase, digits, etc..)

Putting that altogether, you can do something similar to the following to report the number of occurrence if the wanted char, the max occurring char, the min occurring char (and then summarize by dumping the frequency of all chars):

#include <stdio.h>
#include <string.h>
#include <limits.h>

#define MAXS 1024   /* if you need a constant, define one */
#define NASCII 128  /* number of ASCII chars (includes non-printing) */

int main (void) {

    int frequency[NASCII] = {0},
        max = INT_MIN,
        min = INT_MAX;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch,
        minc = 0,
        maxc = 0;

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')              /* just use a pointer to str */
        frequency[(int)*p++]++;     /* increment element representing ch */

    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];     /* save least frequent count */
            minc = i;               /* save least frequent char */
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];     /* save same for max */
            maxc = i;
        }
    }

    /* ouput requested char freq, and max/min chars */
    printf ("\nFrequency of %c = %d\n"
            "least frequent occurrence: %c = %d\n"
            " most frequent occurrence: %c = %d\n\n",
            ch, frequency[(int)ch], minc, min, maxc, max);

    /* output frequency of all printable chars */
    printf ("frequency of all printable characters:\n");
    for (int i = ' '; i < '~'; i++)
        if (frequency[i])
            printf ("  '%c'  :  %d\n", i, frequency[i]);

    return 0;
}

Exammple Use/Output

$ ./bin/freqofc2
Enter a string: a man a plan a canal panama
Enter a character to find the frequency: m

Frequency of m = 2
least frequent occurrence: c = 1
 most frequent occurrence: a = 10

frequency of all printable characters:
  ' '  :  6
  'a'  :  10
  'c'  :  1
  'l'  :  2
  'm'  :  2
  'n'  :  4
  'p'  :  2

Adding /L or /M Switches for Least/Max Occurrences

To add command line switches, for a minimum number in a known order, you can simply use the allowable argument count and argument vector parameters to main(), e.g. int main (int argc, char **argv). Example:

int main (int argc, char **argv) {
    ...
    /* validate "/L" or "/M" provided as an argument */
    if (argc != 2 || (argv[1][1] != 'L' && argv[1][1] != 'M')) {
        fprintf (stderr, "error: insufficient input, req'd /M or /L.\n");
        return 1;
    }

To test and output either the least or minimum, you simply test which character is present and act accordingly, e.g.

    ...
    if (argv[1][1] == 'L')  /* output requested lease or max */
        printf ("requested least frequent occurrence: %c = %d\n\n",
                minc, min);
    else
        printf ("requested most frequent occurrence: %c = %d\n\n",
                maxc, max);

Putting that together an a complete example would be:

#include <stdio.h>
#include <string.h>
#include <limits.h>

#define MAXS 1024   /* if you need a constant, define one */
#define NASCII 128  /* number of ASCII chars (includes non-printing) */

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

    int frequency[NASCII] = {0},
        max = INT_MIN,
        min = INT_MAX;
    char str[MAXS] = "",
        *p = str,           /* pointer to str */
        ch,
        minc = 0,
        maxc = 0;

    /* validate "/L" or "/M" provided as an argument */
    if (argc != 2 || (argv[1][1] != 'L' && argv[1][1] != 'M')) {
        fprintf (stderr, "error: insufficient input, req'd /M or /L.\n");
        return 1;
    }

    printf ("Enter a string: ");

    if (fgets (str, MAXS, stdin)) {         /* validate input received */
        size_t len = strlen (str);          /* get length of str */
        if (len && str[len - 1] != '\n') {  /* validate all input read */
            fprintf (stderr, "error: line exceeds %d chars.\n", MAXS-2);
            return 1;
        }
    }
    else {  /* if fgets failed - user generated EOF to cancel */
        fprintf (stderr, "error: user canceled input (EOF).\n");
        return 1;
    }

    printf ("Enter a character to find the frequency: ");
    if (scanf ("%c", &ch) != 1) {   /* note: chars will remain in stdin */
        fprintf (stderr, "error: user canceled input.\n");
        return 1;
    }

    while (*p != '\n')              /* just use a pointer to str */
        frequency[(int)*p++]++;     /* increment element representing ch */

    /* loop over printable characters (see ASCII Chart), for max/min */
    for (int i = ' '; i <= '~'; i++) {
        /* require a frequency of at least 1 for min */
        if (frequency[i] && frequency[i] < min) {
            min = frequency[i];
            minc = i;
        }
        if (frequency[i] > max) {   /* just find max */
            max = frequency[i];
            maxc = i;
        }
    }

    /* ouput requested char freq, and max/min chars */
    printf ("\nFrequency of %c = %d\n"
            "least frequent occurrence: %c = %d\n"
            " most frequent occurrence: %c = %d\n\n",
            ch, frequency[(int)ch], minc, min, maxc, max);

    if (argv[1][1] == 'L')  /* output requested lease or max */
        printf ("requested least frequent occurrence: %c = %d\n\n",
                minc, min);
    else
        printf ("requested most frequent occurrence: %c = %d\n\n",
                maxc, max);

    /* output frequency of all printable chars */
    printf ("frequency of all printable characters:\n");
    for (int i = ' '; i < '~'; i++)
        if (frequency[i])
            printf ("  '%c'  :  %d\n", i, frequency[i]);

    return 0;
}

Let me know if you have any questions.


问:
Model object has no attribute 'get'
using Django 1.11 I'm stuck with uuid referencing in my views.
I read through all similar looking questions here, but they either focus on forms or anything else.

Minimal example

It's an app called MegaTest. It's bound to /testuuid/

I have a working index view that generate links to /testuuid/<uuid>

If I click on a link on my index page, I get:

```<code>AttributeError at /testuuid/5a147a14-a9a9-4045-8e79-0ce2e8258a68/
'MegaTest' object has no attribute 'get'
</code>```

models.py

```<code>class MegaTest(models.Model):
    uuid = models.UUIDField(db_index=True, default=uuid.uuid4,
               editable=False, unique=True)
    name = models.CharField(max_length=128, blank=True, null=True)
</code>```

views.py

```<code>class IndexView(generic.ListView):
    template_name = 'testuuid/index.html'
    context_object_name = 'test_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return MegaTest.objects.all()

class MegaTestDetailView(generic.DetailView):
    model = MegaTest

    def get(self, request, uuid):
        try:
            megatest = MegaTest.objects.get(uuid=uuid)
            return megatest

        except MegaTest.DoesNotExist:
            raise Http404
</code>```

urls.py

```<code>app_name = 'testuuid'
urlpatterns = [
    # ex: /polls/
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<uuid>[\w-]+)/$', views.MegaTestDetailView.as_view(), name='detail'),
]
</code>```

testuuid/index.html

```<code>{% if test_list %}
    <ul>
    {% for test in test_list %}
        <li>
            <a href="{% url 'testuuid:detail' test.uuid %}">{{ test.name }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No tests available.</p>
{% endif %}
</code>```

I assume a damn simple mistake, but I really have no clue at this point.

The complete traceback can be found here http://dpaste.com/3JTB5NZ

答:
You should override get_object() method instead of get().

```<code>class MegaTestDetailView(generic.DetailView):
    model = MegaTest

    def get_object(self):
        try:
            megatest = MegaTest.objects.get(uuid=self.kwargs['uuid'])
            return megatest

        except MegaTest.DoesNotExist:
            raise Http404
</code>```

You can also work with get_queryset() or even just specify pk field in url and don't write any method in the view class. Django will automatically query on your specified field in pk_url_kwarg

Title: Model object has no attribute 'get'

Body:
using Django 1.11 I'm stuck with uuid referencing in my views.
I read through all similar looking questions here, but they either focus on forms or anything else.

Minimal example

It's an app called MegaTest. It's bound to /testuuid/

I have a working index view that generate links to /testuuid/<uuid>

If I click on a link on my index page, I get:

AttributeError at /testuuid/5a147a14-a9a9-4045-8e79-0ce2e8258a68/
'MegaTest' object has no attribute 'get'

models.py

class MegaTest(models.Model):
    uuid = models.UUIDField(db_index=True, default=uuid.uuid4,
               editable=False, unique=True)
    name = models.CharField(max_length=128, blank=True, null=True)

views.py

class IndexView(generic.ListView):
    template_name = 'testuuid/index.html'
    context_object_name = 'test_list'

    def get_queryset(self):
        """Return the last five published questions."""
        return MegaTest.objects.all()

class MegaTestDetailView(generic.DetailView):
    model = MegaTest

    def get(self, request, uuid):
        try:
            megatest = MegaTest.objects.get(uuid=uuid)
            return megatest

        except MegaTest.DoesNotExist:
            raise Http404

urls.py

app_name = 'testuuid'
urlpatterns = [
    # ex: /polls/
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<uuid>[\w-]+)/$', views.MegaTestDetailView.as_view(), name='detail'),
]

testuuid/index.html

{% if test_list %}

    {% for test in test_list %}

            {{ test.name }}

    {% endfor %}

{% else %}

No tests available.

{% endif %}

I assume a damn simple mistake, but I really have no clue at this point.

The complete traceback can be found here http://dpaste.com/3JTB5NZ

Body:
You should override get_object() method instead of get().

class MegaTestDetailView(generic.DetailView):
    model = MegaTest

    def get_object(self):
        try:
            megatest = MegaTest.objects.get(uuid=self.kwargs['uuid'])
            return megatest

        except MegaTest.DoesNotExist:
            raise Http404

You can also work with get_queryset() or even just specify pk field in url and don't write any method in the view class. Django will automatically query on your specified field in pk_url_kwarg


问:
Jsoup does not retrieve first part of HTML document
I'd like to extract and print the HTML of a Vimeo page with Jsoup, but only the second part of the HTML is retrieved.

I already tried to set .maxBodySize(0) but nothing changes; this is my code:

```<code>import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class PrintVimeoHTML {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://vimeo.com/categories/food/cooking/videos")
            .header("Accept-Encoding", "gzip, deflate")
            .userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
            .maxBodySize(0)
            .timeout(600000)
            .get();
        System.out.println(doc);
    }
}
</code>```

And what is extracted starts from this highlighted

答:
Solved using Selenium instead of Jsoup. It was a JavaScript issue: Jsoup does not run JavaScript, and my content was actually loaded by a script.
Selenium is good for this purpose because it simulates a real browser, so it can get the whole HTML generated.</p>

Body:
I'd like to extract and print the HTML of a Vimeo page with Jsoup, but only the second part of the HTML is retrieved.

I already tried to set .maxBodySize(0) but nothing changes; this is my code:

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class PrintVimeoHTML {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://vimeo.com/categories/food/cooking/videos")
            .header("Accept-Encoding", "gzip, deflate")
            .userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
            .maxBodySize(0)
            .timeout(600000)
            .get();
        System.out.println(doc);
    }
}

And what is extracted starts from this highlighted


答:
You can use plus sign (+) in your selector:

input[checked="false"] + ignore + fillpart

view my example below:

fillpart {background: #a5d2a5;}
input[checked="false"] +ignore+ fillpart{background: red;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>
  <input data-type="fillpart" type="checkbox" name="cough, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“fever, " checked="false">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>

</body>
</html></code>```

Title: CSS3 selector for next matching sibling

Body:
You can use plus sign (+) in your selector:

input[checked="false"] + ignore + fillpart

view my example below:

fillpart {background: #a5d2a5;}
input[checked="false"] +ignore+ fillpart{background: red;}

<!DOCTYPE html>
<html>
<body>
  <input data-type="fillpart" type="checkbox" name="cough, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name="cough, ">cough, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“fever, " checked="false">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“fever, ">fever, </fillpart>
  ...
  <input data-type="fillpart" type="checkbox" name=“flu, " checked="true">
  <ignore></ignore>
  <fillpart explicitlyset="true" name=“flu, ">flue, </fillpart>

</body>
</html>


问:
Jquery.can make JQuery UI draggable,droppable,sortable work together?
In my page I have some dynamic created note sticker which draggable. And then I have a dropper which that sortable(enable sort) at the same time. I drag and drop the note sticker inside the dropper and sort(via drag) the sticker up and down inside the dropper!

I think I can make it using the Jquery UI. But always make mistake!

答:
This is how I do it.

Make all of the elements you want to connect and sort sortable, then use the connect with param to make all elements with the '.connectedSortable' class drag / droppable.

$("#list1, #list2, #list3").sortable({
                connectWith: '.connectedSortable',

etc....

Need source code to give you a proper reponse but this shoudl get you or anyone else with same question started.

Full (ish) example ripped from some prod code...

```<code>/* Widget assignment ui element bind */
            $("#leftAssignedWidgets, #unassignedWidgets, #rightAssignedWidgets, #topAssignedWidgets, #bottomAssignedWidgets").sortable({
                connectWith: '.connectedSortable',
                receive: function (event, ui) {
                    // recieve is only called when we drop a widget into a new section
                    // not when we move one around a section to reorder
                    // container id holds the id of the containder we dropped into

                    var widgetId = ui.item.attr('id');
                    var containerId = $(this).attr('id');

                    var widgetContainer = '';

                    switch (containerId) {
                        case 'topAssignedWidgets':
                            widgetContainer = 'top';
                            break;
                        case 'bottomAssignedWidgets':
                            widgetContainer = 'bottom';
                            break;
                        case 'leftAssignedWidgets':
                            widgetContainer = 'left';
                            break;
                        case 'rightAssignedWidgets':
                            widgetContainer = 'right';
                            break;
                        default:
                            widgetContainer = 'unassigned';
                            break;
                    }

                    // widgets have which positions they can be placed in stored as classes.
                    // ensure if we drop onto the right container the widget has the 'right' class. else error and return
                    // unless we drop it on unassigned in which case dont check as assign widghet below will remove it
                    if (!$(ui.item).hasClass(widgetContainer) && widgetContainer != 'unassigned') {

                        //ui.item.attr('class') example - 'ui-state-default right left'
                        // if a widget does not have the right class (i.e. left, when being dropped on the left panel )
                        if (ui.item.attr('class').indexOf(widgetContainer) == -1) {

                            var classList = ui.item.attr('class').replace('ui-state-default', '').split(/\s+/); ;
                            var classMessage = '';
                            $.each(classList, function (index, item) {
                                if (item != '') {
                                    classMessage += item + ',';
                                }
                            });
                            // remove traling ','
                            classMessage = classMessage.replace(/,$/, '')

                            $(ui.sender).sortable('cancel');

                            $("#dialog-wrong-placement p span").html(classMessage);
                            $("#dialog-wrong-placement").dialog({
                                height: 140,
                                modal: true
                            });

                            return;
                        }
                    }

                    AssignWidget(widgetId, containerId);
                },
                stop: function (event, ui) {
                    // stop is called everytime we stop dragging a widget. This means we need to ignore
                    // when a widget has been dropped into a new section as this will of been handled in the above
                    // recieve function. We use this behaviour to reorder items if they have been dropped on the same list

                    var containerId = $(this).attr('id');
                    var widgetId = ui.item.attr('id');

                    alert('a');
                    // if we drop it on unassigned then we will of deleted it os dont bother with reorder
                    if (containerId != 'unassignedWidgets') {
                        // if widget already exists in section then re-order
                        //    alert(containerId + ' ' + widgetId);
                        if ($('#' + containerId + ' li').index($('#' + widgetId)) > -1) {
                            // alert('u bet');
                            AssignWidget(widgetId, containerId);
                        }
                    }
                },
                placeholder: 'ui-state-highlight'
            });

            // setup colorbox
            $.each($(".widget-preview"), function (i, item) {
                $(this).colorbox({
                    width: "400px",
                    height: "400px",
                    inline: true,
                    href: "#view_widget",
                    onComplete: function () {
                        PreviewWidget($(this).closest('li').attr('id'));
                        if ($(this).hasClass('right')) {
                            $("#view_widget").addClass('right');
                        }
                    }
                })
            });

            $('#dialog-no-preview-available').dialog({
                            autoOpen: false,
                            height: 140,
                            modal: true
                        });

            $('.noPreviewAvailable').click(function () {
                $('#dialog-no-preview-available').dialog('open');
            });

            $("ul, li").disableSelection();
        }
</code>```

Body:
This is how I do it.

Make all of the elements you want to connect and sort sortable, then use the connect with param to make all elements with the '.connectedSortable' class drag / droppable.

$("#list1, #list2, #list3").sortable({
                connectWith: '.connectedSortable',

etc....

Need source code to give you a proper reponse but this shoudl get you or anyone else with same question started.

Full (ish) example ripped from some prod code...

/* Widget assignment ui element bind */
            $("#leftAssignedWidgets, #unassignedWidgets, #rightAssignedWidgets, #topAssignedWidgets, #bottomAssignedWidgets").sortable({
                connectWith: '.connectedSortable',
                receive: function (event, ui) {
                    // recieve is only called when we drop a widget into a new section
                    // not when we move one around a section to reorder
                    // container id holds the id of the containder we dropped into

                    var widgetId = ui.item.attr('id');
                    var containerId = $(this).attr('id');

                    var widgetContainer = '';

                    switch (containerId) {
                        case 'topAssignedWidgets':
                            widgetContainer = 'top';
                            break;
                        case 'bottomAssignedWidgets':
                            widgetContainer = 'bottom';
                            break;
                        case 'leftAssignedWidgets':
                            widgetContainer = 'left';
                            break;
                        case 'rightAssignedWidgets':
                            widgetContainer = 'right';
                            break;
                        default:
                            widgetContainer = 'unassigned';
                            break;
                    }

                    // widgets have which positions they can be placed in stored as classes.
                    // ensure if we drop onto the right container the widget has the 'right' class. else error and return
                    // unless we drop it on unassigned in which case dont check as assign widghet below will remove it
                    if (!$(ui.item).hasClass(widgetContainer) && widgetContainer != 'unassigned') {

                        //ui.item.attr('class') example - 'ui-state-default right left'
                        // if a widget does not have the right class (i.e. left, when being dropped on the left panel )
                        if (ui.item.attr('class').indexOf(widgetContainer) == -1) {

                            var classList = ui.item.attr('class').replace('ui-state-default', '').split(/\s+/); ;
                            var classMessage = '';
                            $.each(classList, function (index, item) {
                                if (item != '') {
                                    classMessage += item + ',';
                                }
                            });
                            // remove traling ','
                            classMessage = classMessage.replace(/,$/, '')

                            $(ui.sender).sortable('cancel');

                            $("#dialog-wrong-placement p span").html(classMessage);
                            $("#dialog-wrong-placement").dialog({
                                height: 140,
                                modal: true
                            });

                            return;
                        }
                    }

                    AssignWidget(widgetId, containerId);
                },
                stop: function (event, ui) {
                    // stop is called everytime we stop dragging a widget. This means we need to ignore
                    // when a widget has been dropped into a new section as this will of been handled in the above
                    // recieve function. We use this behaviour to reorder items if they have been dropped on the same list

                    var containerId = $(this).attr('id');
                    var widgetId = ui.item.attr('id');

                    alert('a');
                    // if we drop it on unassigned then we will of deleted it os dont bother with reorder
                    if (containerId != 'unassignedWidgets') {
                        // if widget already exists in section then re-order
                        //    alert(containerId + ' ' + widgetId);
                        if ($('#' + containerId + ' li').index($('#' + widgetId)) > -1) {
                            // alert('u bet');
                            AssignWidget(widgetId, containerId);
                        }
                    }
                },
                placeholder: 'ui-state-highlight'
            });

            // setup colorbox
            $.each($(".widget-preview"), function (i, item) {
                $(this).colorbox({
                    width: "400px",
                    height: "400px",
                    inline: true,
                    href: "#view_widget",
                    onComplete: function () {
                        PreviewWidget($(this).closest('li').attr('id'));
                        if ($(this).hasClass('right')) {
                            $("#view_widget").addClass('right');
                        }
                    }
                })
            });

            $('#dialog-no-preview-available').dialog({
                            autoOpen: false,
                            height: 140,
                            modal: true
                        });

            $('.noPreviewAvailable').click(function () {
                $('#dialog-no-preview-available').dialog('open');
            });

            $("ul, li").disableSelection();
        }


问:
Angular 2 - How to refresh my view datas?
I'm new in Angular 2 and I need some advices concerning my personal project.
I have two components, a formation list and a form to update my datas.
I work with services calls to update my datas and to display my formations list.
I had a problem with the datas update on my view but I resolved it by adding a timer to refresh datas.
I'm not fan of this solution because my service is called every second in my formation list interface :/

My question : What's the better way to refresh my view in my case ?

Thx in advance

答:
Your question is, how to trigger the change detection in your application. Specially when any observable/promise is fulfilled in the view, so you need to trigger the change detection in your application manually,

declare following in your component

```<code>constructor(private ref: ChangeDetectorRef)
</code>```

and mark all its ancestor for check by this method,

```<code>ref.markForCheck();
</code>```

in your application you can also trigger the change detection manually like given below,

```<code>ChangeDetectorRef.detectChanges()
</code>```

here is another awesome post about change detection that you can refer, which can provide you a little insight of change detection.

Stack overflow answer of change detection

Body:
Your question is, how to trigger the change detection in your application. Specially when any observable/promise is fulfilled in the view, so you need to trigger the change detection in your application manually,

declare following in your component

constructor(private ref: ChangeDetectorRef)

and mark all its ancestor for check by this method,

ref.markForCheck();

in your application you can also trigger the change detection manually like given below,

ChangeDetectorRef.detectChanges()

here is another awesome post about change detection that you can refer, which can provide you a little insight of change detection.

Stack overflow answer of change detection