答:
First of all, fix your indentation (if it is not a problem only in your example). Second, you need to put easy, medium, and hard in either single ' or double " quotes:

```<code>difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty=="easy":
    print("You have chosen the easy mode, your test will now begin")
    print("")

elif difficulty=="medium":
    print("You have chosen the medium mode, your test will now begin")

else:
    print("You have chosen the hard mode or tried to be funny, your test
    will now begin")
</code>```

If you don't put them in quotes, then you aren't comparing difficulty to the word easy, but rather to the variable called easy. This of course causes an error, since no such variable exists. The quotes however tell python to interpret easy as a string.

Title: Trying to change a variable in use to what the user inputs

Body:
First of all, fix your indentation (if it is not a problem only in your example). Second, you need to put easy, medium, and hard in either single ' or double " quotes:

difficulty=input("What difficulty do you wish to choose, easy,medium or hard?")
if difficulty=="easy":
    print("You have chosen the easy mode, your test will now begin")
    print("")

elif difficulty=="medium":
    print("You have chosen the medium mode, your test will now begin")

else:
    print("You have chosen the hard mode or tried to be funny, your test
    will now begin")

If you don't put them in quotes, then you aren't comparing difficulty to the word easy, but rather to the variable called easy. This of course causes an error, since no such variable exists. The quotes however tell python to interpret easy as a string.


来源: stackexchange

问:
Threaded DelayedJob workers dry up ActiveRecord connection pool
I want to run jobs scheduling (with rufus_scheduler) and processing (with delayed_job, DJ) with the ActiveRecord backend from the same jRuby process, but in different threads.

This works fine when just one DJ worker is in use, but when I set up multiple queues (with one worker per queue), the scheduler terminates with the following message:

```<code>rufus-scheduler intercepted an error:
   job:
     Rufus::Scheduler::CronJob "*/10 * * * * *" {}
   error:
     ActiveRecord::ConnectionTimeoutError
     could not obtain a connection from the pool within 5.000 seconds (waited 5.000 seconds); all pooled connections were in use
</code>```

This leads me to believe that the workers do not free the database connections upon termination of the job, but I have yet to find the relevant code. The amount of connections in the pool is configured to be 50.

The script is supposed to keep running until it receives SIGTERM and should have access to the Rails environment. A MWE is given below:

```<code>require './config/environment'

module Jobs
  class ExampleJob < ActiveJob::Base
    queue_as :system

    def perform
      puts 'Performing ExampleJob'
    end
  end
end

QUEUES = %i(system database).freeze
NUM_QUEUES = QUEUES.size

workers = []
worker_threads = []

NUM_QUEUES.times do |queue_number|
  worker = Delayed::Worker.new(quiet: false)
  worker.name = queue_number
  workers.append(worker)
  worker_threads.append(Thread.new do
    worker.start
  end)
end

scheduler = Rufus::Scheduler.new

scheduler.cron '*/10 * * * * *' do
  puts 'Scheduled ExampleJob'
  Jobs::ExampleJob.perform_later
end

Signal.trap('TERM') do
  scheduler.shutdown
  workers.each do |worker|
    worker.stop
  end
end

scheduler.join
worker_threads.each do |thread|
  thread.join
end
</code>```

Is there a way to get this to run properly?

答:
How about

```<code>module Jobs
  class ExampleJob < ActiveJob::Base
    queue_as :system

    def perform
      puts 'Performing ExampleJob'
    end

    after_perform do
      ActiveRecord::Base.clear_active_connections!
    end
  end
end
</code>```

?

ContentLicense: CC BY-SA 3.0

Body:
I want to run jobs scheduling (with rufus_scheduler) and processing (with delayed_job, DJ) with the ActiveRecord backend from the same jRuby process, but in different threads.

This works fine when just one DJ worker is in use, but when I set up multiple queues (with one worker per queue), the scheduler terminates with the following message:

rufus-scheduler intercepted an error:
   job:
     Rufus::Scheduler::CronJob "*/10 * * * * *" {}
   error:
     ActiveRecord::ConnectionTimeoutError
     could not obtain a connection from the pool within 5.000 seconds (waited 5.000 seconds); all pooled connections were in use

This leads me to believe that the workers do not free the database connections upon termination of the job, but I have yet to find the relevant code. The amount of connections in the pool is configured to be 50.

The script is supposed to keep running until it receives SIGTERM and should have access to the Rails environment. A MWE is given below:

require './config/environment'

module Jobs
  class ExampleJob < ActiveJob::Base
    queue_as :system

    def perform
      puts 'Performing ExampleJob'
    end
  end
end

QUEUES = %i(system database).freeze
NUM_QUEUES = QUEUES.size

workers = []
worker_threads = []

NUM_QUEUES.times do |queue_number|
  worker = Delayed::Worker.new(quiet: false)
  worker.name = queue_number
  workers.append(worker)
  worker_threads.append(Thread.new do
    worker.start
  end)
end

scheduler = Rufus::Scheduler.new

scheduler.cron '*/10 * * * * *' do
  puts 'Scheduled ExampleJob'
  Jobs::ExampleJob.perform_later
end

Signal.trap('TERM') do
  scheduler.shutdown
  workers.each do |worker|
    worker.stop
  end
end

scheduler.join
worker_threads.each do |thread|
  thread.join
end

Is there a way to get this to run properly?

Body:
How about

module Jobs
  class ExampleJob < ActiveJob::Base
    queue_as :system

    def perform
      puts 'Performing ExampleJob'
    end

    after_perform do
      ActiveRecord::Base.clear_active_connections!
    end
  end
end

?


问:
Yellow warning triangle in Xcode 9's Create Bot.. window
I'm trying to set up continuous integration (CI) in Xcode 9 with it's new built-in Xcode Server functionality. (MacBook Pro, macOS High Sierra)

I've been following various tutorials, such as Tutorial: Continuous Integration with Xcode 9 and FastLane, Xcode Server and Continuous Integration Guide: Configure Bots to Perform Continuous Integration, and a few others.

Everything seems to work fine, till I get to the Product -> Create Bot... step. The window opens with a yellow triangle/exclamation mark warning symbol to the right of the Server dropdown:

The Previous and Next buttons are disabled. Nothing happens if I click on the warning triangle, and there are no other related messages I can see in Xcode or the macOS console.

I performed the same setup on another MacBook Pro running High Sierra and the same version of Xcode 9. There was no triangle on that one, and I was able to select Next and continue the process.

Update: The triangle is present for any project I create. And, I've tried closing/restarting both Xcode and the MacBook Pro.

I've searched repeatedly for things like create bot yellow triangle, create bot warning symbol, xcode 9 continuous integration warning symbol, etc, but found nothing relevant.

Has anybody seen this, and what does it mean/how do I fix it???

答:
Ah, the actual problem was that, in Accounts, I used the integration user I had set up. That was incorrect. I needed to put myself or another registered user into the Account section.

Once I added my own user's Name and Password into the Accounts/Xcode Server section, I was able to successfully create a bot.


问:
what is the default access modifier for controls created on .aspx page. Private or something else?
What is the default access modifier for controls created on .aspx page. Private or something else?</p>

答:
protected

If you open the MyPage.aspx.designer.cs (or MyPage.aspx.designer.vb) you can see the declarations for the controls.

ContentLicense: CC BY-SA 2.5


问:
Delphi - Extending Indy components in push method
I need to build mail server using IMAP4. It should "push" mails to client when is connected. I use Delphi XE6 and Indy 10.6.0.5122 that doesn't support IMAP IDLE. Is there any possibility to equip my Indy components in "push" method? If not, then can i substitute "push" for periodic asking server if new mails exist, or it's bad idea?
Thanks for every helpful answer!</p>

答:
Like you said, Indy does not currently support IDLE, but you should be able to implement it manually with some extra work.

On the client side, call TIdIMAP4.IOHandler.WriteLn() to send an IDLE command and IOHandler.ReadLn to read its reply (I'm not sure if TIdIMAP4.SendCmd() would work in this situation), then start a timer/thread to read inbound data until you turn IDLE off.

On the server side, add an entry for IDLE in the TIdIMAP4Server.CommandHandlers collection and assign an OnCommand handler to it to send a reply, then you can push entries to the client socket when needed until the client turns off IDLE (with a DONE command or closing the socket).

I don't have a code example.  Read RFC 2177 for the full detail of how IDLE works.


问:
Making a project in php and i have to use Steam login api
I want to practice on Steam login API and i don't have domain so can i use my local host XAMP/WAMP if yes then how to get an API key for it ?

Help will be appreciated

答:
When Steam asks for a domain to obtain an API key, they don't actually verify that requests come from that domain. It's just for their records, likely so they can trace API abuse back to keys.

As long as it looks like a domain to Steam, it ought to work. Just don't use anything legitimate or try to impersonate anyone, as I can't guarantee there won't be repercussions.

You've probably found the page, but if you haven't, you can get an API key here.


问:
Trying to debug mystery sinewave using AKMIDISampler in Audiokit
Following on from a previous issue, I stopped using AKSampler to move to the functionality used in AKMIDISampler. Got my loops working again (with help from this Google Groups post), but I have a sinewave playing (which happens when the MIDISampler can't find it's source file).

It's not an issue with the source files I'm targeting because they all play OK. The sinewave is coming from somewhere else in the process, but I can't see where...

Please help 8•)

(Simplified and edited code to show only relevant details - please get in touch for any clarification)

```<code>var MIDISamplePlayer = AKMIDISampler()
var sequencer: AKSequencer?
var mixer: AKMixer!

// initialise the mixer
mixer = AKMixer()

do  {
        audiofile = try AKAudioFile(readFileName: SoundFilename as! String,
        baseDir: .resources)
    } catch let error as NSError {
        print("There's an error: \(error)")
    }

do {
       try sprite.MIDISamplePlayer.loadAudioFile(audiofile)
    } catch let error as NSError {
       print("There's an error: \(error)")
    }

sprite.tracker = AKAmplitudeTracker(sprite.MIDISamplePlayer)
mixer.connect(to:sprite.tracker, bus: mixer.nextInput.bus)

sequencer = AKSequencer(filename: POPmidi)
sequencer?.enableLooping()

let midi = AKMIDI()

for i in 0..<popCount {
    gPOPs[i].MIDISamplePlayer.enableMIDI(midi.client, name: "MIDISample_\(i)")
    mixer.connect(gPOPs[i].MIDISamplePlayer)
    sequencer!.tracks[i].setMIDIOutput(gPOPs[i].MIDISamplePlayer.midiIn)
}

AudioKit.start()
sequencer!.play()
</code>```

答:
I found out the cause of this issue. I learnt that the MIDI sequencer was creating an extra track when I gave it a specific number of MIDI tracks; for four tracks in my midi file, the sequencer was giving me five. This extra track is for tempo (as discovered here).

I also learnt that my first track was being ignored from my .plist (where I set up the stems for different songs).

My assumption that the first track is being used for the tempo track was tested, and when I created five tracks in my .plist to match the sequencer, the sinewave tone disappeared.

This lead to a workaround hack. I did this by duplicating the first sample in my .plist, which was being ignored anyway, and then hiding the sprite that represented this sound off screen. This works for now, but if anyone has an idea of how to control this tempo track and its use in AKSequencer I’d love to know more.

So in short:
Make sure that the MIDI file has exact number of tracks that you want to use. Create the same number of AKMIDISampler to use in AKSequencer adding one for tempo track. Then beware that the first track in the sequencer is the tempo track and will not work playing samples.

Body:
Following on from a previous issue, I stopped using AKSampler to move to the functionality used in AKMIDISampler. Got my loops working again (with help from this Google Groups post), but I have a sinewave playing (which happens when the MIDISampler can't find it's source file).

It's not an issue with the source files I'm targeting because they all play OK. The sinewave is coming from somewhere else in the process, but I can't see where...

Please help 8•)

(Simplified and edited code to show only relevant details - please get in touch for any clarification)

var MIDISamplePlayer = AKMIDISampler()
var sequencer: AKSequencer?
var mixer: AKMixer!

// initialise the mixer
mixer = AKMixer()

do  {
        audiofile = try AKAudioFile(readFileName: SoundFilename as! String,
        baseDir: .resources)
    } catch let error as NSError {
        print("There's an error: \(error)")
    }

do {
       try sprite.MIDISamplePlayer.loadAudioFile(audiofile)
    } catch let error as NSError {
       print("There's an error: \(error)")
    }

sprite.tracker = AKAmplitudeTracker(sprite.MIDISamplePlayer)
mixer.connect(to:sprite.tracker, bus: mixer.nextInput.bus)

sequencer = AKSequencer(filename: POPmidi)
sequencer?.enableLooping()

let midi = AKMIDI()

for i in 0..<popCount {
    gPOPs[i].MIDISamplePlayer.enableMIDI(midi.client, name: "MIDISample_\(i)")
    mixer.connect(gPOPs[i].MIDISamplePlayer)
    sequencer!.tracks[i].setMIDIOutput(gPOPs[i].MIDISamplePlayer.midiIn)
}

AudioKit.start()
sequencer!.play()


问:
Subset pandas dataframe up to when condition is met the first time
I have not had any luck accomplishing a task, where I want to subset a pandas dataframe up to a value, and grouping by their id. In the actual dataset I have several columns in between 'id' and 'status'

For example:

```<code>d = {'id': [1,1,1,1,1,1,1,2,2,2,2,2,2,2], 'status': [0,0,0,0,1,1,1,0,0,0,0,1,0,1]}
df = pd.DataFrame(data=d)

    id  status
0    1       0
1    1       0
2    1       0
3    1       0
4    1       1
5    1       1
6    1       1
7    2       0
8    2       0
9    2       0
10   2       0
11   2       1
12   2       0
13   2       1
</code>```

The desired subset would be:

```<code>    id  status
0    1       0
1    1       0
2    1       0
3    1       0
4    1       1
5    2       0
6    2       0
7    2       0
8    2       0
9    2       1
</code>```

答:
Let's try groupby + cumsum:

```<code>df = df.groupby('id', group_keys=False)\
       .apply(lambda x: x[x.status.cumsum().cumsum().le(1)])\
       .reset_index(drop=1)
df

   id  status
0   1       0
1   1       0
2   1       0
3   1       0
4   1       1
5   2       0
6   2       0
7   2       0
8   2       0
9   2       1
</code>```

Here's an alternative that performs a groupby to create a mask to be used as an indexer:

```<code>df = df[df.status.eq(1).groupby(df.id)\
          .apply(lambda x: x.cumsum().cumsum().le(1))]\
          .reset_index(drop=1)
df

   id  status
0   1       0
1   1       0
2   1       0
3   1       0
4   1       1
5   2       0
6   2       0
7   2       0
8   2       0
9   2       1
</code>```

Body:
I have not had any luck accomplishing a task, where I want to subset a pandas dataframe up to a value, and grouping by their id. In the actual dataset I have several columns in between 'id' and 'status'

For example:

d = {'id': [1,1,1,1,1,1,1,2,2,2,2,2,2,2], 'status': [0,0,0,0,1,1,1,0,0,0,0,1,0,1]}
df = pd.DataFrame(data=d)

    id  status
0    1       0
1    1       0
2    1       0
3    1       0
4    1       1
5    1       1
6    1       1
7    2       0
8    2       0
9    2       0
10   2       0
11   2       1
12   2       0
13   2       1

The desired subset would be:

    id  status
0    1       0
1    1       0
2    1       0
3    1       0
4    1       1
5    2       0
6    2       0
7    2       0
8    2       0
9    2       1

Body:
Let's try groupby + cumsum:

df = df.groupby('id', group_keys=False)\
       .apply(lambda x: x[x.status.cumsum().cumsum().le(1)])\
       .reset_index(drop=1)
df

   id  status
0   1       0
1   1       0
2   1       0
3   1       0
4   1       1
5   2       0
6   2       0
7   2       0
8   2       0
9   2       1

Here's an alternative that performs a groupby to create a mask to be used as an indexer:

df = df[df.status.eq(1).groupby(df.id)\
          .apply(lambda x: x.cumsum().cumsum().le(1))]\
          .reset_index(drop=1)
df

   id  status
0   1       0
1   1       0
2   1       0
3   1       0
4   1       1
5   2       0
6   2       0
7   2       0
8   2       0
9   2       1


问:
Problems with through associations
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

```<code>has_many :sales, primary_key: 'account_id'
</code>```

Sales Model

```<code>belongs_to :previousAgent, primary_key: 'previous_agent_id'
</code>```

Account View

```<code><% @account.sales.each do |p| %>
 <p>Previous Agent <%= p.previousAgent.name %></p>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>
</code>```

答:
I have worked out a solution for this. I'm unsure as why this has worked though.

I added a foreign_key to my Sales Model.

```<code>belongs_to :previousAgent, primary_key: 'previous_agent_id', foreign_key: 'previous_agent_id'
</code>```

If anyone can shed some light on why both primary and foreign key is needed that would be great.

Title: Problems with through associations

Body:
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

has_many :sales, primary_key: 'account_id'

Sales Model

belongs_to :previousAgent, primary_key: 'previous_agent_id'

Account View

<% @account.sales.each do |p| %>

Previous Agent <%= p.previousAgent.name %>

Date: <%= p.date.strftime("%d %B, %Y") %>

Comments: <%= p.comment %>

<% end %>

Body:
I have worked out a solution for this. I'm unsure as why this has worked though.

I added a foreign_key to my Sales Model.

belongs_to :previousAgent, primary_key: 'previous_agent_id', foreign_key: 'previous_agent_id'

If anyone can shed some light on why both primary and foreign key is needed that would be great.


问:
Dynamic allocation in CUDA - lower contention than handwritten solution?
Now CUDA allows dynamic allocation on the global memory. However, I couldn't find any reference to the scalability of that malloc function: is it any better than, for instance, preallocate a chunk of memory and then just assign the next memory chuck to a thread by atomically incrementing a global integer? This last "home-made" solution works but there is an obvious problem with scalability, so I wonder whether malloc takes care of that somehow.

答:
I think while your "home-made" solution might be just as good currently, although concurrent calls to a global integer might slow it down, Malloc would be my choice.

This is because it allows for Nvidia to deal with the headache of scalability and to make improvements, in either the hardware or software implementation, that you can taken advantage of just by re-compiling your code at a later date.


问:
How to submit radio button value + additional info about the form to Redux
This is a bit longwinded so I'll do my best to explain clearly.

I'm making a simple poll app and on the home page is an array of polls where you can vote on each poll.

Each poll is on a card and there will be different radio buttons representing the different voting options for that poll.

I'm trying to set up a form for each poll which contains radio button inputs for each of the different options and push that onSubmit to an action creator.

However, I would also like to pass that title of the poll as well as an argument to the action creator so that I can create a single action creator that will help me submit the votes for all the polls. Something like submitVote(title, option).

Here is my polls page:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import Loading from '../Loading';

class MyPolls extends Component {
  constructor(props) {
    super(props);
    this.state = {
      skip: 0,
      isLoading: true,
      isLoadingMore: false,
      value: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    this.props.fetchMyPolls(this.state.skip)
      .then(() => {
        setTimeout(() => {
            this.setState({
            skip: this.state.skip + 4,
            isLoading: false
          });
        }, 1000);
      });
  }

  sumVotes(acc, cur) {
    return acc.votes + cur.votes
  }

  loadMore(skip) {
    this.setState({ isLoadingMore: true });

    setTimeout(() => {
      this.props.fetchMyPolls(skip)
        .then(() => {
          const nextSkip = this.state.skip + 4;
          this.setState({
            skip: nextSkip,
            isLoadingMore: false
          });
        });
    }, 1000);
  }

  handleSubmit(e) {
    e.preventDefault();
  }

  handleChange(event) {
    console.log(event.target.value);
    this.setState({ value: event.target.value });
  }

  renderPolls() {
    return this.props.polls.map(poll => {
      return (
        <div className='card' key={poll._id} style={{ width: '350px', height: '400px' }}>
          <div className='card-content'>
            <span className='card-title'>{poll.title}</span>
            <p>Total votes: {poll.options.reduce((acc, cur) => { return acc + cur.votes }, 0)}</p>
            <form onSubmit={this.handleSubmit}>
              {poll.options.map(option => {
                return (
                  <p key={option._id}>
                    <input
                      name={poll.title}
                      className='with-gap'
                      type='radio'
                      id={option._id}
                      value={option.option}
                      onChange={this.handleChange}
                    />
                    <label htmlFor={option._id}>
                      {option.option}
                    </label>
                  </p>
                )
              })}

              <button
                type='text'
                className='activator teal btn waves-effect waves-light'
                style={{
                  position: 'absolute',
                  bottom: '10%',
                  transform: 'translateX(-50%)'
                }}
                >
                Submit
                <i className='material-icons right'>
                  send
                </i>
              </button>
            </form>
          </div>
          <div className='card-reveal'>
            <span className='card-title'>{poll.title}
              <i className='material-icons right'>close</i>
            </span>
            <p>
              dsfasfasdf
            </p>
          </div>
        </div>
      )
    })
  }

  render() {
    return (
      <div className='center-align container'>
        <h2>My Polls</h2>
        {this.state.isLoading ? <Loading size='big' /> :
        <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-evenly', alignItems: 'center', alignContent: 'center' }}>
          {this.renderPolls()}
        </div>}
        <div className='row'>
          {this.state.isLoadingMore ? <Loading size='small' /> :
          <button
            className='btn red lighten-2 wave-effect waves-light' onClick={() => this.loadMore(this.state.skip)}>
            Load More
          </button>}
        </div>
      </div>

    );
  }
}

function mapStateToProps({ polls }) {
  return { polls }
}

export default connect(mapStateToProps, actions)(MyPolls);
</code>```

Demo of the app so far: https://voting-app-drhectapus.herokuapp.com/

(use riverfish@gmail.com and password 123 to login).

Github repo: https://github.com/drhectapus/Voting-App

I'd like to program it so that when form is submitted via this.handleSubmit, the handleSubmit function can take 2 arguments, title and option and pass that onto an action creator in redux.

How do I do this?

答:
It's a little difficult to understand everything going on here, but I get the sense that your main goal is to pass two args to this.handleSubmit. You may instead consider just passing poll.title and grabbing the selected option from state. Try something like this:

```<code>this.handleSubmit(title) {

    // this.state.value should already have the selected option!
    let obj = {
        title,
        option: this.state.value
    };

    // dispatch the object to redux, update your reducer, etc.
}
</code>```

And in your render, be sure to bind poll.title as the argument:

```<code>render() {
    ...
    <form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}
</code>```

Does that help at all? Let me know if I'm totally missing the mark on what you intend. With .bind() you pass the this context to use followed by a list of common separated args, so you could pass multiple args, but it's much easier to just grab option from state in this case.

Edit

If you want to access the SyntheticEvent that gets fired on submit, you simple specify it as the second argument to this.handleSubmit like so:

```<code>this.handleSubmit(title, event) {
    // prevent form submit
    event.preventDefault();
}

// this is the exact same as above, no need to pass event
render() {
    ...
    <form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}
</code>```

In React, synthetic events are always passed as the last argument to a bound function and simply need to be specified to be in the method definition (no need to specify in render). This is Function.prototype.bind way of working with functions and events in React. Here are the supporting docs: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

Body:
This is a bit longwinded so I'll do my best to explain clearly.

I'm making a simple poll app and on the home page is an array of polls where you can vote on each poll.

Each poll is on a card and there will be different radio buttons representing the different voting options for that poll.

I'm trying to set up a form for each poll which contains radio button inputs for each of the different options and push that onSubmit to an action creator.

However, I would also like to pass that title of the poll as well as an argument to the action creator so that I can create a single action creator that will help me submit the votes for all the polls. Something like submitVote(title, option).

Here is my polls page:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import Loading from '../Loading';

class MyPolls extends Component {
  constructor(props) {
    super(props);
    this.state = {
      skip: 0,
      isLoading: true,
      isLoadingMore: false,
      value: ''
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    this.props.fetchMyPolls(this.state.skip)
      .then(() => {
        setTimeout(() => {
            this.setState({
            skip: this.state.skip + 4,
            isLoading: false
          });
        }, 1000);
      });
  }

  sumVotes(acc, cur) {
    return acc.votes + cur.votes
  }

  loadMore(skip) {
    this.setState({ isLoadingMore: true });

    setTimeout(() => {
      this.props.fetchMyPolls(skip)
        .then(() => {
          const nextSkip = this.state.skip + 4;
          this.setState({
            skip: nextSkip,
            isLoadingMore: false
          });
        });
    }, 1000);
  }

  handleSubmit(e) {
    e.preventDefault();
  }

  handleChange(event) {
    console.log(event.target.value);
    this.setState({ value: event.target.value });
  }

  renderPolls() {
    return this.props.polls.map(poll => {
      return (

            {poll.title}

Total votes: {poll.options.reduce((acc, cur) => { return acc + cur.votes }, 0)}

            <form onSubmit={this.handleSubmit}>
              {poll.options.map(option => {
                return (

                    <input
                      name={poll.title}
                      className='with-gap'
                      type='radio'
                      id={option._id}
                      value={option.option}
                      onChange={this.handleChange}
                    />

                      {option.option}

                )
              })}

              <button
                type='text'
                className='activator teal btn waves-effect waves-light'
                style={{
                  position: 'absolute',
                  bottom: '10%',
                  transform: 'translateX(-50%)'
                }}
                >
                Submit

                  send

              </button>
            </form>

            {poll.title}
              close

              dsfasfasdf

      )
    })
  }

  render() {
    return (

My Polls

        {this.state.isLoading ? <Loading size='big' /> :

          {this.renderPolls()}

}

          {this.state.isLoadingMore ? <Loading size='small' /> :
          <button
            className='btn red lighten-2 wave-effect waves-light' onClick={() => this.loadMore(this.state.skip)}>
            Load More
          </button>}

    );
  }
}

function mapStateToProps({ polls }) {
  return { polls }
}

export default connect(mapStateToProps, actions)(MyPolls);

Demo of the app so far: https://voting-app-drhectapus.herokuapp.com/

(use riverfish@gmail.com and password 123 to login).

Github repo: https://github.com/drhectapus/Voting-App

I'd like to program it so that when form is submitted via this.handleSubmit, the handleSubmit function can take 2 arguments, title and option and pass that onto an action creator in redux.

How do I do this?

Body:
It's a little difficult to understand everything going on here, but I get the sense that your main goal is to pass two args to this.handleSubmit. You may instead consider just passing poll.title and grabbing the selected option from state. Try something like this:

this.handleSubmit(title) {

    // this.state.value should already have the selected option!
    let obj = {
        title,
        option: this.state.value
    };

    // dispatch the object to redux, update your reducer, etc.
}

And in your render, be sure to bind poll.title as the argument:

render() {
    ...
    <form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}

Does that help at all? Let me know if I'm totally missing the mark on what you intend. With .bind() you pass the this context to use followed by a list of common separated args, so you could pass multiple args, but it's much easier to just grab option from state in this case.

Edit

If you want to access the SyntheticEvent that gets fired on submit, you simple specify it as the second argument to this.handleSubmit like so:

this.handleSubmit(title, event) {
    // prevent form submit
    event.preventDefault();
}

// this is the exact same as above, no need to pass event
render() {
    ...
    <form onSubmit={this.handleSubmit.bind(this, poll.title)}>
}

In React, synthetic events are always passed as the last argument to a bound function and simply need to be specified to be in the method definition (no need to specify in render). This is Function.prototype.bind way of working with functions and events in React. Here are the supporting docs: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers


问:
BufferedReader not reading second output
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

```<code>public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.
</code>```

What could be the issue here and what is the best way to solve this problem?

答:
Documentation says

The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined. After execution of the terminal stream operation there are no guarantees that the reader will be at a specific position from which to read the next character or line.

Body:
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.

What could be the issue here and what is the best way to solve this problem?


问:
View raw markdown of GitHub comment
How can I view the Markdown of a comment in a GitHub issue? For example, I would like to see the Markdown that makes up this comment:
https://github.com/jashkenas/backbone/issues/3857#issue-116738665</p>

答:
It's probably late. But I could somewhat do it this way (at least in firefox).

I am assuming your intention is to copy the formatting of the comment.

This is not an exact solution, but since GitHub supports HTML tags in comments, this will work just fine.

Right click somewhere at the top of the comment you want to copy.

Inspect element

In the Inspect Element box, you will find a line that's a few lines above the highlighted line which has this code:

Right click on the line having the above code

Select Copy>Inner HTML

Now you can either paste this in a comment box, preview it and you'll be able to see the same formatting, OR use an online HTML to MD converter.

Title: View raw markdown of GitHub comment

Body:
It's probably late. But I could somewhat do it this way (at least in firefox).

I am assuming your intention is to copy the formatting of the comment.

This is not an exact solution, but since GitHub supports HTML tags in comments, this will work just fine.

Right click somewhere at the top of the comment you want to copy.

Inspect element

In the Inspect Element box, you will find a line that's a few lines above the highlighted line which has this code:

<td class="d-block comment-body markdown-body  js-comment-body">

Right click on the line having the above code

Select Copy>Inner HTML

Now you can either paste this in a comment box, preview it and you'll be able to see the same formatting, OR use an online HTML to MD converter.


问:
Why does the bullet point created by OpenXML become a strange character?
I encountered a very strange problem while I was creating a bullet list using the Open XML SDK. The problem is the bullet points in the list are shown in strange characters, not the dots that I expected. The following is the code:

```<code>NumberingDefinitionsPart numberingPart = doc.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("nl01");
            W.Numbering element =
              new W.Numbering(
                new W.AbstractNum(
                  new W.Level(
                    new W.NumberingFormat() { Val = W.NumberFormatValues.Bullet },
                    new W.LevelText { Val = "·" },
                    new W.LevelJustification() { Val = W.LevelJustificationValues.Left },
                    new W.NumberingSymbolRunProperties(
                          new W.RunFonts { Hint = W.FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" })
                  ) { LevelIndex = 0 }
                ) { AbstractNumberId = 1 },
                new W.NumberingInstance(
                  new W.AbstractNumId() { Val = 1 }
                ) { NumberID = 1 });

            element.Save(numberingPart);
</code>```

Would anyone point out the problem in the code?

答:
I created a blank word doc and put in one bullet list item. I then used the Open XML SDK 2.0 Productivity Tool to reflect the code that made that list:

```<code>            Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "002C2112", RsidParagraphProperties = "00CD1798", RsidRunAdditionDefault = "002C2112" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };

            NumberingProperties numberingProperties1 = new NumberingProperties();
            NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
            NumberingId numberingId1 = new NumberingId(){ Val = 1 };

            numberingProperties1.Append(numberingLevelReference1);
            numberingProperties1.Append(numberingId1);

            paragraphProperties1.Append(paragraphStyleId1);
            paragraphProperties1.Append(numberingProperties1);

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Test bullet list";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);
</code>```

You also need to make sure the level of bullet you are using (in my example below is level 0) is defined in the numbering.xml part.  This only gets created when you use a number. I've posted how to create that part below:

```<code>NumberingDefinitionsPart numberingDefinitionsPart1 = part.AddNewPart<NumberingDefinitionsPart>("rId1"); //<-This id must be unique so you might have to change it
            GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

// Generates content of part.
        private void GeneratePartContent(NumberingDefinitionsPart part)
        {
            Numbering numbering1 = new Numbering();
            numbering1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            numbering1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            numbering1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            numbering1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            numbering1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            numbering1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            numbering1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            numbering1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            numbering1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");

            AbstractNum abstractNum1 = new AbstractNum(){ AbstractNumberId = 0 };
            Nsid nsid1 = new Nsid(){ Val = "4BEB3E25" };
            MultiLevelType multiLevelType1 = new MultiLevelType(){ Val = MultiLevelValues.HybridMultilevel };
            TemplateCode templateCode1 = new TemplateCode(){ Val = "C2420342" };

            Level level1 = new Level(){ LevelIndex = 0, TemplateCode = "04090001" };
            StartNumberingValue startNumberingValue1 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat1 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText1 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification1 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties1 = new PreviousParagraphProperties();
            Indentation indentation1 = new Indentation(){ Left = "720", Hanging = "360" };

            previousParagraphProperties1.Append(indentation1);

            NumberingSymbolRunProperties numberingSymbolRunProperties1 = new NumberingSymbolRunProperties();
            RunFonts runFonts1 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties1.Append(runFonts1);

            level1.Append(startNumberingValue1);
            level1.Append(numberingFormat1);
            level1.Append(levelText1);
            level1.Append(levelJustification1);
            level1.Append(previousParagraphProperties1);
            level1.Append(numberingSymbolRunProperties1);

            Level level2 = new Level(){ LevelIndex = 1, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue2 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat2 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText2 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification2 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties2 = new PreviousParagraphProperties();
            Indentation indentation2 = new Indentation(){ Left = "1440", Hanging = "360" };

            previousParagraphProperties2.Append(indentation2);

            NumberingSymbolRunProperties numberingSymbolRunProperties2 = new NumberingSymbolRunProperties();
            RunFonts runFonts2 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties2.Append(runFonts2);

            level2.Append(startNumberingValue2);
            level2.Append(numberingFormat2);
            level2.Append(levelText2);
            level2.Append(levelJustification2);
            level2.Append(previousParagraphProperties2);
            level2.Append(numberingSymbolRunProperties2);

            Level level3 = new Level(){ LevelIndex = 2, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue3 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat3 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText3 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification3 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties3 = new PreviousParagraphProperties();
            Indentation indentation3 = new Indentation(){ Left = "2160", Hanging = "360" };

            previousParagraphProperties3.Append(indentation3);

            NumberingSymbolRunProperties numberingSymbolRunProperties3 = new NumberingSymbolRunProperties();
            RunFonts runFonts3 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties3.Append(runFonts3);

            level3.Append(startNumberingValue3);
            level3.Append(numberingFormat3);
            level3.Append(levelText3);
            level3.Append(levelJustification3);
            level3.Append(previousParagraphProperties3);
            level3.Append(numberingSymbolRunProperties3);

            Level level4 = new Level(){ LevelIndex = 3, TemplateCode = "04090001", Tentative = true };
            StartNumberingValue startNumberingValue4 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat4 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText4 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification4 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties4 = new PreviousParagraphProperties();
            Indentation indentation4 = new Indentation(){ Left = "2880", Hanging = "360" };

            previousParagraphProperties4.Append(indentation4);

            NumberingSymbolRunProperties numberingSymbolRunProperties4 = new NumberingSymbolRunProperties();
            RunFonts runFonts4 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties4.Append(runFonts4);

            level4.Append(startNumberingValue4);
            level4.Append(numberingFormat4);
            level4.Append(levelText4);
            level4.Append(levelJustification4);
            level4.Append(previousParagraphProperties4);
            level4.Append(numberingSymbolRunProperties4);

            Level level5 = new Level(){ LevelIndex = 4, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue5 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat5 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText5 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification5 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties5 = new PreviousParagraphProperties();
            Indentation indentation5 = new Indentation(){ Left = "3600", Hanging = "360" };

            previousParagraphProperties5.Append(indentation5);

            NumberingSymbolRunProperties numberingSymbolRunProperties5 = new NumberingSymbolRunProperties();
            RunFonts runFonts5 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties5.Append(runFonts5);

            level5.Append(startNumberingValue5);
            level5.Append(numberingFormat5);
            level5.Append(levelText5);
            level5.Append(levelJustification5);
            level5.Append(previousParagraphProperties5);
            level5.Append(numberingSymbolRunProperties5);

            Level level6 = new Level(){ LevelIndex = 5, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue6 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat6 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText6 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification6 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties6 = new PreviousParagraphProperties();
            Indentation indentation6 = new Indentation(){ Left = "4320", Hanging = "360" };

            previousParagraphProperties6.Append(indentation6);

            NumberingSymbolRunProperties numberingSymbolRunProperties6 = new NumberingSymbolRunProperties();
            RunFonts runFonts6 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties6.Append(runFonts6);

            level6.Append(startNumberingValue6);
            level6.Append(numberingFormat6);
            level6.Append(levelText6);
            level6.Append(levelJustification6);
            level6.Append(previousParagraphProperties6);
            level6.Append(numberingSymbolRunProperties6);

            Level level7 = new Level(){ LevelIndex = 6, TemplateCode = "04090001", Tentative = true };
            StartNumberingValue startNumberingValue7 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat7 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText7 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification7 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties7 = new PreviousParagraphProperties();
            Indentation indentation7 = new Indentation(){ Left = "5040", Hanging = "360" };

            previousParagraphProperties7.Append(indentation7);

            NumberingSymbolRunProperties numberingSymbolRunProperties7 = new NumberingSymbolRunProperties();
            RunFonts runFonts7 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties7.Append(runFonts7);

            level7.Append(startNumberingValue7);
            level7.Append(numberingFormat7);
            level7.Append(levelText7);
            level7.Append(levelJustification7);
            level7.Append(previousParagraphProperties7);
            level7.Append(numberingSymbolRunProperties7);

            Level level8 = new Level(){ LevelIndex = 7, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue8 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat8 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText8 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification8 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties8 = new PreviousParagraphProperties();
            Indentation indentation8 = new Indentation(){ Left = "5760", Hanging = "360" };

            previousParagraphProperties8.Append(indentation8);

            NumberingSymbolRunProperties numberingSymbolRunProperties8 = new NumberingSymbolRunProperties();
            RunFonts runFonts8 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties8.Append(runFonts8);

            level8.Append(startNumberingValue8);
            level8.Append(numberingFormat8);
            level8.Append(levelText8);
            level8.Append(levelJustification8);
            level8.Append(previousParagraphProperties8);
            level8.Append(numberingSymbolRunProperties8);

            Level level9 = new Level(){ LevelIndex = 8, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue9 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat9 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText9 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification9 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties9 = new PreviousParagraphProperties();
            Indentation indentation9 = new Indentation(){ Left = "6480", Hanging = "360" };

            previousParagraphProperties9.Append(indentation9);

            NumberingSymbolRunProperties numberingSymbolRunProperties9 = new NumberingSymbolRunProperties();
            RunFonts runFonts9 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties9.Append(runFonts9);

            level9.Append(startNumberingValue9);
            level9.Append(numberingFormat9);
            level9.Append(levelText9);
            level9.Append(levelJustification9);
            level9.Append(previousParagraphProperties9);
            level9.Append(numberingSymbolRunProperties9);

            abstractNum1.Append(nsid1);
            abstractNum1.Append(multiLevelType1);
            abstractNum1.Append(templateCode1);
            abstractNum1.Append(level1);
            abstractNum1.Append(level2);
            abstractNum1.Append(level3);
            abstractNum1.Append(level4);
            abstractNum1.Append(level5);
            abstractNum1.Append(level6);
            abstractNum1.Append(level7);
            abstractNum1.Append(level8);
            abstractNum1.Append(level9);

            NumberingInstance numberingInstance1 = new NumberingInstance(){ NumberID = 1 };
            AbstractNumId abstractNumId1 = new AbstractNumId(){ Val = 0 };

            numberingInstance1.Append(abstractNumId1);

            numbering1.Append(abstractNum1);
            numbering1.Append(numberingInstance1);

            part.Numbering = numbering1;
        }
</code>```

Body:
I encountered a very strange problem while I was creating a bullet list using the Open XML SDK. The problem is the bullet points in the list are shown in strange characters, not the dots that I expected. The following is the code:

NumberingDefinitionsPart numberingPart = doc.MainDocumentPart.AddNewPart<NumberingDefinitionsPart>("nl01");
            W.Numbering element =
              new W.Numbering(
                new W.AbstractNum(
                  new W.Level(
                    new W.NumberingFormat() { Val = W.NumberFormatValues.Bullet },
                    new W.LevelText { Val = "·" },
                    new W.LevelJustification() { Val = W.LevelJustificationValues.Left },
                    new W.NumberingSymbolRunProperties(
                          new W.RunFonts { Hint = W.FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" })
                  ) { LevelIndex = 0 }
                ) { AbstractNumberId = 1 },
                new W.NumberingInstance(
                  new W.AbstractNumId() { Val = 1 }
                ) { NumberID = 1 });

            element.Save(numberingPart);

Would anyone point out the problem in the code?

Body:
I created a blank word doc and put in one bullet list item. I then used the Open XML SDK 2.0 Productivity Tool to reflect the code that made that list:

            Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "002C2112", RsidParagraphProperties = "00CD1798", RsidRunAdditionDefault = "002C2112" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };

            NumberingProperties numberingProperties1 = new NumberingProperties();
            NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
            NumberingId numberingId1 = new NumberingId(){ Val = 1 };

            numberingProperties1.Append(numberingLevelReference1);
            numberingProperties1.Append(numberingId1);

            paragraphProperties1.Append(paragraphStyleId1);
            paragraphProperties1.Append(numberingProperties1);

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Test bullet list";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

You also need to make sure the level of bullet you are using (in my example below is level 0) is defined in the numbering.xml part.  This only gets created when you use a number. I've posted how to create that part below:

NumberingDefinitionsPart numberingDefinitionsPart1 = part.AddNewPart<NumberingDefinitionsPart>("rId1"); //<-This id must be unique so you might have to change it
            GenerateNumberingDefinitionsPart1Content(numberingDefinitionsPart1);

// Generates content of part.
        private void GeneratePartContent(NumberingDefinitionsPart part)
        {
            Numbering numbering1 = new Numbering();
            numbering1.AddNamespaceDeclaration("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            numbering1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            numbering1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            numbering1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            numbering1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            numbering1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            numbering1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            numbering1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            numbering1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");

            AbstractNum abstractNum1 = new AbstractNum(){ AbstractNumberId = 0 };
            Nsid nsid1 = new Nsid(){ Val = "4BEB3E25" };
            MultiLevelType multiLevelType1 = new MultiLevelType(){ Val = MultiLevelValues.HybridMultilevel };
            TemplateCode templateCode1 = new TemplateCode(){ Val = "C2420342" };

            Level level1 = new Level(){ LevelIndex = 0, TemplateCode = "04090001" };
            StartNumberingValue startNumberingValue1 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat1 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText1 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification1 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties1 = new PreviousParagraphProperties();
            Indentation indentation1 = new Indentation(){ Left = "720", Hanging = "360" };

            previousParagraphProperties1.Append(indentation1);

            NumberingSymbolRunProperties numberingSymbolRunProperties1 = new NumberingSymbolRunProperties();
            RunFonts runFonts1 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties1.Append(runFonts1);

            level1.Append(startNumberingValue1);
            level1.Append(numberingFormat1);
            level1.Append(levelText1);
            level1.Append(levelJustification1);
            level1.Append(previousParagraphProperties1);
            level1.Append(numberingSymbolRunProperties1);

            Level level2 = new Level(){ LevelIndex = 1, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue2 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat2 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText2 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification2 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties2 = new PreviousParagraphProperties();
            Indentation indentation2 = new Indentation(){ Left = "1440", Hanging = "360" };

            previousParagraphProperties2.Append(indentation2);

            NumberingSymbolRunProperties numberingSymbolRunProperties2 = new NumberingSymbolRunProperties();
            RunFonts runFonts2 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties2.Append(runFonts2);

            level2.Append(startNumberingValue2);
            level2.Append(numberingFormat2);
            level2.Append(levelText2);
            level2.Append(levelJustification2);
            level2.Append(previousParagraphProperties2);
            level2.Append(numberingSymbolRunProperties2);

            Level level3 = new Level(){ LevelIndex = 2, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue3 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat3 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText3 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification3 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties3 = new PreviousParagraphProperties();
            Indentation indentation3 = new Indentation(){ Left = "2160", Hanging = "360" };

            previousParagraphProperties3.Append(indentation3);

            NumberingSymbolRunProperties numberingSymbolRunProperties3 = new NumberingSymbolRunProperties();
            RunFonts runFonts3 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties3.Append(runFonts3);

            level3.Append(startNumberingValue3);
            level3.Append(numberingFormat3);
            level3.Append(levelText3);
            level3.Append(levelJustification3);
            level3.Append(previousParagraphProperties3);
            level3.Append(numberingSymbolRunProperties3);

            Level level4 = new Level(){ LevelIndex = 3, TemplateCode = "04090001", Tentative = true };
            StartNumberingValue startNumberingValue4 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat4 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText4 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification4 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties4 = new PreviousParagraphProperties();
            Indentation indentation4 = new Indentation(){ Left = "2880", Hanging = "360" };

            previousParagraphProperties4.Append(indentation4);

            NumberingSymbolRunProperties numberingSymbolRunProperties4 = new NumberingSymbolRunProperties();
            RunFonts runFonts4 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties4.Append(runFonts4);

            level4.Append(startNumberingValue4);
            level4.Append(numberingFormat4);
            level4.Append(levelText4);
            level4.Append(levelJustification4);
            level4.Append(previousParagraphProperties4);
            level4.Append(numberingSymbolRunProperties4);

            Level level5 = new Level(){ LevelIndex = 4, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue5 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat5 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText5 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification5 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties5 = new PreviousParagraphProperties();
            Indentation indentation5 = new Indentation(){ Left = "3600", Hanging = "360" };

            previousParagraphProperties5.Append(indentation5);

            NumberingSymbolRunProperties numberingSymbolRunProperties5 = new NumberingSymbolRunProperties();
            RunFonts runFonts5 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties5.Append(runFonts5);

            level5.Append(startNumberingValue5);
            level5.Append(numberingFormat5);
            level5.Append(levelText5);
            level5.Append(levelJustification5);
            level5.Append(previousParagraphProperties5);
            level5.Append(numberingSymbolRunProperties5);

            Level level6 = new Level(){ LevelIndex = 5, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue6 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat6 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText6 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification6 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties6 = new PreviousParagraphProperties();
            Indentation indentation6 = new Indentation(){ Left = "4320", Hanging = "360" };

            previousParagraphProperties6.Append(indentation6);

            NumberingSymbolRunProperties numberingSymbolRunProperties6 = new NumberingSymbolRunProperties();
            RunFonts runFonts6 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties6.Append(runFonts6);

            level6.Append(startNumberingValue6);
            level6.Append(numberingFormat6);
            level6.Append(levelText6);
            level6.Append(levelJustification6);
            level6.Append(previousParagraphProperties6);
            level6.Append(numberingSymbolRunProperties6);

            Level level7 = new Level(){ LevelIndex = 6, TemplateCode = "04090001", Tentative = true };
            StartNumberingValue startNumberingValue7 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat7 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText7 = new LevelText(){ Val = "·" };
            LevelJustification levelJustification7 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties7 = new PreviousParagraphProperties();
            Indentation indentation7 = new Indentation(){ Left = "5040", Hanging = "360" };

            previousParagraphProperties7.Append(indentation7);

            NumberingSymbolRunProperties numberingSymbolRunProperties7 = new NumberingSymbolRunProperties();
            RunFonts runFonts7 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Symbol", HighAnsi = "Symbol" };

            numberingSymbolRunProperties7.Append(runFonts7);

            level7.Append(startNumberingValue7);
            level7.Append(numberingFormat7);
            level7.Append(levelText7);
            level7.Append(levelJustification7);
            level7.Append(previousParagraphProperties7);
            level7.Append(numberingSymbolRunProperties7);

            Level level8 = new Level(){ LevelIndex = 7, TemplateCode = "04090003", Tentative = true };
            StartNumberingValue startNumberingValue8 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat8 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText8 = new LevelText(){ Val = "o" };
            LevelJustification levelJustification8 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties8 = new PreviousParagraphProperties();
            Indentation indentation8 = new Indentation(){ Left = "5760", Hanging = "360" };

            previousParagraphProperties8.Append(indentation8);

            NumberingSymbolRunProperties numberingSymbolRunProperties8 = new NumberingSymbolRunProperties();
            RunFonts runFonts8 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Courier New", HighAnsi = "Courier New", ComplexScript = "Courier New" };

            numberingSymbolRunProperties8.Append(runFonts8);

            level8.Append(startNumberingValue8);
            level8.Append(numberingFormat8);
            level8.Append(levelText8);
            level8.Append(levelJustification8);
            level8.Append(previousParagraphProperties8);
            level8.Append(numberingSymbolRunProperties8);

            Level level9 = new Level(){ LevelIndex = 8, TemplateCode = "04090005", Tentative = true };
            StartNumberingValue startNumberingValue9 = new StartNumberingValue(){ Val = 1 };
            NumberingFormat numberingFormat9 = new NumberingFormat(){ Val = NumberFormatValues.Bullet };
            LevelText levelText9 = new LevelText(){ Val = "§" };
            LevelJustification levelJustification9 = new LevelJustification(){ Val = LevelJustificationValues.Left };

            PreviousParagraphProperties previousParagraphProperties9 = new PreviousParagraphProperties();
            Indentation indentation9 = new Indentation(){ Left = "6480", Hanging = "360" };

            previousParagraphProperties9.Append(indentation9);

            NumberingSymbolRunProperties numberingSymbolRunProperties9 = new NumberingSymbolRunProperties();
            RunFonts runFonts9 = new RunFonts(){ Hint = FontTypeHintValues.Default, Ascii = "Wingdings", HighAnsi = "Wingdings" };

            numberingSymbolRunProperties9.Append(runFonts9);

            level9.Append(startNumberingValue9);
            level9.Append(numberingFormat9);
            level9.Append(levelText9);
            level9.Append(levelJustification9);
            level9.Append(previousParagraphProperties9);
            level9.Append(numberingSymbolRunProperties9);

            abstractNum1.Append(nsid1);
            abstractNum1.Append(multiLevelType1);
            abstractNum1.Append(templateCode1);
            abstractNum1.Append(level1);
            abstractNum1.Append(level2);
            abstractNum1.Append(level3);
            abstractNum1.Append(level4);
            abstractNum1.Append(level5);
            abstractNum1.Append(level6);
            abstractNum1.Append(level7);
            abstractNum1.Append(level8);
            abstractNum1.Append(level9);

            NumberingInstance numberingInstance1 = new NumberingInstance(){ NumberID = 1 };
            AbstractNumId abstractNumId1 = new AbstractNumId(){ Val = 0 };

            numberingInstance1.Append(abstractNumId1);

            numbering1.Append(abstractNum1);
            numbering1.Append(numberingInstance1);

            part.Numbering = numbering1;
        }


问:
How to get video meta data when the track changes in JW player 7?
Looking through their docs, I do not see any method which allows me to get the metadata when a video changes.

I would like to get the videos metadata so I can display that data in custom way.

答:
Found it:

https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayeronplaylistitem

when the video changes, u get metadata back.

```<code>jwplayer().on('playlistItem', function(data) { console.log('meta', data.item); });
</code>```

Body:
Found it:

https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayeronplaylistitem

when the video changes, u get metadata back.

jwplayer().on('playlistItem', function(data) { console.log('meta', data.item); });


问:
Django - Check Other Objects Prior to Save
I want to override the built-in django .save() method to perform a check against all other objects in the database.

```<code>For example:

class User(models.Model):
    name = models.CharField(max_length=120)

class Admin(models.Model):
    name = models.CharField(max_length=120)

class SecurityGroup(models.Model):
    name = models.CharField(max_length=120)
    users = models.ManytoManyField(User)
    admins = models.ManytoManyField(Admin)

    def save(self, *args, **kwargs):

        # check admins don't exist in any other SecurityGroup prior to save

        super(SecurityGroup, self).save(*args, **kwargs) # Call the "real" save() method.
</code>```

The documentation example is pretty simple, and doesn't describe this type of pre-save check.

I have tried adding in lines to .save() such as:

```<code>`self.objects.filter(admins__name=self.admins.name).count()`
</code>```

to call the other SecurityGroup objects but I receive the error:

```<code>`Manager is not accessible via SecurityGroup instance`
</code>```

Is it possible to achieve this save functionality internal to the SecurityGroup Model, or do I need to create a form and use SecurityGroup.save(commit=False) for this type of pre-save check?

Thanks for the help.

答:
The error is caused by accessing the Manager of a model through a model instance. You should have used </p>

```<code>self.model_class().objects
</code>```

Body:
I want to override the built-in django .save() method to perform a check against all other objects in the database.

For example:

class User(models.Model):
    name = models.CharField(max_length=120)

class Admin(models.Model):
    name = models.CharField(max_length=120)

class SecurityGroup(models.Model):
    name = models.CharField(max_length=120)
    users = models.ManytoManyField(User)
    admins = models.ManytoManyField(Admin)

    def save(self, *args, **kwargs):

        # check admins don't exist in any other SecurityGroup prior to save

        super(SecurityGroup, self).save(*args, **kwargs) # Call the "real" save() method.

The documentation example is pretty simple, and doesn't describe this type of pre-save check.

I have tried adding in lines to .save() such as:

`self.objects.filter(admins__name=self.admins.name).count()`

to call the other SecurityGroup objects but I receive the error:

`Manager is not accessible via SecurityGroup instance`

Is it possible to achieve this save functionality internal to the SecurityGroup Model, or do I need to create a form and use SecurityGroup.save(commit=False) for this type of pre-save check?

Thanks for the help.

Body:
The error is caused by accessing the Manager of a model through a model instance. You should have used

self.model_class().objects


问:
Chartjs dynamic chart return both x & y axis undefined
I am new to chartjs. After spend some time checking tutorials I came up codes as following and it's giving me undefined result both x and y axis. I can manage to get static data working i.e. if put down month on y-axis and charts display fine. Any help is greatly appreciated. By the way I am using chartjsversion 2.1.4.

data.php:

```<code><?php
//setting header to json
header('Content-Type: application/json');
include_once 'includes/db_connect.php';

$query = sprintf("SELECT FiscalPeriod, SUM(DollarsSold) AS Sold
                  FROM ar_customersalespersonhistory
                  WHERE FiscalYear = '2017'
                  GROUP BY FiscalPeriod
                  ORDER BY FiscalPeriod
                ");

//execute query
$result = $connection->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$connection->close();

//now print the data
print json_encode($data);

?>
</code>```

Output from data.php:

```<code>[{
  "FiscalPeriod": "01",
  "Sold": "357508.03"
}, {
  "FiscalPeriod": "02",
  "Sold": "393790.14"
}, {
  "FiscalPeriod": "03",
  "Sold": "407346.07"
}, {
  "FiscalPeriod": "04",
  "Sold": "557704.12"
}, {
  "FiscalPeriod": "05",
  "Sold": "555916.68"
}, {
  "FiscalPeriod": "06",
  "Sold": "422659.26"
}, {
  "FiscalPeriod": "07",
  "Sold": "297766.49"
}, {
  "FiscalPeriod": "08",
  "Sold": "448256.07"
}, {
  "FiscalPeriod": "09",
  "Sold": "510020.86"
}, {
  "FiscalPeriod": "10",
  "Sold": "325525.30"
}, {
  "FiscalPeriod": "11",
  "Sold": "89214.27"
}]
</code>```

And javascript:

```<code>$(document).ready(function() {
  $.ajax({
    url: '/registration/sales_general.php',
    method: 'GET',
    // dataType: 'json',
    success: function(data) {
      // console.log(data);
      var month = [];
      var sold = [];

      for (var i in data) {
        month.push(data[i].FiscalPeriod);
        sold.push(data[i].Sold);
      }

      console.log(month);
      console.log(sold);
      var chartdata = {
        // labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        labels: month,
        datasets: [{
          label: '2017',
          backgroundColor: '#26B99A',
          // data: [33,24,25,19,46,99,21]
          data: sold
        }]
      };

      var ctx = $('#mybarChart1');
      ctx.height = 70;

      var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata
      });
    },
    error: function(data) {
      console.log(data);
    }
  });
});
</code>```

答:
Your chartdata object doesn't contain valid ChartJS options

This should work:

    var data = [{"FiscalPeriod":"01","Sold":"357508.03"},{"FiscalPeriod":"02","Sold":"393790.14"},{"FiscalPeriod":"03","Sold":"407346.07"},{"FiscalPeriod":"04","Sold":"557704.12"},{"FiscalPeriod":"05","Sold":"555916.68"},{"FiscalPeriod":"06","Sold":"422659.26"},{"FiscalPeriod":"07","Sold":"297766.49"},{"FiscalPeriod":"08","Sold":"448256.07"},{"FiscalPeriod":"09","Sold":"510020.86"},{"FiscalPeriod":"10","Sold":"325525.30"},{"FiscalPeriod":"11","Sold":"89214.27"}];
    var month = [];
    var sold = [];

    for (var i in data) {
      month.push(data[i].FiscalPeriod);
      sold.push(data[i].Sold);
    }

    var chartdata = {
      type: 'line',
      data: {
        labels: month,
        datasets: [
          {
            label: '2017',
            data: sold,
            backgroundColor: '#26B99A',
          }
        ]
      },
    }
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, chartdata);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body></code>```

Body:
I am new to chartjs. After spend some time checking tutorials I came up codes as following and it's giving me undefined result both x and y axis. I can manage to get static data working i.e. if put down month on y-axis and charts display fine. Any help is greatly appreciated. By the way I am using chartjsversion 2.1.4.

data.php:

<?php
//setting header to json
header('Content-Type: application/json');
include_once 'includes/db_connect.php';

$query = sprintf("SELECT FiscalPeriod, SUM(DollarsSold) AS Sold
                  FROM ar_customersalespersonhistory
                  WHERE FiscalYear = '2017'
                  GROUP BY FiscalPeriod
                  ORDER BY FiscalPeriod
                ");

//execute query
$result = $connection->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$connection->close();

//now print the data
print json_encode($data);

?>

Output from data.php:

[{
  "FiscalPeriod": "01",
  "Sold": "357508.03"
}, {
  "FiscalPeriod": "02",
  "Sold": "393790.14"
}, {
  "FiscalPeriod": "03",
  "Sold": "407346.07"
}, {
  "FiscalPeriod": "04",
  "Sold": "557704.12"
}, {
  "FiscalPeriod": "05",
  "Sold": "555916.68"
}, {
  "FiscalPeriod": "06",
  "Sold": "422659.26"
}, {
  "FiscalPeriod": "07",
  "Sold": "297766.49"
}, {
  "FiscalPeriod": "08",
  "Sold": "448256.07"
}, {
  "FiscalPeriod": "09",
  "Sold": "510020.86"
}, {
  "FiscalPeriod": "10",
  "Sold": "325525.30"
}, {
  "FiscalPeriod": "11",
  "Sold": "89214.27"
}]

And javascript:

$(document).ready(function() {
  $.ajax({
    url: '/registration/sales_general.php',
    method: 'GET',
    // dataType: 'json',
    success: function(data) {
      // console.log(data);
      var month = [];
      var sold = [];

      for (var i in data) {
        month.push(data[i].FiscalPeriod);
        sold.push(data[i].Sold);
      }

      console.log(month);
      console.log(sold);
      var chartdata = {
        // labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        labels: month,
        datasets: [{
          label: '2017',
          backgroundColor: '#26B99A',
          // data: [33,24,25,19,46,99,21]
          data: sold
        }]
      };

      var ctx = $('#mybarChart1');
      ctx.height = 70;

      var barGraph = new Chart(ctx, {
        type: 'bar',
        data: chartdata
      });
    },
    error: function(data) {
      console.log(data);
    }
  });
});

Body:
Your chartdata object doesn't contain valid ChartJS options

This should work:

    var data = [{"FiscalPeriod":"01","Sold":"357508.03"},{"FiscalPeriod":"02","Sold":"393790.14"},{"FiscalPeriod":"03","Sold":"407346.07"},{"FiscalPeriod":"04","Sold":"557704.12"},{"FiscalPeriod":"05","Sold":"555916.68"},{"FiscalPeriod":"06","Sold":"422659.26"},{"FiscalPeriod":"07","Sold":"297766.49"},{"FiscalPeriod":"08","Sold":"448256.07"},{"FiscalPeriod":"09","Sold":"510020.86"},{"FiscalPeriod":"10","Sold":"325525.30"},{"FiscalPeriod":"11","Sold":"89214.27"}];
    var month = [];
    var sold = [];

    for (var i in data) {
      month.push(data[i].FiscalPeriod);
      sold.push(data[i].Sold);
    }

    var chartdata = {
      type: 'line',
      data: {
        labels: month,
        datasets: [
          {
            label: '2017',
            data: sold,
            backgroundColor: '#26B99A',
          }
        ]
      },
    }
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, chartdata);

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>


问:
Save Facebook credentials on React Native and Firebase
I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().

My first question is: does the FBSDK do this automatically? If not, how can I do this?

I have this code for Facebook Auth:

```<code>facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
  function(result) {
    if (result.isCancelled) {
      alert('Inicio de sesión cancelado');
    } else {
      AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
        const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
        Firebase.auth().signInWithCredential(credential).then((result) =>{
          return callback;
        }, (error) =>{
          console.log('Error en firebase' + error);
        });
      }, (error) =>{
        console.log('ACCESS TOKEN ERROR: ' + error);
      });
    }
  },
  function(error) {
    console.log('Login failed with error: ' + error);
  }
);
</code>```

}

The code works perfectly, thanks in advance.

答:
With React Native you can use Asyncstorage, which is basically what localstorage is for the web realm: a key-value pair mini-database.

Actually, you can retrieve the currently logged in user using Firebase's firebase.auth().currentUser. Maybe you can check on app startup if it returns a valid user object.

Body:
I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().

My first question is: does the FBSDK do this automatically? If not, how can I do this?

I have this code for Facebook Auth:

facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
  function(result) {
    if (result.isCancelled) {
      alert('Inicio de sesión cancelado');
    } else {
      AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
        const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
        Firebase.auth().signInWithCredential(credential).then((result) =>{
          return callback;
        }, (error) =>{
          console.log('Error en firebase' + error);
        });
      }, (error) =>{
        console.log('ACCESS TOKEN ERROR: ' + error);
      });
    }
  },
  function(error) {
    console.log('Login failed with error: ' + error);
  }
);

}

The code works perfectly, thanks in advance.


问:
Javascript - push children to array, appendChild the array to other DOM element effects the childrens list?
So I have a list of children from a DOM element. I take the child list and push it to an empty array. When I appendChild the array elements one by one, why does it change the position of the children elements? Shouldn't it effect only the array?</p>

```<code>var listItemsContainer = document.getElementById("$content_id");
var items = listItemsContainer.children;
var itemsArr = [];
var continentcontainer = document.getElementById('continents');

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

itemsArr.sort(function(a, b) { //sorting itemsArr (array of listItems) A to Z
  return a.innerHTML == b.innerHTML ?
    0 :
    (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (var i = 0; i < itemsArr.length; ++i) {
  continentcontainer.appendChild(itemsArr[i]); //append child moves item from current location into new location
}
</code>```

答:
Your array cannot hold DOM Elements, only their respective pointers.

The order of these pointers in your array has no significance to DOM. It's like keeping a list of people in the room. Some may change their positions and others may even leave - but your list will stay as is, and counting people that are no longer in the room and will no longer reflect their order in your list.

You are trying to sort (reorder) your DOM elements by pushing their references in an array - that's not possible.

This answer has been answered here:  Why doesn't htmlCollection inherit from array

And here is the way to sort DOM Elements using Array:
JavaScript sorting issue with looping

Body:
So I have a list of children from a DOM element. I take the child list and push it to an empty array. When I appendChild the array elements one by one, why does it change the position of the children elements? Shouldn't it effect only the array?

var listItemsContainer = document.getElementById("$content_id");
var items = listItemsContainer.children;
var itemsArr = [];
var continentcontainer = document.getElementById('continents');

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

itemsArr.sort(function(a, b) { //sorting itemsArr (array of listItems) A to Z
  return a.innerHTML == b.innerHTML ?
    0 :
    (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (var i = 0; i < itemsArr.length; ++i) {
  continentcontainer.appendChild(itemsArr[i]); //append child moves item from current location into new location
}


问:
Translating a form/input on the Z-axis
When translating a form/input on the Z-axis, the area that accepts the cursor isn't brought forward in Z space with the apparent place of the element, and trying to click on the input box doesn't work unless you click where the element would be if it hadn't been translated. Is there any way to fix this?

HTML

```<code><html>
<body>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../../css/client-questionaire.css" type="text/css">

<div id="impress" data-transition-duration="3000">

    <div id="yourself" class="step page" data-x="0">
            <div class="innerDiv">
                <p class="mainWord">
                    <span class="textLength">
                        <span class="black">YOUR</span><span class="white">SELF</span>
                    </span>
                </p>
                <div class="wrap">
                    <div class="formBox">
                        <form id="yourselfForm" class="form">

                            <label for="firstName">
                                What's your <u>first name</u>?
                            </label><br>
                            <input name="firstName" type="text" ><br>

                            <label for="lastName">
                                What's your <u>last name</u>?
                            </label><br>
                            <input name="lastName" type="text" ><br>

                            <label for="currentJob">
                                What's your <u>current job title</u>?
                            </label><br>
                            <input name="currentJob" type="text" ><br>

                        </form>
                    </div>
                </div>
            </div>
    </div>
   <div id="intro" class="step page" data-x="2000">
        <div class="outerDiv">
            <div class="innerDiv">
                <p class="mainWord"><span class="black first">CREÆTIVE</span> <span class="white last">BRIEF</span></p>

                <div class="formBox">
                </div>
             </div>
        </div>
    </div>
    <div id="lookFeel" class="step page" data-x="4000">
        <div class="outerDiv">
            <div class="innerDiv">
                <p class="mainWord"><span class="black firstSpan">LOOK</span> <span class="white secondSpan">&</span><span class="black"> FEEL</span></p>

                <div class="formBox">
                </div>
             </div>
        </div>
    </div>
<script src="/js/impress.js"></script>
<script>
impress().init();
</script>
</code>```

CSS

```<code>body {
    background: #cc9933;
}

.page {
    height: 830px;
    width: 1480px;
    margin: 0px;
}

.formBox {
    position:absolute;
    border: 1px solid black;
    height: 450px;
    width: 270px;
    top: -150px;
    left: 867px;
    z-index: 21;
    background: #cc9933;
    transform: translateZ(300px);
}

.innerDiv {
    position:absolute;
    z-index: 9;
    width: 1000%;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
    top:40%;
    height: 108px;
}

.frontFiller {
    transform: translateX(-2000px);
    width: 1000%;
}

.mainWord {
    margin: 0px 50px;
    font-size: 90px;
    height: 100%;
}

.black {
    color: black;
}

.white {
    color: white;
}
</code>```

答:
Not sure what you're trying to achieve, your example moves the input outside of the viewport and the translation isn't working at all.

So, I'll take a guess: Have you tried setting the CSS property perspective on the parent of .formBox?

Here's an example that shows how it would work:

.wrapper {
    perspective: 50px;
    transform-style:preserve-3d;
}
.formBox {
    position:absolute;
    border: 1px solid black;
    height: 450px;
    width: 270px;
    left: 200px;
    z-index: 21;
    background: #cc9933;
    -webkit-transform: translateZ(30px);
    transform: translateZ(30px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="formBox">
    <form id="yourselfForm" class="form">
        <label for="firstName">
        What's your <u>first name</u>?
        </label><br>
        <input name="firstName" type="text" >
    </form>
</div>
</div></code>```

Title: Translating a form/input on the Z-axis

Body:
When translating a form/input on the Z-axis, the area that accepts the cursor isn't brought forward in Z space with the apparent place of the element, and trying to click on the input box doesn't work unless you click where the element would be if it hadn't been translated. Is there any way to fix this?

HTML

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../../css/client-questionaire.css" type="text/css">

                        YOURSELF

                        <form id="yourselfForm" class="form">

                                What's your first name?

                            <input name="firstName" type="text" >

                                What's your last name?

                            <input name="lastName" type="text" >

                                What's your current job title?

                            <input name="currentJob" type="text" >

                        </form>

CREÆTIVE BRIEF

LOOK & FEEL

CSS

body {
    background: #cc9933;
}

.page {
    height: 830px;
    width: 1480px;
    margin: 0px;
}

.formBox {
    position:absolute;
    border: 1px solid black;
    height: 450px;
    width: 270px;
    top: -150px;
    left: 867px;
    z-index: 21;
    background: #cc9933;
    transform: translateZ(300px);
}

.innerDiv {
    position:absolute;
    z-index: 9;
    width: 1000%;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
    top:40%;
    height: 108px;
}

.frontFiller {
    transform: translateX(-2000px);
    width: 1000%;
}

.mainWord {
    margin: 0px 50px;
    font-size: 90px;
    height: 100%;
}

.black {
    color: black;
}

.white {
    color: white;
}

Body:
Not sure what you're trying to achieve, your example moves the input outside of the viewport and the translation isn't working at all.

So, I'll take a guess: Have you tried setting the CSS property perspective on the parent of .formBox?

Here's an example that shows how it would work:

.wrapper {
    perspective: 50px;
    transform-style:preserve-3d;
}
.formBox {
    position:absolute;
    border: 1px solid black;
    height: 450px;
    width: 270px;
    left: 200px;
    z-index: 21;
    background: #cc9933;
    -webkit-transform: translateZ(30px);
    transform: translateZ(30px);
}

<div class="wrapper">
<div class="formBox">
    <form id="yourselfForm" class="form">
        <label for="firstName">
        What's your <u>first name</u>?
        </label><br>
        <input name="firstName" type="text" >
    </form>
</div>
</div>


问:
How can I use the name of a string in the form of a string variable to retrieve that string from the XML files?
I want to use the string's name or label in the form of a string variable to retrieve that string from R.string.nameOfString but can't figure out how. In the method getText() which is used to get the string, it takes "resource id for the string as a parameter," and the resource id is an int. I'm not sure how the path in a string variable can be converted to this resource id so I can retrieve that string from the XML file.

答:
You can use the getResources().getIdentifier(String name, String defType, String defPackage) method.

Code to access a String Resource

```<code>int resId = getResources().getIdentifier("string_name", "string", getPackageName());
String str = getString(resId);
Log.i(LOG_TAG, "Res String : " + str);
</code>```

Body:
You can use the getResources().getIdentifier(String name, String defType, String defPackage) method.

Code to access a String Resource

int resId = getResources().getIdentifier("string_name", "string", getPackageName());
String str = getString(resId);
Log.i(LOG_TAG, "Res String : " + str);


问:
Ifelse in R with multiple categorical conditions
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

```<code>dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]
</code>```

I'm using this to run linear model about sales.

答:
```<code>language_options <- c("english", "french", "spanish", ...)
dt.train2[, language_string := match(language, language_options)]
</code>```

Body:
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]

I'm using this to run linear model about sales.