问:
Do I had to loop? Is there a faster way to build dummy variables?
I have some plant data that looks like (but I have up to 7 attributes):

```<code>     Unnamed: 0     plant          att_1           att_2 ...
0            0     plant_a         sunlover        tall
1            1     plant_b         waterlover      sunlover
2            2     plant_c         fast growing    sunlover
</code>```

I tried to use pandas get_dummies like:

```<code>df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],'C': [1, 2, 3]})

pd.get_dummies(df, prefix=['col1', 'col2']):
</code>```

.

```<code> C  col1_a  col1_b  col2_a  col2_b  col2_c
 0  1       1       0       0       1       0
 1  2       0       1       1       0       0
 2  3       1       0       0       0       1
</code>```

But sunlover should be encoded as 1 nevertheless it is in att_1 or att_2. Then I will end up with approx 30 dummy variables instead of 7 * 30 = 210 variables.
I have tried to loop through the whole set and add the value for each dummy:

```<code>for count, plants in enumerate(data_plants.iterrows()):
  print("First", count, plants)
  for attribute in plants:
        print("Second", count, attribute)
</code>```

The code is just printing because i saw the issue of time wasting code.
That work but it is not fast enough to use for 100k and more rows. I thought of using .value_counts() to get the attributes and then accessing the dataframe dummy variable to update that to 1, but then I will overwrite the attribute.  At the moment I am a litte bit lost and out of ideas. Perhaps I had to use an other package?

The goal would be something like:

```<code>     Unnamed: 0     plant          att_1           att_2       sunlover      waterlover     tall  ...
0            0     plant_a         sunlover        tall        1             0              1
1            1     plant_b         waterlover      sunlover    1             1              0
2            2     plant_c         fast growing    sunlover    1             0              0
</code>```

答:
Use get_dummies with max:

```<code>c = ['att_1', 'att_2']
df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
print (df1)
     plant         att_1     att_2  fast growing  sunlover  waterlover  tall
0  plant_a      sunlover      tall             0         1           0     1
1  plant_b    waterlover  sunlover             0         1           1     0
2  plant_c  fast growing  sunlover             1         1           0     0
</code>```

Performance for 3k rows, in real data should be different:

```<code>df = pd.concat([df] * 1000, ignore_index=True)

In [339]: %%timeit
     ...:
     ...: c = ['att_1', 'att_2']
     ...: df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
     ...:
     ...:
10.7 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [340]: %%timeit
     ...: attCols = df[['att_1', 'att_2']]
     ...: colVals = pd.Index(np.sort(attCols.stack().unique()))
     ...: def myDummies(row):
     ...:     return pd.Series(colVals.isin(row).astype(int), index=colVals)
     ...:
     ...: df1 = df.join(attCols.apply(myDummies, axis=1))
     ...:
     ...:
1.03 s ± 22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Another solution:

```<code>In [133]: %%timeit
     ...: c = ['att_1', 'att_2']
     ...: df1 = (df.join(pd.DataFrame([dict.fromkeys(x, 1) for x in df[c].to_numpy()])
     ...:                  .fillna(0)
     ...:                  .astype(np.int8)))
     ...:
13.1 ms ± 723 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
I have some plant data that looks like (but I have up to 7 attributes):

     Unnamed: 0     plant          att_1           att_2 ...
0            0     plant_a         sunlover        tall
1            1     plant_b         waterlover      sunlover
2            2     plant_c         fast growing    sunlover

I tried to use pandas get_dummies like:

df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'],'C': [1, 2, 3]})

pd.get_dummies(df, prefix=['col1', 'col2']):

.

 C  col1_a  col1_b  col2_a  col2_b  col2_c
 0  1       1       0       0       1       0
 1  2       0       1       1       0       0
 2  3       1       0       0       0       1

But sunlover should be encoded as 1 nevertheless it is in att_1 or att_2. Then I will end up with approx 30 dummy variables instead of 7 * 30 = 210 variables.
I have tried to loop through the whole set and add the value for each dummy:

for count, plants in enumerate(data_plants.iterrows()):
  print("First", count, plants)
  for attribute in plants:
        print("Second", count, attribute)

The code is just printing because i saw the issue of time wasting code.
That work but it is not fast enough to use for 100k and more rows. I thought of using .value_counts() to get the attributes and then accessing the dataframe dummy variable to update that to 1, but then I will overwrite the attribute.  At the moment I am a litte bit lost and out of ideas. Perhaps I had to use an other package?

The goal would be something like:

     Unnamed: 0     plant          att_1           att_2       sunlover      waterlover     tall  ...
0            0     plant_a         sunlover        tall        1             0              1
1            1     plant_b         waterlover      sunlover    1             1              0
2            2     plant_c         fast growing    sunlover    1             0              0

Body:
Use get_dummies with max:

c = ['att_1', 'att_2']
df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
print (df1)
     plant         att_1     att_2  fast growing  sunlover  waterlover  tall
0  plant_a      sunlover      tall             0         1           0     1
1  plant_b    waterlover  sunlover             0         1           1     0
2  plant_c  fast growing  sunlover             1         1           0     0

Performance for 3k rows, in real data should be different:

df = pd.concat([df] * 1000, ignore_index=True)

In [339]: %%timeit
     ...:
     ...: c = ['att_1', 'att_2']
     ...: df1 = df.join(pd.get_dummies(df[c], prefix='', prefix_sep='').max(axis=1, level=0))
     ...:
     ...:
10.7 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [340]: %%timeit
     ...: attCols = df[['att_1', 'att_2']]
     ...: colVals = pd.Index(np.sort(attCols.stack().unique()))
     ...: def myDummies(row):
     ...:     return pd.Series(colVals.isin(row).astype(int), index=colVals)
     ...:
     ...: df1 = df.join(attCols.apply(myDummies, axis=1))
     ...:
     ...:
1.03 s ± 22 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Another solution:

In [133]: %%timeit
     ...: c = ['att_1', 'att_2']
     ...: df1 = (df.join(pd.DataFrame([dict.fromkeys(x, 1) for x in df[c].to_numpy()])
     ...:                  .fillna(0)
     ...:                  .astype(np.int8)))
     ...:
13.1 ms ± 723 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


来源: stackexchange

问:
Fill_between error python - giving me error: ordinal must be >= 1
I have the following code:

```<code>ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],where = None,color='yellow',alpha=0.25)
plt.show()
</code>```

However, I keep getting the error:

ordinal must be >= 1

Could anybody give me a helping hand?

I can't understand why the 'fill_between' function is not working.

答:
This code works:

```<code>  plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
</code>```

Essentially, I was using pandas plotting for the line plots while using standard matplotlib for the fill_between.

Thus, using range(len(datamax['Date'])) instead of datamax['Date'] overcame this compatibility issue.

ContentLicense: CC BY-SA 4.0

Body:
I have the following code:

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],where = None,color='yellow',alpha=0.25)
plt.show()

However, I keep getting the error:

ordinal must be >= 1

Could anybody give me a helping hand?

I can't understand why the 'fill_between' function is not working.

Body:
This code works:

  plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)

Essentially, I was using pandas plotting for the line plots while using standard matplotlib for the fill_between.

Thus, using range(len(datamax['Date'])) instead of datamax['Date'] overcame this compatibility issue.


问:
can we create a conditional zip that doesn't consume input when false?
I want to create a generator which pulls from two generators but doesn't consume the input of both when the condition is false.

I have been using the itertools docs as reference which is quite helpful, but it seems what I want to do is not possible within itertools.

here is a pytest I want to pass:

    def test_itertools_example(self):
        import itertools
        cond = itertools.cycle([True, False])
        none = itertools.repeat(None)
        data = itertools.count(1, 1)
        every_other = (d if c else n for (c, d, n) in zip(cond, data, none))
        assert next(every_other) == 1
        assert next(every_other) is None
        assert next(every_other) == 2  # this is 3 and i want 2 but 2 got dropped on the previous call
        assert next(every_other) is None
```

答:
You can just write:</p>

```<code>every_other = (next(data) if c else next(none) for c in cond)
</code>```

Body:
You can just write:

every_other = (next(data) if c else next(none) for c in cond)


问:
How can I get the number of users in a voice channel?
I'm making a music bot, when the member writes "~play" the bot search a random file (.mp3) in a folder, and joines the voice channel where the user currently in. I want my bot to leave the voice channel when all the users leave the voicechannel.</p>

```<code>const fs = require('fs');

module.exports.run = async (bot, message, args) => {

let channel = message.member.voice.channel;
if(!channel) return message.reply("You're not connected to a voice channel!");

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" started this song: " + ` ${randomfile}`)
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })

        dispatcher.on('error', (err) => console.log(err));

        if(channel.members == 1){  //this is the problem
          channel.leave()
        }

        dispatcher.on('finish', finish => {
            message.reply(" Song ended! - " + ` ${randomfile}`)
            //console.log("Playing ended");
            channel.leave()
        })
    }).catch(err => console.error(err))
}
</code>```

答:
I found the answer. Here's my code:</p>

```<code>const fs = require('fs');

module.exports.run = async (bot, message, args) => {
let found = 0;
let channel = message.member.voice.channel;

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" has started this song: " + ` ${randomfile}`).then(sent => {
            sentmessage = sent;
            //console.log(id);
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })
        dispatcher.on('error', (err) => console.log(err));

        const voicechannel = message.member.voice.channel; //saving the voicechannel to an array

        for (const [memberID, member] of voicechannel.members) { //look for member in the voicechannel array
          if(member.user) found++; //member gives giuld.user, when found, found++

          if(found < 1) return channel.leave();

          //console.log("when bot joins:" + found);
        }

        bot.on("voiceStateUpdate", (oldState, newState) => {
            let oldVoice = oldState.channelID;
            let newVoice = newState.channelID;
            if (oldVoice != newVoice) {
                if (oldVoice == null) {
                    //console.log("before join:" + found);
                    found++;
                    //console.log("after join:" + found);
                    //console.log("User joined!");
                }
                if (newVoice == null) {
                    //console.log("before leaving:" + found);
                    found--;
                    //console.log("after leaving:" + found);
                    if(found == 1) return channel.leave();
                  }
             }
        })

        dispatcher.on('finish', finish => {
            message.reply(" song ended! - " + ` ${randomfile}`)
            //console.log("Playing end");
            channel.leave()
        })
    }).catch(err => console.error(err))
  }
};

module.exports.help = {
    name: "play"
  };
</code>```

Body:
I'm making a music bot, when the member writes "~play" the bot search a random file (.mp3) in a folder, and joines the voice channel where the user currently in. I want my bot to leave the voice channel when all the users leave the voicechannel.

const fs = require('fs');

module.exports.run = async (bot, message, args) => {

let channel = message.member.voice.channel;
if(!channel) return message.reply("You're not connected to a voice channel!");

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" started this song: " + ` ${randomfile}`)
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })

        dispatcher.on('error', (err) => console.log(err));

        if(channel.members == 1){  //this is the problem
          channel.leave()
        }

        dispatcher.on('finish', finish => {
            message.reply(" Song ended! - " + ` ${randomfile}`)
            //console.log("Playing ended");
            channel.leave()
        })
    }).catch(err => console.error(err))
}

Body:
I found the answer. Here's my code:

const fs = require('fs');

module.exports.run = async (bot, message, args) => {
let found = 0;
let channel = message.member.voice.channel;

if (channel) {

    channel.join()
    .then(connection => {

        const commandFiles = fs.readdirSync('./commands/Workout/').filter(file => file.endsWith('.mp3'));
        let randomfile = commandFiles[Math.floor(Math.random() * commandFiles.length)]

        const dispatcher = connection.play(`./commands/Workout/${randomfile}`);

        dispatcher.on('start', () => {
            dispatcher.setVolume(0.70);
            message.reply(" has started this song: " + ` ${randomfile}`).then(sent => {
            sentmessage = sent;
            //console.log(id);
          }).catch(err => console.error(err))
            //console.log("Playing music");
        })
        dispatcher.on('error', (err) => console.log(err));

        const voicechannel = message.member.voice.channel; //saving the voicechannel to an array

        for (const [memberID, member] of voicechannel.members) { //look for member in the voicechannel array
          if(member.user) found++; //member gives giuld.user, when found, found++

          if(found < 1) return channel.leave();

          //console.log("when bot joins:" + found);
        }

        bot.on("voiceStateUpdate", (oldState, newState) => {
            let oldVoice = oldState.channelID;
            let newVoice = newState.channelID;
            if (oldVoice != newVoice) {
                if (oldVoice == null) {
                    //console.log("before join:" + found);
                    found++;
                    //console.log("after join:" + found);
                    //console.log("User joined!");
                }
                if (newVoice == null) {
                    //console.log("before leaving:" + found);
                    found--;
                    //console.log("after leaving:" + found);
                    if(found == 1) return channel.leave();
                  }
             }
        })

        dispatcher.on('finish', finish => {
            message.reply(" song ended! - " + ` ${randomfile}`)
            //console.log("Playing end");
            channel.leave()
        })
    }).catch(err => console.error(err))
  }
};

module.exports.help = {
    name: "play"
  };


问:
Failed to find Build Tools revision 26.0.2
How am i going to fix this? I downloaded the SDKs that i need but but the error does not go away.enter image description here</p>

答:
your need build tool 29.0.2.

for install =>

1.File>Setting>Appearavne & Behavior>System Setting>Android SDK.
2.go to tab SDK Tools
3. on check android SDK Tools X.X.X(Download)


问:
Hover over one element to make a different element visible
I have been told that this isn't possible via CSS alone and so have turned to javascript.

Using onmouseover but I cannot get the hidden element to appear. I want it so that when hovering over element with ID #a, element with class .excerpt-box appears and then disappears when the mouse is moved away.

Does anyone know where I am going wrong? Thanks

Here's the code I've written so far:

The CSS includes visibility hidden for .excerpt-box.

 Read more

This is an example excerpt title...

          <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>function showExcerpt() {
  document.getElementByClass('excerpt-box').style.visibility = 'visible';
}</code>```

答:
First, the function you are looking for is document.getElementsByClassName.
After this you have to select a particular element by index. See this link.

Better would be this solution:
Grab the id of the div (id='b') and set display to block.
As you can see, the div is display:none; at startup.

function showExcerpt() {
  document.getElementById('b').style.display = 'block';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.excerpt-box {
  display: none;
}</code>```

 Read more

This is an example excerpt title...

  <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Body:
I have been told that this isn't possible via CSS alone and so have turned to javascript.

Using onmouseover but I cannot get the hidden element to appear. I want it so that when hovering over element with ID #a, element with class .excerpt-box appears and then disappears when the mouse is moved away.

Does anyone know where I am going wrong? Thanks

Here's the code I've written so far:

The CSS includes visibility hidden for .excerpt-box.

 Read more

This is an example excerpt title...

          <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

function showExcerpt() {
  document.getElementByClass('excerpt-box').style.visibility = 'visible';
}

Body:
First, the function you are looking for is document.getElementsByClassName.
After this you have to select a particular element by index. See this link.

Better would be this solution:
Grab the id of the div (id='b') and set display to block.
As you can see, the div is display:none; at startup.

function showExcerpt() {
  document.getElementById('b').style.display = 'block';
}

.excerpt-box {
  display: none;
}

<div class="ind-circle" id="a" onmouseover="showExcerpt()">
  <p class="circle-title"> <a href="#">Read more</a></p>
</div>

<div class="excerpt-box" id="b">
  <h1 class="excerpts-title">This is an example excerpt title...</h1>
  <img class="excerpts-fi" src="<?php echo BASE_URL . '/assets/images/water.jpg'; ?>" alt="">
  <p class="excerpts-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>


问:
Can I infer a enum value, from a Generic param?

What I want

I would like a general-use hook, to create getter/setters for a specific Pre-existing property. My aspirational implementation would look like:

```<code>const [getTitle, setTitle] = useUpdateState("title", "<defaultTitle>");
const [getAge, setAge] = useUpdateState("age", 44);
const [getErr, setErr] = useUpdateState("age", "44"); // Must error, as my types (defined elsewhere) state "age" must be number
</code>```

Alternative:

```<code>const [getTitle, setTitle] = useUpdateState<TitleUpdate>("Mr");
const [getAge, setAge] = useUpdateState<AgeUpdate>(44);
const [getErr, setErr] = useUpdateState<AgeUpdate>("44"); // Must error
</code>```

What I have

But my current implementation  requires that I pass in a type AND property, to ensure the defaultValue's type is correct.

```<code>
const [getTitle, setTitle] = useUpdateState<TitleUpdate>(Properties.title, "Mr");
const [getAge, setAge] = useUpdateState<AgeUpdate>(Properties.age, 44);
const [getErr, setErr] = useUpdateState<AgeUpdate>(Properties.age, "44"); // Must Error!
</code>```

It feels like both type and property should be unnecessary.

Here is the implementation I have so far (TypeScriptPlaygroud)

```<code>enum Properties {
    title = 'title',
    age = 'age',
};
type TitleUpdate = { property: Properties.title, value: string };
type AgeUpdate = { property: Properties.age, value: number };

type Update = TitleUpdate | AgeUpdate;

let state: {
    [Properties.title]: TitleUpdate['value'],
    [Properties.age]: AgeUpdate['value'],
} = {
    [Properties.title]: '',
    [Properties.age]: 0,
}

const useUpdateState = <U extends Update>(property: Properties, defaultValue: U['value']) => {
    // const property = Properties[keyof U]; // <- Want to infer this from U
    const getter = (): U['value'] => state[property];
    const setter = (value: U['value']): void => {
        state = { ...state, ...{ [property]: value } }
    };
    setter(defaultValue);
return [getter, setter];
}
</code>```

答:
It will be a bit easier to define a state shape, then restrict the hook to accept only valid state keys with corresponding valid values:

```<code>type State = { [Properties.title]: string, [Properties.age]: number };

const useUpdateState = <P extends keyof State>(property: P, defaultValue: State[P]) => {
// ...
</code>```

Playground

Body:
What I want

I would like a general-use hook, to create getter/setters for a specific Pre-existing property. My aspirational implementation would look like:

const [getTitle, setTitle] = useUpdateState("title", "<defaultTitle>");
const [getAge, setAge] = useUpdateState("age", 44);
const [getErr, setErr] = useUpdateState("age", "44"); // Must error, as my types (defined elsewhere) state "age" must be number

Alternative:

const [getTitle, setTitle] = useUpdateState<TitleUpdate>("Mr");
const [getAge, setAge] = useUpdateState<AgeUpdate>(44);
const [getErr, setErr] = useUpdateState<AgeUpdate>("44"); // Must error

What I have

But my current implementation  requires that I pass in a type AND property, to ensure the defaultValue's type is correct.

const [getTitle, setTitle] = useUpdateState<TitleUpdate>(Properties.title, "Mr");
const [getAge, setAge] = useUpdateState<AgeUpdate>(Properties.age, 44);
const [getErr, setErr] = useUpdateState<AgeUpdate>(Properties.age, "44"); // Must Error!

It feels like both type and property should be unnecessary.

Here is the implementation I have so far (<a href="https://www.typescriptlang.org/play/?ssl=29&ssc=87&pln=29&pc=72#code/KYOwrgtgBACgTgewA7DgFwJbAM5QN4CwAUFKVJmgDbBQC8UA5BdQwDTFlQCGA5jfQ17A2xAL4BuYmgCeKKABUMVYAFUkAEy5p++KEkQp00gFywDqTDgB0zYKygA3LpTDBT2NHAwgeUCVNkaAEE+NU1tOl19ZAsTMxj0LGwrIXsnFzcocAgAI1Q-SSIAuTCtHUVlUoiAHygQ1Q0ywuJqNCgPMtNCEjIAbXgEy2TbAF1TCuoq4F6GdNcGEfYe0n7zROshMbrQxu0ZueFFsUjuzlXBpJslai2GEWWoc8MhlL4tgAYl0WJiAGMEEAeKBgbANcLAADKaDKkQAPCooMAAB7aEDqXBTAB8AApos84gNnkl7OpgAAzLhgShoABqzlcphU+3phwAlHRMfgOGQAPQ8qD-QFtPGxSKEixJXoAa2A0gQZKgKhG4igfKgsIAtFAAOpcEBtNAIKDeMn5NAACwwuDJiGgKm5pEFQL4aG0cEi2NZjOZGQWHPa0L2IqMyodAoBQNBrvy9GxB29sxZCy9jgQGHU-tOnDIHQi9DwUCsRdzdkLRYLvWDMi2Bz8fjD-geUbd2NJFKptJZrMKcGAaDAcBAjxdbvszdQoaI3yKRCdbV6LompajS5GkRBYLKULKsKXWOx4vWw2upYARABZOCn7t-CPzl31Md9+pr+gbqbb7Sw+r7w8vVJQAALIB3aqvy54gm0ACicCIHAACEt5CsOfYwXAT5oGhr7AqCH6BsA347OCOJ-pcAGnsB14qmqEFAmhCAIUAA" rel="nofollow noreferrer">TypeScriptPlaygroud)

enum Properties {
    title = 'title',
    age = 'age',
};
type TitleUpdate = { property: Properties.title, value: string };
type AgeUpdate = { property: Properties.age, value: number };

type Update = TitleUpdate | AgeUpdate;

let state: {
    [Properties.title]: TitleUpdate['value'],
    [Properties.age]: AgeUpdate['value'],
} = {
    [Properties.title]: '',
    [Properties.age]: 0,
}

const useUpdateState = (property: Properties, defaultValue: U['value']) => {
    // const property = Properties[keyof U]; // <- Want to infer this from U
    const getter = (): U['value'] => state[property];
    const setter = (value: U['value']): void => {
        state = { ...state, ...{ [property]: value } }
    };
    setter(defaultValue);
return [getter, setter];
}

Body:
It will be a bit easier to define a state shape, then restrict the hook to accept only valid state keys with corresponding valid values:

type State = { [Properties.title]: string, [Properties.age]: number };

const useUpdateState = <P extends keyof State>(property: P, defaultValue: State[P]) => {
// ...

<a href="https://www.typescriptlang.org/play/#code/KYOwrgtgBACgTgewA7DgFwJbAM5QN4CwAUFKVJmgDbBQC8UA5BdQwDTFlQCGA5jfQ17A2xAL4BuYsTQBPFFADKaLmn74oAbXjJUmHADpmwALoAuKNjRwMIHq03aU6LNn1CzUcBABGqKBKkiajQLZVVzJRU1QhIyLUQnPVcjDwYRWNJ4nWcDd3MABnYiUUCAYwQQSygwbGAAVSQAEyjI1TooAB4YKGAAD1UQRtwAa2AZBAAzRTDgAD4ACiQE3RlzGHtG4AmuMEo0ADUuSjBgCJmtYwBKOln8DjJyypC+NFU4dvnLs6iLm9CfpbZWTGSQZKCPKq1V5+ejzABuRxO31UFy+UDhCAwjT+MU4nEsUXaeCg+lJBNU9lJ+mJGkBiRkHgRxxoon891IATBULe802212B0RwEuoM4cGAaDAcBAmheb3s3NQILEZQqVQ0LwAKhgqMAFRLtbrjO0avUmi0ZvNHLoXIYddR7AAiACycEdIuIEJCGolAEE+Pq0P6TCbag1mqpWsArcscq4hPYACyJkVQAD0aagzpqIQAonBEHAAISetXel75uCByvG+im8MWqIxoG2hNQR02JlY9FC93idOZ7NVSsIYulp6aLj2by16ph82Ry0MMAgYYgBAAdxldLY7eTfYHWZzUBHxaAA" rel="nofollow noreferrer">Playground


问:
button with corner and hide bottom border
The result i want

what i'm getting :

i use this code:

```<code>    func roundedTopLeftButton(radius : Int, colorBorder : UIColor) {
    // Add border
       let gradient = CAGradientLayer()
       let size = CGSize(width: self.frame.width, height: self.frame.height)
       let rect = CGRect(origin: .zero, size: size)
       gradient.frame =  CGRect(origin: CGPoint.zero, size: size)
       gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]

       let shape = CAShapeLayer()
       shape.lineWidth = 2

       shape.path = UIBezierPath(roundedRect: rect,
       byRoundingCorners: [.topLeft , .topRight],
       cornerRadii: CGSize(width: radius, height: radius)).cgPath
       shape.strokeColor = colorBorder.cgColor
       shape.fillColor = UIColor.clear.cgColor
       gradient.mask = shape

    self.layer.addSublayer(shape)
}
</code>```

how can hide buttom border for the button Paiements please ?

答:
Use a custom path, there is nothing complicated with Corner Radius.
You just need to draw your shape on a paper sheet. Mark the point of interests, know a little about trigonometry (and that's just to know the angles) and a little of basic geometry.</p>

```<code>let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: bounds.size.height))
path.addLine(to: CGPoint(x: 0, y: radius))
path.addArc(withCenter: CGPoint(x: radius, y: radius),
            radius: radius,
            startAngle: CGFloat.pi,
            endAngle: -CGFloat.pi/2.0,
            clockwise: true)
path.addLine(to: CGPoint(x: bounds.size.width - radius, y: 0))
path.addArc(withCenter: CGPoint(x: bounds.width - radius, y: radius),
            radius: radius,
            startAngle: -CGFloat.pi/2.0,
            endAngle: 0,
            clockwise: true)
path.addLine(to: CGPoint(x: bounds.size.width, y: bounds.size.height))
</code>```

Body:
The result i want

what i'm getting :

i use this code:

    func roundedTopLeftButton(radius : Int, colorBorder : UIColor) {
    // Add border
       let gradient = CAGradientLayer()
       let size = CGSize(width: self.frame.width, height: self.frame.height)
       let rect = CGRect(origin: .zero, size: size)
       gradient.frame =  CGRect(origin: CGPoint.zero, size: size)
       gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]

       let shape = CAShapeLayer()
       shape.lineWidth = 2

       shape.path = UIBezierPath(roundedRect: rect,
       byRoundingCorners: [.topLeft , .topRight],
       cornerRadii: CGSize(width: radius, height: radius)).cgPath
       shape.strokeColor = colorBorder.cgColor
       shape.fillColor = UIColor.clear.cgColor
       gradient.mask = shape

    self.layer.addSublayer(shape)
}

how can hide buttom border for the button Paiements please ?

Body:
Use a custom path, there is nothing complicated with Corner Radius.
You just need to draw your shape on a paper sheet. Mark the point of interests, know a little about trigonometry (and that's just to know the angles) and a little of basic geometry.

let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: bounds.size.height))
path.addLine(to: CGPoint(x: 0, y: radius))
path.addArc(withCenter: CGPoint(x: radius, y: radius),
            radius: radius,
            startAngle: CGFloat.pi,
            endAngle: -CGFloat.pi/2.0,
            clockwise: true)
path.addLine(to: CGPoint(x: bounds.size.width - radius, y: 0))
path.addArc(withCenter: CGPoint(x: bounds.width - radius, y: radius),
            radius: radius,
            startAngle: -CGFloat.pi/2.0,
            endAngle: 0,
            clockwise: true)
path.addLine(to: CGPoint(x: bounds.size.width, y: bounds.size.height))


问:
Technical difference between Spring Boot with JOOQ and Spring Data JPA
When would you use Spring Data JPA over Spring Boot with JOOQ and vice versa?

I know that Spring Data JPA can be used for completing basic CRUD queries, but not really for complex join queries while using JOOQ makes it easier?

EDIT: Can you use both Spring data jpa with jooq?

答:
There is no easy answer to your question. I have given a couple of talks on that topic. Sometimes there are good reasons to have both in a project.

Edit: IMHO Abstraction over the database in regards of dialects and datatypes is not the main point here!! jOOQ does a pretty good job to generate SQL for a given target dialect - and so does JPA / Hibernate. I would even say that jOOQ goes an extra mile to emulate functions for databases that don't have all the bells and whistles like Postgres or Oracle.
The question here is "Do I want to be able to express a query myself with everything SQL has to offer or am I happy with what JPA can express?"

Here's an example to run both together. I have a Spring Data JPA provided repository here with a custom extension (interface and implementation are necessary). I let the Spring context inject both the JPA EntityManager as well as the jOOQ context. I then use jOOQ to create queries and run them through JPA.
Why? Because expressing the query in question is not possible with JPA ("Give me the thing I listened the most" which is not the one having the highest number of count, but could be several).

The reason I run the query through JPA is simple: A downstream use case might require me to pass JPA entities to it. jOOQ can of course run this query itself and you could work on records or map the stuff anyway u like. But as you specifically asked about maybe using both technologies, I thought this is a good example:

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.SelectQuery;
import org.jooq.conf.ParamType;
import org.jooq.impl.DSL;
import org.springframework.data.repository.CrudRepository;

import static ac.simons.bootiful_databases.db.tables.Genres.GENRES;
import static ac.simons.bootiful_databases.db.tables.Plays.PLAYS;
import static ac.simons.bootiful_databases.db.tables.Tracks.TRACKS;
import static org.jooq.impl.DSL.count;
import static org.jooq.impl.DSL.rank;
import static org.jooq.impl.DSL.select;

public interface GenreRepository extends
        CrudRepository<GenreEntity, Integer>, GenreRepositoryExt {

    List<GenreEntity> findAllByOrderByName();
}

interface GenreRepositoryExt {
    List<GenreWithPlaycount> findAllWithPlaycount();

    List<GenreEntity> findWithHighestPlaycount();
}

class GenreRepositoryImpl implements GenreRepositoryExt {

    private final EntityManager entityManager;

    private final DSLContext create;

    public GenreRepositoryImpl(EntityManager entityManager, DSLContext create) {
        this.entityManager = entityManager;
        this.create = create;
    }

    @Override
    public List<GenreWithPlaycount> findAllWithPlaycount() {
        final Field<Integer> cnt = count().as("cnt");
        return this.create
                .select(GENRES.GENRE, cnt)
                .from(PLAYS)
                .join(TRACKS).onKey()
                .join(GENRES).onKey()
                .groupBy(GENRES.GENRE)
                .orderBy(cnt)
                .fetchInto(GenreWithPlaycount.class);
    }

    @Override
    public List<GenreEntity> findWithHighestPlaycount() {
        /*
        select id, genre
        from (
          select g.id, g.genre, rank() over (order by count(*) desc) rnk
            from plays p
            join tracks t on p.track_id = t.id
            join genres g on t.genre_id = g.id
           group by g.id, g.genre
        ) src
        where src.rnk = 1;
        */
        final SelectQuery<Record> sqlGenerator =
        this.create.select()
                .from(
                        select(
                                GENRES.ID, GENRES.GENRE,
                                rank().over().orderBy(count().desc()).as("rnk")
                        ).from(PLAYS)
                        .join(TRACKS).onKey()
                        .join(GENRES).onKey()
                        .groupBy(GENRES.ID, GENRES.GENRE)
                ).where(DSL.field("rnk").eq(1)).getQuery();

         // Retrieve sql with named parameter
        final String sql = sqlGenerator.getSQL(ParamType.NAMED);
        // and create actual hibernate query
        final Query query = this.entityManager.createNativeQuery(sql, GenreEntity.class);
        // fill in parameter
        sqlGenerator.getParams().forEach((n, v) -> query.setParameter(n, v.getValue()));
        // execute query
        return query.getResultList();
    }
}
```

I spoke about this a couple of times. There is no silver bullet in those tech, sometimes it's a very thin judgement:

The full talk is here: https://speakerdeck.com/michaelsimons/live-with-your-sql-fetish-and-choose-the-right-tool-for-the-job

As well as the recorded version of it: https://www.youtube.com/watch?v=NJ9ZJstVL9E

The full working example is here https://github.com/michael-simons/bootiful-databases.

Body:
There is no easy answer to your question. I have given a couple of talks on that topic. Sometimes there are good reasons to have both in a project.

Edit: IMHO Abstraction over the database in regards of dialects and datatypes is not the main point here!! jOOQ does a pretty good job to generate SQL for a given target dialect - and so does JPA / Hibernate. I would even say that jOOQ goes an extra mile to emulate functions for databases that don't have all the bells and whistles like Postgres or Oracle.
The question here is "Do I want to be able to express a query myself with everything SQL has to offer or am I happy with what JPA can express?"

Here's an example to run both together. I have a Spring Data JPA provided repository here with a custom extension (interface and implementation are necessary). I let the Spring context inject both the JPA EntityManager as well as the jOOQ context. I then use jOOQ to create queries and run them through JPA.
Why? Because expressing the query in question is not possible with JPA ("Give me the thing I listened the most" which is not the one having the highest number of count, but could be several).

The reason I run the query through JPA is simple: A downstream use case might require me to pass JPA entities to it. jOOQ can of course run this query itself and you could work on records or map the stuff anyway u like. But as you specifically asked about maybe using both technologies, I thought this is a good example:

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.SelectQuery;
import org.jooq.conf.ParamType;
import org.jooq.impl.DSL;
import org.springframework.data.repository.CrudRepository;

import static ac.simons.bootiful_databases.db.tables.Genres.GENRES;
import static ac.simons.bootiful_databases.db.tables.Plays.PLAYS;
import static ac.simons.bootiful_databases.db.tables.Tracks.TRACKS;
import static org.jooq.impl.DSL.count;
import static org.jooq.impl.DSL.rank;
import static org.jooq.impl.DSL.select;

public interface GenreRepository extends
        CrudRepository<GenreEntity, Integer>, GenreRepositoryExt {

    List<GenreEntity> findAllByOrderByName();
}

interface GenreRepositoryExt {
    List<GenreWithPlaycount> findAllWithPlaycount();

    List<GenreEntity> findWithHighestPlaycount();
}

class GenreRepositoryImpl implements GenreRepositoryExt {

    private final EntityManager entityManager;

    private final DSLContext create;

    public GenreRepositoryImpl(EntityManager entityManager, DSLContext create) {
        this.entityManager = entityManager;
        this.create = create;
    }

    @Override
    public List<GenreWithPlaycount> findAllWithPlaycount() {
        final Field<Integer> cnt = count().as("cnt");
        return this.create
                .select(GENRES.GENRE, cnt)
                .from(PLAYS)
                .join(TRACKS).onKey()
                .join(GENRES).onKey()
                .groupBy(GENRES.GENRE)
                .orderBy(cnt)
                .fetchInto(GenreWithPlaycount.class);
    }

    @Override
    public List<GenreEntity> findWithHighestPlaycount() {
        /*
        select id, genre
        from (
          select g.id, g.genre, rank() over (order by count(*) desc) rnk
            from plays p
            join tracks t on p.track_id = t.id
            join genres g on t.genre_id = g.id
           group by g.id, g.genre
        ) src
        where src.rnk = 1;
        */
        final SelectQuery<Record> sqlGenerator =
        this.create.select()
                .from(
                        select(
                                GENRES.ID, GENRES.GENRE,
                                rank().over().orderBy(count().desc()).as("rnk")
                        ).from(PLAYS)
                        .join(TRACKS).onKey()
                        .join(GENRES).onKey()
                        .groupBy(GENRES.ID, GENRES.GENRE)
                ).where(DSL.field("rnk").eq(1)).getQuery();

         // Retrieve sql with named parameter
        final String sql = sqlGenerator.getSQL(ParamType.NAMED);
        // and create actual hibernate query
        final Query query = this.entityManager.createNativeQuery(sql, GenreEntity.class);
        // fill in parameter
        sqlGenerator.getParams().forEach((n, v) -> query.setParameter(n, v.getValue()));
        // execute query
        return query.getResultList();
    }
}

I spoke about this a couple of times. There is no silver bullet in those tech, sometimes it's a very thin judgement:

The full talk is here: https://speakerdeck.com/michaelsimons/live-with-your-sql-fetish-and-choose-the-right-tool-for-the-job

As well as the recorded version of it: https://www.youtube.com/watch?v=NJ9ZJstVL9E

The full working example is here https://github.com/michael-simons/bootiful-databases.


问:
How to avoid Image Area showing Blue before Loading App
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

```<code> Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),
</code>```

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.

答:
This Cookbook solution is designed for this situation. Just replace the CircularProgressIndicator with whatever you want to show before the image is loaded.

https://flutter.dev/docs/cookbook/images/fading-in-images

Body:
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

 Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.


问:
attr_accessor causes Rspec tests to fail
I've added a :username_or_email property to my User model as such:

```<code>class User < ActiveRecord::Base

  #authlogic
  acts_as_authentic do |c|
    c.login_field = :username_or_email
  end

  #virtual field for allowing a user to login with their username or email
  attr_accessor :username_or_email

  attr_accessible :username, :email, :password, :password_confirmation, :username_or_email

  validates :username, :presence => true,
                       :length => { :within => 3..20 },
                       :uniqueness => true,
                       :format => { :with => /\A[a-z0-9][a-z0-9\-]+[a-z0-9]\z/ }

  validates :email, :presence => true,
                    :format => { :with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i },
                    :uniqueness => { :case_sensative => false }

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }

  def self.find_by_username_or_email(username_or_email)
    User.find_by_username(username_or_email) || User.find_by_email(username_or_email)
  end

end
</code>```

The purpose of this is to create a virtual field which allows the user to log in with either their username or email using Authlogic.  This works perfectly when I run the server, doing exactly what I want it to.  However, it causes all of the following specs to fail:

```<code>require 'spec_helper'

describe User do

  before(:each) do
    @attr = {
      :username => "example",
      :email => "user@example.com",
      :password => "password",
      :password_confirmation => "password"
    }
  end

  describe "username validations" do

    it "should allow usernames with numbers" do
      User.create!(@attr.merge(:username => 'example123'))
    end

    it "should allow hyphens" do
      User.create!(@attr.merge(:username => 'example-two'))
    end

    it "should require a username" do
      no_username_user = User.new (@attr.merge(:username => ""))
      no_username_user.should_not be_valid
    end

    it "should reject usernames that are too long" do
      user = User.new(@attr.merge(:username => ("a" * 21)))
      user.should_not be_valid
    end

    it "should reject username that are too short" do
      user = User.new(@attr.merge(:username => ("a" * 2)))
      user.should_not be_valid
    end

    it "should reject username with uppercase letters" do
      user = User.new(@attr.merge(:username => "Example"))
      user.should_not be_valid
    end

    it "should reject duplicate usernames" do
      User.create!(@attr)
      user = User.new(@attr.merge(:email => "user2@example.com"))
      user.should_not be_valid
    end

    it "should reject usernames with whitespace characters" do
      u1 = User.new(@attr.merge(:username => "exa mple"))
      u2 = User.new(@attr.merge(:username => " example"))
      u3 = User.new(@attr.merge(:username => "example "))
      u4 = User.new(@attr.merge(:username => "exa\tmple"))
      u5 = User.new(@attr.merge(:username => "exa\nmple"))

      u1.should_not be_valid
      u2.should_not be_valid
      u3.should_not be_valid
      u4.should_not be_valid
      u5.should_not be_valid
    end

    it "should reject usernames with special characters" do
      u1 = User.new(@attr.merge(:username => 'ex&mple'))
      u2 = User.new(@attr.merge(:username => 'ex*mple'))
      u3 = User.new(@attr.merge(:username => 'ex"mple'))
      u4 = User.new(@attr.merge(:username => 'ex^mple'))
      u5 = User.new(@attr.merge(:username => 'ex;mple'))

      u1.should_not be_valid
      u2.should_not be_valid
      u3.should_not be_valid
      u4.should_not be_valid
      u5.should_not be_valid
    end

    it "should reject usernames that begin with a hypen" do
      user = User.new(@attr.merge(:username => '-example'))
      user.should_not be_valid
    end

    it "should reject usernames that end with a hypen" do
      user = User.new(@attr.merge(:username => 'example-'))
      user.should_not be_valid
    end

  end

  describe "email validations" do

    it "should require an email" do
      no_email_user = User.new (@attr.merge(:email => ""))
      no_email_user.should_not be_valid
    end

    it "should reject duplicate emails" do
      User.create!(@attr)
      user2 = User.new(@attr.merge(:username => "example2"))
      user2.should_not be_valid
    end

    it "should accept valid email addresses" do
      addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
      addresses.each do |address|
        valid_email_user = User.new(@attr.merge(:email => address))
        valid_email_user.should be_valid
      end
    end

    it "should reject invalid email addresses" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
      addresses.each do |address|
        invalid_email_user = User.new(@attr.merge(:email => address))
        invalid_email_user.should_not be_valid
      end
    end

    it "should reject email address idential up to case" do
      User.create!(@attr)
      user = User.new(@attr.merge(:email => @attr[:email].capitalize))
      user.should_not be_valid
    end

  end

  describe "password validations" do

    it "should require a password or a password confirmation" do
      user = User.new(@attr.merge(:password => "", :password_confirmation => ""))
      user.should_not be_valid
    end

    it "should require a password" do
      user = User.new(@attr.merge(:password => ""))
      user.should_not be_valid
    end

    it "should require a password confirmation" do
      user = User.new(@attr.merge(:password_confirmation => ""))
      user.should_not be_valid
    end

    it "should require a matching password confirmation" do
      user = User.new(@attr.merge(:password_confirmation => "invalid"))
      user.should_not be_valid
    end

    it "should reject passwords that are too short" do
      password = "a" * 5
      user = User.new(@attr.merge(:password => password, :password_confirmation => password))
      user.should_not be_valid
    end

    it "should reject passwords that are too long" do
      password = "a" * 41
      user = User.new(@attr.merge(:password => password, :password_confirmation => password))
      user.should_not be_valid
    end

    it "should require case sensative password confirmations" do
      password = "password"
      user = User.new(@attr.merge(:password => password,
      :password_confirmation => password.capitalize))
      user.should_not be_valid
    end

  end

end
</code>```

They fails with the errors:

```<code>Running: spec/models/user_spec.rb
FFFFFFFFFFFFFFFFFFFFFFF

Failures:

  1) User username validations should allow usernames with numbers
     Failure/Error: User.create!(@attr.merge(:username => 'example123'))
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001017c1850>
     # ./spec/models/user_spec.rb:17:in `block (3 levels) in <top (required)>'

  2) User username validations should allow hyphens
     Failure/Error: User.create!(@attr.merge(:username => 'example-two'))
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100d50f10>
     # ./spec/models/user_spec.rb:21:in `block (3 levels) in <top (required)>'

  3) User username validations should require a username
     Failure/Error: no_username_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100cc9da8>
     # ./spec/models/user_spec.rb:26:in `block (3 levels) in <top (required)>'

  4) User username validations should reject usernames that are too long
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100c333f8>
     # ./spec/models/user_spec.rb:31:in `block (3 levels) in <top (required)>'

  5) User username validations should reject username that are too short
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100aafbd0>
     # ./spec/models/user_spec.rb:36:in `block (3 levels) in <top (required)>'

  6) User username validations should reject username with uppercase letters
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001032e2f58>
     # ./spec/models/user_spec.rb:41:in `block (3 levels) in <top (required)>'

  7) User username validations should reject duplicate usernames
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000103167f70>
     # ./spec/models/user_spec.rb:45:in `block (3 levels) in <top (required)>'

  8) User username validations should reject usernames with whitespace characters
     Failure/Error: u1.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001032dbb40>
     # ./spec/models/user_spec.rb:57:in `block (3 levels) in <top (required)>'

  9) User username validations should reject usernames with special characters
     Failure/Error: u1.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010328d0d0>
     # ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'

  10) User username validations should reject usernames that begin with a hypen
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010323f3d0>
     # ./spec/models/user_spec.rb:80:in `block (3 levels) in <top (required)>'

  11) User username validations should reject usernames that end with a hypen
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000103212a10>
     # ./spec/models/user_spec.rb:85:in `block (3 levels) in <top (required)>'

  12) User email validations should require an email
     Failure/Error: no_email_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031ed4e0>
     # ./spec/models/user_spec.rb:96:in `block (3 levels) in <top (required)>'

  13) User email validations should reject duplicate emails
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031bf630>
     # ./spec/models/user_spec.rb:100:in `block (3 levels) in <top (required)>'

  14) User email validations should accept valid email addresses
     Failure/Error: valid_email_user.should be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031991b0>
     # ./spec/models/user_spec.rb:109:in `block (4 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:107:in `each'
     # ./spec/models/user_spec.rb:107:in `block (3 levels) in <top (required)>'

  15) User email validations should reject invalid email addresses
     Failure/Error: invalid_email_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010315d1b0>
     # ./spec/models/user_spec.rb:117:in `block (4 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:115:in `each'
     # ./spec/models/user_spec.rb:115:in `block (3 levels) in <top (required)>'

  16) User email validations should reject email address idential up to case
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010310a898>
     # ./spec/models/user_spec.rb:122:in `block (3 levels) in <top (required)>'

  17) User password validations should require a password or a password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010172f2c0>
     # ./spec/models/user_spec.rb:135:in `block (3 levels) in <top (required)>'

  18) User password validations should require a password
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001015f5b98>
     # ./spec/models/user_spec.rb:140:in `block (3 levels) in <top (required)>'

  19) User password validations should require a password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010155f120>
     # ./spec/models/user_spec.rb:145:in `block (3 levels) in <top (required)>'

  20) User password validations should require a matching password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000101310298>
     # ./spec/models/user_spec.rb:150:in `block (3 levels) in <top (required)>'

  21) User password validations should reject passwords that are too short
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100eecbf8>
     # ./spec/models/user_spec.rb:156:in `block (3 levels) in <top (required)>'

  22) User password validations should reject passwords that are too long
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100d7f400>
     # ./spec/models/user_spec.rb:162:in `block (3 levels) in <top (required)>'

  23) User password validations should require case sensative password confirmations
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100cf0b38>
     # ./spec/models/user_spec.rb:169:in `block (3 levels) in <top (required)>'

Finished in 0.19613 seconds
23 examples, 23 failures
</code>```

It seems like the problem is occurring with the valid? method, but I don't understand why considering :username_or_email doesn't have any validations in place.  Why are these errors occurring and how can I fix them?

Thanks.

答: I would guess that because username_or_email is not an attribute in the ActiveRecord sense, it should not be mentioned with attr_accessible.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've added a :username_or_email property to my User model as such:

class User < ActiveRecord::Base

  #authlogic
  acts_as_authentic do |c|
    c.login_field = :username_or_email
  end

  #virtual field for allowing a user to login with their username or email
  attr_accessor :username_or_email

  attr_accessible :username, :email, :password, :password_confirmation, :username_or_email

  validates :username, :presence => true,
                       :length => { :within => 3..20 },
                       :uniqueness => true,
                       :format => { :with => /\A[a-z0-9][a-z0-9\-]+[a-z0-9]\z/ }

  validates :email, :presence => true,
                    :format => { :with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i },
                    :uniqueness => { :case_sensative => false }

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }

  def self.find_by_username_or_email(username_or_email)
    User.find_by_username(username_or_email) || User.find_by_email(username_or_email)
  end

end

The purpose of this is to create a virtual field which allows the user to log in with either their username or email using Authlogic.  This works perfectly when I run the server, doing exactly what I want it to.  However, it causes all of the following specs to fail:

require 'spec_helper'

describe User do

  before(:each) do
    @attr = {
      :username => "example",
      :email => "user@example.com",
      :password => "password",
      :password_confirmation => "password"
    }
  end

  describe "username validations" do

    it "should allow usernames with numbers" do
      User.create!(@attr.merge(:username => 'example123'))
    end

    it "should allow hyphens" do
      User.create!(@attr.merge(:username => 'example-two'))
    end

    it "should require a username" do
      no_username_user = User.new (@attr.merge(:username => ""))
      no_username_user.should_not be_valid
    end

    it "should reject usernames that are too long" do
      user = User.new(@attr.merge(:username => ("a" * 21)))
      user.should_not be_valid
    end

    it "should reject username that are too short" do
      user = User.new(@attr.merge(:username => ("a" * 2)))
      user.should_not be_valid
    end

    it "should reject username with uppercase letters" do
      user = User.new(@attr.merge(:username => "Example"))
      user.should_not be_valid
    end

    it "should reject duplicate usernames" do
      User.create!(@attr)
      user = User.new(@attr.merge(:email => "user2@example.com"))
      user.should_not be_valid
    end

    it "should reject usernames with whitespace characters" do
      u1 = User.new(@attr.merge(:username => "exa mple"))
      u2 = User.new(@attr.merge(:username => " example"))
      u3 = User.new(@attr.merge(:username => "example "))
      u4 = User.new(@attr.merge(:username => "exa\tmple"))
      u5 = User.new(@attr.merge(:username => "exa\nmple"))

      u1.should_not be_valid
      u2.should_not be_valid
      u3.should_not be_valid
      u4.should_not be_valid
      u5.should_not be_valid
    end

    it "should reject usernames with special characters" do
      u1 = User.new(@attr.merge(:username => 'ex&mple'))
      u2 = User.new(@attr.merge(:username => 'ex*mple'))
      u3 = User.new(@attr.merge(:username => 'ex"mple'))
      u4 = User.new(@attr.merge(:username => 'ex^mple'))
      u5 = User.new(@attr.merge(:username => 'ex;mple'))

      u1.should_not be_valid
      u2.should_not be_valid
      u3.should_not be_valid
      u4.should_not be_valid
      u5.should_not be_valid
    end

    it "should reject usernames that begin with a hypen" do
      user = User.new(@attr.merge(:username => '-example'))
      user.should_not be_valid
    end

    it "should reject usernames that end with a hypen" do
      user = User.new(@attr.merge(:username => 'example-'))
      user.should_not be_valid
    end

  end

  describe "email validations" do

    it "should require an email" do
      no_email_user = User.new (@attr.merge(:email => ""))
      no_email_user.should_not be_valid
    end

    it "should reject duplicate emails" do
      User.create!(@attr)
      user2 = User.new(@attr.merge(:username => "example2"))
      user2.should_not be_valid
    end

    it "should accept valid email addresses" do
      addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
      addresses.each do |address|
        valid_email_user = User.new(@attr.merge(:email => address))
        valid_email_user.should be_valid
      end
    end

    it "should reject invalid email addresses" do
      addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
      addresses.each do |address|
        invalid_email_user = User.new(@attr.merge(:email => address))
        invalid_email_user.should_not be_valid
      end
    end

    it "should reject email address idential up to case" do
      User.create!(@attr)
      user = User.new(@attr.merge(:email => @attr[:email].capitalize))
      user.should_not be_valid
    end

  end

  describe "password validations" do

    it "should require a password or a password confirmation" do
      user = User.new(@attr.merge(:password => "", :password_confirmation => ""))
      user.should_not be_valid
    end

    it "should require a password" do
      user = User.new(@attr.merge(:password => ""))
      user.should_not be_valid
    end

    it "should require a password confirmation" do
      user = User.new(@attr.merge(:password_confirmation => ""))
      user.should_not be_valid
    end

    it "should require a matching password confirmation" do
      user = User.new(@attr.merge(:password_confirmation => "invalid"))
      user.should_not be_valid
    end

    it "should reject passwords that are too short" do
      password = "a" * 5
      user = User.new(@attr.merge(:password => password, :password_confirmation => password))
      user.should_not be_valid
    end

    it "should reject passwords that are too long" do
      password = "a" * 41
      user = User.new(@attr.merge(:password => password, :password_confirmation => password))
      user.should_not be_valid
    end

    it "should require case sensative password confirmations" do
      password = "password"
      user = User.new(@attr.merge(:password => password,
      :password_confirmation => password.capitalize))
      user.should_not be_valid
    end

  end

end

They fails with the errors:

Running: spec/models/user_spec.rb
FFFFFFFFFFFFFFFFFFFFFFF

Failures:

  1) User username validations should allow usernames with numbers
     Failure/Error: User.create!(@attr.merge(:username => 'example123'))
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001017c1850>
     # ./spec/models/user_spec.rb:17:in `block (3 levels) in <top (required)>'

  2) User username validations should allow hyphens
     Failure/Error: User.create!(@attr.merge(:username => 'example-two'))
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100d50f10>
     # ./spec/models/user_spec.rb:21:in `block (3 levels) in <top (required)>'

  3) User username validations should require a username
     Failure/Error: no_username_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100cc9da8>
     # ./spec/models/user_spec.rb:26:in `block (3 levels) in <top (required)>'

  4) User username validations should reject usernames that are too long
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100c333f8>
     # ./spec/models/user_spec.rb:31:in `block (3 levels) in <top (required)>'

  5) User username validations should reject username that are too short
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100aafbd0>
     # ./spec/models/user_spec.rb:36:in `block (3 levels) in <top (required)>'

  6) User username validations should reject username with uppercase letters
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001032e2f58>
     # ./spec/models/user_spec.rb:41:in `block (3 levels) in <top (required)>'

  7) User username validations should reject duplicate usernames
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000103167f70>
     # ./spec/models/user_spec.rb:45:in `block (3 levels) in <top (required)>'

  8) User username validations should reject usernames with whitespace characters
     Failure/Error: u1.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001032dbb40>
     # ./spec/models/user_spec.rb:57:in `block (3 levels) in <top (required)>'

  9) User username validations should reject usernames with special characters
     Failure/Error: u1.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010328d0d0>
     # ./spec/models/user_spec.rb:71:in `block (3 levels) in <top (required)>'

  10) User username validations should reject usernames that begin with a hypen
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010323f3d0>
     # ./spec/models/user_spec.rb:80:in `block (3 levels) in <top (required)>'

  11) User username validations should reject usernames that end with a hypen
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000103212a10>
     # ./spec/models/user_spec.rb:85:in `block (3 levels) in <top (required)>'

  12) User email validations should require an email
     Failure/Error: no_email_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031ed4e0>
     # ./spec/models/user_spec.rb:96:in `block (3 levels) in <top (required)>'

  13) User email validations should reject duplicate emails
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031bf630>
     # ./spec/models/user_spec.rb:100:in `block (3 levels) in <top (required)>'

  14) User email validations should accept valid email addresses
     Failure/Error: valid_email_user.should be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001031991b0>
     # ./spec/models/user_spec.rb:109:in `block (4 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:107:in `each'
     # ./spec/models/user_spec.rb:107:in `block (3 levels) in <top (required)>'

  15) User email validations should reject invalid email addresses
     Failure/Error: invalid_email_user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010315d1b0>
     # ./spec/models/user_spec.rb:117:in `block (4 levels) in <top (required)>'
     # ./spec/models/user_spec.rb:115:in `each'
     # ./spec/models/user_spec.rb:115:in `block (3 levels) in <top (required)>'

  16) User email validations should reject email address idential up to case
     Failure/Error: User.create!(@attr)
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010310a898>
     # ./spec/models/user_spec.rb:122:in `block (3 levels) in <top (required)>'

  17) User password validations should require a password or a password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010172f2c0>
     # ./spec/models/user_spec.rb:135:in `block (3 levels) in <top (required)>'

  18) User password validations should require a password
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x000001015f5b98>
     # ./spec/models/user_spec.rb:140:in `block (3 levels) in <top (required)>'

  19) User password validations should require a password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x0000010155f120>
     # ./spec/models/user_spec.rb:145:in `block (3 levels) in <top (required)>'

  20) User password validations should require a matching password confirmation
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000101310298>
     # ./spec/models/user_spec.rb:150:in `block (3 levels) in <top (required)>'

  21) User password validations should reject passwords that are too short
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100eecbf8>
     # ./spec/models/user_spec.rb:156:in `block (3 levels) in <top (required)>'

  22) User password validations should reject passwords that are too long
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100d7f400>
     # ./spec/models/user_spec.rb:162:in `block (3 levels) in <top (required)>'

  23) User password validations should require case sensative password confirmations
     Failure/Error: user.should_not be_valid
     NoMethodError:
       undefined method `username_or_email_changed?' for #<User:0x00000100cf0b38>
     # ./spec/models/user_spec.rb:169:in `block (3 levels) in <top (required)>'

Finished in 0.19613 seconds
23 examples, 23 failures

It seems like the problem is occurring with the valid? method, but I don't understand why considering :username_or_email doesn't have any validations in place.  Why are these errors occurring and how can I fix them?

Thanks.


问:
Create columns with the frequency of a code per ID
I have to perform a query where I can count the number of distinct codes per Id.

```<code>   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C
</code>```

The output should be something like:

```<code>   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0
</code>```

Can you give me some advise on this?

Body:
I have to perform a query where I can count the number of distinct codes per Id.

   |Id  | Code
   ------------
   | 1  |   C
   | 1  |   I
   | 2  |   I
   | 2  |   C
   | 2  |   D
   | 2  |   D
   | 3  |   C
   | 3  |   I
   | 3  |   D
   | 4  |   I
   | 4  |   C
   | 4  |   C

The output should be something like:

   |Id  | Count | #Code C | #Code I | #Code D
   -------------------------------------------
   | 1  | 2     |    1    |    1    |   0
   | 2  | 3     |    1    |    0    |   2
   | 3  | 3     |    1    |    1    |   1
   | 4  | 2     |    2    |    1    |   0

Can you give me some advise on this?

Body:
You can try the below SQL code in SQL Server.

DECLARE @table Table(Id tinyint,  Code CHAR(1))

INSERT INTO @table
values
    (1     ,'C'),
    (1     ,'I'),
    (2     ,'I'),
    (2     ,'C'),
    (2     ,'D'),
    (2     ,'D'),
    (3     ,'C'),
    (3     ,'I'),
    (3     ,'D'),
    (4     ,'I'),
    (4     ,'C'),
    (4     ,'C');

SELECT Id, c+d+i as [Count], [c] as [#Code C],[d] as [#Code D],[i] as [#Code I]
FROM @table
PIVOT
(
Count(code) FOR code IN ([c],[d],[i])
) as pvt

+----+-------+---------+---------+---------+
| Id | Count | #Code C | #Code D | #Code I |
+----+-------+---------+---------+---------+
|  1 |     2 |       1 |       0 |       1 |
|  2 |     4 |       1 |       2 |       1 |
|  3 |     3 |       1 |       1 |       1 |
|  4 |     3 |       2 |       0 |       1 |
+----+-------+---------+---------+---------+


问:
State Pattern in c#
I got into this book called "game programming patterns" and I started implementing some of its patterns in C#. Right now, I'm implementing the State Pattern which is described by the UML Class Diagram below.

This is my main program. I use 2 different threads in order to not stop the game loop with the keyboard user input. In the hero, class the HandleInput method calls the HandleInput method of the current state stored in the field state.

```<code>class Program
{

    private static string key;
    private static Thread t;
    private static Hero hero1;

    public delegate void PressDelegate();
    public static event PressDelegate OnPress;
    static void Main(string[] args)
    {
        // Creating Hero
        hero1 = new Hero("zelda");

        // Subscribing to KeyboardInput Event
        OnPress += KeyboardInputHandler;

        // Game Loop
        t = new Thread(new ThreadStart(KeyboardInput));
        t.Start();
    }
    private static void KeyboardInput()
    {
        while (true)
        {
            key = Console.ReadLine();
            OnPress();
        }

    }
    private static void KeyboardInputHandler()
    {
        hero1.HandleInput(key);
    }
}
</code>```

}

My goal is to when user press Space, the hero changes his states to JumpingState assuming that its default state is the idlestate and after 1-second changes back to idle (simulating the gravity effect). The problem is I've tried some solutions like having the timer inside the IdleState but then I'll have to do that for every state that transition to jumping state (for example a ducking state). I've also tried to do that on the hero class with an if statement :( if state is JumpingState then start the timer and when finish call SetState(IdleState) something like that) but I feel that this breaks the fact that the SetState method is only called inside the state and not on the hero.

I really appreciate your help :)

答:
Usually a game is run in a game-loop. A very simple one could look like this:

Read input

Process input (move character, advance enemies etc)

Draw the result

This loop would typically at a more or less fixed rate. this is in contrast to most windows programs that only run when the user has provided some kind of input, or the program has some timer that has triggered.

So the active state would receive an update call every frame, and it has then a chance to decide what to do. The state would typically check the game-state and user input, from this it can then decide what to do.

Instead of reading the input in a separate thread you can use Console.KeyAvailable to check if a key is available, and if so, ReadKey should not block.

The way I'm used to program state machines is that the current state is called with some input parameters, and returns the next state to use. There are a bunch of details that can be taken into consideration:

Should you process all input? only the last input each frame? Only if the key is pressed when the frame starts?

Should it be possible to switch states more than once per frame? I.e. "Jumping" may transition to "Idle", but if the user is holding the shift-key then it could immediately transition to "crouching".

It is common to separate "state" and "transition". This helps making the state machine more abstract. I.e. Instead of having hard coding that the hero should jump on space in each state, you can have a OnKeyTransition that takes a input key and a target state as input. You can then add this transition to all states that should support jumping.

There can be many different kinds of state machines in a game. One high level might be if the player is driving a car, on foot, piloting an airplane etc. A lower level state machine might handle animations. A third kind could be used for AI. All of these have different kinds of requirements, so need to be treated differently.

This would be an example of a very simple state machine. I'm not sure that it is exactly what you are looking for, but I hope it will provide some inspiration at least.

```<code>public class State
{
    public virtual State Update(ConsoleKey? input, TimeSpan deltaTime) => this;
}

public class IdleState : State
{
    public override State Update(ConsoleKey? input, TimeSpan deltaTime)
    {
        if (input == ConsoleKey.Spacebar)
        {
            return new JumpingState();
        }
        return base.Update(input, deltaTime);
    }
}

public class JumpingState : State
{
    private TimeSpan elapsed = TimeSpan.Zero;

    public override State Update(ConsoleKey? input, TimeSpan deltaTime)
    {
        elapsed += deltaTime;
        if (elapsed > TimeSpan.FromSeconds(1))
        {
            return new IdleState();
        }
        return base.Update(input, deltaTime);
    }
}

public class Game
{
    static void Main(string[] args)
    {
        var game = new Game();
        game.StartGame();

    }

    State currentState = new IdleState();
    private TimeSpan frameRate = TimeSpan.FromMilliseconds(30);

    public void StartGame()
    {
        Console.WriteLine("Game Started");
        while (true)
        {

            var input = GetLastKeypress()?.Key;
            if (input == ConsoleKey.Escape)
            {
                Console.WriteLine("Game Over");
                return;
            }

            // Update the state
            var nextState = currentState.Update(input, frameRate);
            if (nextState != currentState)
            {
                currentState = nextState;
                Console.WriteLine(currentState.GetType().Name);
            }
            Thread.Sleep(frameRate);
        }
    }

    private ConsoleKeyInfo? GetLastKeypress()
    {
        ConsoleKeyInfo? info = null;
        while (Console.KeyAvailable)
        {
            info = Console.ReadKey();
        }
        return info;
    }
}
</code>```

Title: State Pattern in c#

Body:
I got into this book called "game programming patterns" and I started implementing some of its patterns in C#. Right now, I'm implementing the State Pattern which is described by the UML Class Diagram below.

This is my main program. I use 2 different threads in order to not stop the game loop with the keyboard user input. In the hero, class the HandleInput method calls the HandleInput method of the current state stored in the field state.

class Program
{

    private static string key;
    private static Thread t;
    private static Hero hero1;

    public delegate void PressDelegate();
    public static event PressDelegate OnPress;
    static void Main(string[] args)
    {
        // Creating Hero
        hero1 = new Hero("zelda");

        // Subscribing to KeyboardInput Event
        OnPress += KeyboardInputHandler;

        // Game Loop
        t = new Thread(new ThreadStart(KeyboardInput));
        t.Start();
    }
    private static void KeyboardInput()
    {
        while (true)
        {
            key = Console.ReadLine();
            OnPress();
        }

    }
    private static void KeyboardInputHandler()
    {
        hero1.HandleInput(key);
    }
}

}

My goal is to when user press Space, the hero changes his states to JumpingState assuming that its default state is the idlestate and after 1-second changes back to idle (simulating the gravity effect). The problem is I've tried some solutions like having the timer inside the IdleState but then I'll have to do that for every state that transition to jumping state (for example a ducking state). I've also tried to do that on the hero class with an if statement :( if state is JumpingState then start the timer and when finish call SetState(IdleState) something like that) but I feel that this breaks the fact that the SetState method is only called inside the state and not on the hero.

I really appreciate your help :)

Body:
Usually a game is run in a game-loop. A very simple one could look like this:

Read input

Process input (move character, advance enemies etc)

Draw the result

This loop would typically at a more or less fixed rate. this is in contrast to most windows programs that only run when the user has provided some kind of input, or the program has some timer that has triggered.

So the active state would receive an update call every frame, and it has then a chance to decide what to do. The state would typically check the game-state and user input, from this it can then decide what to do.

Instead of reading the input in a separate thread you can use Console.KeyAvailable to check if a key is available, and if so, ReadKey should not block.

The way I'm used to program state machines is that the current state is called with some input parameters, and returns the next state to use. There are a bunch of details that can be taken into consideration:

Should you process all input? only the last input each frame? Only if the key is pressed when the frame starts?

Should it be possible to switch states more than once per frame? I.e. "Jumping" may transition to "Idle", but if the user is holding the shift-key then it could immediately transition to "crouching".

It is common to separate "state" and "transition". This helps making the state machine more abstract. I.e. Instead of having hard coding that the hero should jump on space in each state, you can have a OnKeyTransition that takes a input key and a target state as input. You can then add this transition to all states that should support jumping.

There can be many different kinds of state machines in a game. One high level might be if the player is driving a car, on foot, piloting an airplane etc. A lower level state machine might handle animations. A third kind could be used for AI. All of these have different kinds of requirements, so need to be treated differently.

This would be an example of a very simple state machine. I'm not sure that it is exactly what you are looking for, but I hope it will provide some inspiration at least.

public class State
{
    public virtual State Update(ConsoleKey? input, TimeSpan deltaTime) => this;
}

public class IdleState : State
{
    public override State Update(ConsoleKey? input, TimeSpan deltaTime)
    {
        if (input == ConsoleKey.Spacebar)
        {
            return new JumpingState();
        }
        return base.Update(input, deltaTime);
    }
}

public class JumpingState : State
{
    private TimeSpan elapsed = TimeSpan.Zero;

    public override State Update(ConsoleKey? input, TimeSpan deltaTime)
    {
        elapsed += deltaTime;
        if (elapsed > TimeSpan.FromSeconds(1))
        {
            return new IdleState();
        }
        return base.Update(input, deltaTime);
    }
}

public class Game
{
    static void Main(string[] args)
    {
        var game = new Game();
        game.StartGame();

    }

    State currentState = new IdleState();
    private TimeSpan frameRate = TimeSpan.FromMilliseconds(30);

    public void StartGame()
    {
        Console.WriteLine("Game Started");
        while (true)
        {

            var input = GetLastKeypress()?.Key;
            if (input == ConsoleKey.Escape)
            {
                Console.WriteLine("Game Over");
                return;
            }

            // Update the state
            var nextState = currentState.Update(input, frameRate);
            if (nextState != currentState)
            {
                currentState = nextState;
                Console.WriteLine(currentState.GetType().Name);
            }
            Thread.Sleep(frameRate);
        }
    }

    private ConsoleKeyInfo? GetLastKeypress()
    {
        ConsoleKeyInfo? info = null;
        while (Console.KeyAvailable)
        {
            info = Console.ReadKey();
        }
        return info;
    }
}


问:
How to convert nested array of object into arraylist in javascript?
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

```<code>{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}
</code>```

and i want change convert to array like this :

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }
</code>```

i try using map to convert on result like this :

```<code>result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);
</code>```

but why i only get result data of one array not four data ? help me please, thankyou..

```<code>{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}
</code>```

答:
Would that work for you?

const src = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]},

result = {
  ...src,
  data: src.data[0].pasien_docs.map(Object.values)
}

console.log(result)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height:100%;}</code>```

Body:
i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :

{
    "status": true,
    "message": "",
    "data": [{
            "pasien_docs": [{
                    "ecg": null,
                    "date": "2020-01-21T05:22:01.901Z"
                }, {
                    "ecg": 1.03,
                    "date": "2020-01-21T05:22:02.979Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:04.053Z"
                }, {
                    "ecg": 1.04,
                    "date": "2020-01-21T05:22:05.126Z"
                },
            ]
        }
    ]
}

and i want change convert to array like this :

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ],
        [
            "2020-01-21T05:22:01.901Z",
            1, 03
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
        [
            "2020-01-21T05:22:01.901Z",
            1.04
        ]
    ]
 }

i try using map to convert on result like this :

result = result.map((u, i) => [
            u.pasien_docs[i].date,
            u.pasien_docs[i].ecg,
        ]);

but why i only get result data of one array not four data ? help me please, thankyou..

{
    "status": true,
    "message": "",
    "data": [
        [
            "2020-01-21T05:22:01.901Z",
            null
        ]
    ]
}

Body:
Would that work for you?

const src = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]},

result = {
  ...src,
  data: src.data[0].pasien_docs.map(Object.values)
}

console.log(result)

.as-console-wrapper{min-height:100%;}


问:
Jquery, search and show a hidden div
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

    <link rel="stylesheet" href="/css/style.css">

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

 ```

im pretty new to this community. thanks for any help!

答:
You could use display: none; on .foodcard in your CSS file , so that the elements are hidden even before the page is loaded

Then you can use the .show() or .hide() jquery functions in your JS file to display/hide the elements

Title: Jquery, search and show a hidden div

Body:
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });

.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

    <link rel="stylesheet" href="/css/style.css">

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

im pretty new to this community. thanks for any help!