问:
Nested map is not rendering the Redux State Correctly
I am new to react js. I am creating a comparison between user typing and actual sentence to be typed Somehow I am able to achieve this but It is not perfect like nested map is not rendering properly if letter typed correctly it should render green background My state is updated properly But my nested map Kinda not working there is a delay

Component Code

```<code> renderLine = () => {
    let test = this.props.test.get('master')
   return test.map(line => {
       return line.check.map( (ltr,i) =>  ltr.status ? <span key={i} className="correct">{ltr.letter}</span> : ltr.letter )
   })

};
handleKeyPress = e => {
    if(e.charCode === 32) {
        this.setState({
            pushToNext:true,
            currentTyping:""
        })
    }
};
handleInput = e => {
    if(e.target.value !== " "){
        let {storeValue} = this.state;
        console.log(storeValue.length);
        let updatedWord = e.target.value;
        let updateArr = [];
        if(storeValue.length  ===  0){
            updateArr = storeValue.concat(updatedWord)
        }else {
            if(this.state.pushToNext){
                updateArr = storeValue.concat(updatedWord)
            }else {
                storeValue.pop();
                updateArr = storeValue.concat(updatedWord);
            }
        }
        this.setState({
            currentTyping:updatedWord,
            storeValue:updateArr,
            pushToNext:false
        },() => {

            let {storeValue} = this.state
            let lastWordIndex = storeValue.length === 0 ? storeValue.length : storeValue.length - 1;
            let lastLetterIndex = storeValue[lastWordIndex].length === 0 ? storeValue[lastWordIndex].length : storeValue[lastWordIndex].length - 1;
            let lastWordValue = storeValue[lastWordIndex];
            let lastLetterValue = lastWordValue[lastLetterIndex];

            // console.log(lastWordIndex,lastLetterIndex,lastWordValue,lastLetterValue,"After tstae")
            return this.props.compareCurrentTextWithMater(lastWordIndex,lastLetterIndex,lastWordValue,lastLetterValue)

        });

    }

};
</code>```

Redux Reducer

```<code>import {FETCH_USER_TYPING_TEXT,COMPARE_TEXT_WITH_MASTER} from "../actions/types";
import {fromJS} from 'immutable';

const initialState = fromJS({
    text:null,
    master:[],
    inputBoxStatus:false
});

export default function (state = initialState,action) {
    switch (action.type){
        case FETCH_USER_TYPING_TEXT:
            return setTextManipulated(state,action);
        case COMPARE_TEXT_WITH_MASTER:
            return compareTextWithMaster(state,action)
        default:
            return state
    }
}

const compareTextWithMaster = (state,action) => {

    let {lastWordIndex,lastLetterIndex,lastLetterValue} = action;
    let masterWord = state.get('master')[lastWordIndex];
    let masterLetter = masterWord.check[lastLetterIndex];
    let newState = state.get('master');

    if(typeof masterLetter !== "undefined"){
        if(masterLetter.letter === lastLetterValue){
            masterWord.check[lastLetterIndex].status = true;
            newState[lastWordIndex] = masterWord;
            return state.set('master',newState)
        }else {
            masterWord.check[lastLetterIndex].status = false;
            newState[lastWordIndex] = masterWord;
            return state.set('master',newState)
        }

    }else {
        console.log('Undefinedd  Set Eroing or wrong Space Chratced set Box Red Colot',newState);

    }

};
</code>```

UPDATE

I did the same Logic with plain React.js it works Perfectly and nested map rendering the if else logic properly there is no on letter delay

https://codesandbox.io/s/zx3jkxk8o4

But the same logic with Redux State with immutable js Does'nt take effect with nested loop if else statement I don't know where the problem Relies ..and My Code  Snippet will be little bit different from CodeSanbox COde But the Logic is Same

答:
Probably, the diffing algorithm of react does see that oldState === newState and skips the re rendering. To avoid that situation, use a new object in the root of the state so that the above check returns false. I see that you use immutableJs, so maybe force re-render with componentShouldUpdate method instead.

Also consider using dev tools to step through the code line by line to see what is going on.

If nothing at all works, switch to something simpler with less dependencies and go from there, incrementally adding what you need.

Body:
I am new to react js. I am creating a comparison between user typing and actual sentence to be typed Somehow I am able to achieve this but It is not perfect like nested map is not rendering properly if letter typed correctly it should render green background My state is updated properly But my nested map Kinda not working there is a delay

Component Code

 renderLine = () => {
    let test = this.props.test.get('master')
   return test.map(line => {
       return line.check.map( (ltr,i) =>  ltr.status ? {ltr.letter} : ltr.letter )
   })

};
handleKeyPress = e => {
    if(e.charCode === 32) {
        this.setState({
            pushToNext:true,
            currentTyping:""
        })
    }
};
handleInput = e => {
    if(e.target.value !== " "){
        let {storeValue} = this.state;
        console.log(storeValue.length);
        let updatedWord = e.target.value;
        let updateArr = [];
        if(storeValue.length  ===  0){
            updateArr = storeValue.concat(updatedWord)
        }else {
            if(this.state.pushToNext){
                updateArr = storeValue.concat(updatedWord)
            }else {
                storeValue.pop();
                updateArr = storeValue.concat(updatedWord);
            }
        }
        this.setState({
            currentTyping:updatedWord,
            storeValue:updateArr,
            pushToNext:false
        },() => {

            let {storeValue} = this.state
            let lastWordIndex = storeValue.length === 0 ? storeValue.length : storeValue.length - 1;
            let lastLetterIndex = storeValue[lastWordIndex].length === 0 ? storeValue[lastWordIndex].length : storeValue[lastWordIndex].length - 1;
            let lastWordValue = storeValue[lastWordIndex];
            let lastLetterValue = lastWordValue[lastLetterIndex];

            // console.log(lastWordIndex,lastLetterIndex,lastWordValue,lastLetterValue,"After tstae")
            return this.props.compareCurrentTextWithMater(lastWordIndex,lastLetterIndex,lastWordValue,lastLetterValue)

        });

    }

};

Redux Reducer

import {FETCH_USER_TYPING_TEXT,COMPARE_TEXT_WITH_MASTER} from "../actions/types";
import {fromJS} from 'immutable';

const initialState = fromJS({
    text:null,
    master:[],
    inputBoxStatus:false
});

export default function (state = initialState,action) {
    switch (action.type){
        case FETCH_USER_TYPING_TEXT:
            return setTextManipulated(state,action);
        case COMPARE_TEXT_WITH_MASTER:
            return compareTextWithMaster(state,action)
        default:
            return state
    }
}

const compareTextWithMaster = (state,action) => {

    let {lastWordIndex,lastLetterIndex,lastLetterValue} = action;
    let masterWord = state.get('master')[lastWordIndex];
    let masterLetter = masterWord.check[lastLetterIndex];
    let newState = state.get('master');

    if(typeof masterLetter !== "undefined"){
        if(masterLetter.letter === lastLetterValue){
            masterWord.check[lastLetterIndex].status = true;
            newState[lastWordIndex] = masterWord;
            return state.set('master',newState)
        }else {
            masterWord.check[lastLetterIndex].status = false;
            newState[lastWordIndex] = masterWord;
            return state.set('master',newState)
        }

    }else {
        console.log('Undefinedd  Set Eroing or wrong Space Chratced set Box Red Colot',newState);

    }

};

UPDATE

I did the same Logic with plain React.js it works Perfectly and nested map rendering the if else logic properly there is no on letter delay

https://codesandbox.io/s/zx3jkxk8o4

But the same logic with Redux State with immutable js Does'nt take effect with nested loop if else statement I don't know where the problem Relies ..and My Code  Snippet will be little bit different from CodeSanbox COde But the Logic is Same


来源: stackexchange

问:
D3 Topojson Adding Name Property to FeatureCollection
I have hard-coded a merged multipolygon region by filtering the desired FIPS ids like so:

```<code>var set1 = d3.set([
  48111, 48421, 48195, 48357, 48295, 48205, 48341, 48233, 48393, 48211,
  48359, 48375, 48065, 48179, 48483, 48485, 48077, 48337, 48237, 48009,
  48503, 48023, 48269, 48125, 48107, 48303, 48219, 48079, 48501, 48445,
  48117, 48381, 48011, 48129, 48087, 48369, 48069, 48437, 48045, 48191,
  48075, 48017, 48279, 48189, 48153, 48345, 48101, 48155, 48197, 48487,
  48305, 48169
]);

var region1 = {type: "FeatureCollection", features: counties.filter(function(d) {return set1.has(d.id); })};
</code>```

My question is: If I wish to add a name property for this region, how would I proceed? I'm thinking to declare something with the region variable, maybe something like:

```<code>var region1 = {type: "FeatureCollection", properties: 'Name': 'My Region', features: counties.filter(function(d) {return set1.has(d.id); })};
</code>```

答:
What you have...

```<code>properties: 'Name': 'My Region'
</code>```

... is not a valid JavaScript Object. It should be:

```<code>var region1 = {
    type: "FeatureCollection",
    name: 'My Region',
    features: counties.filter(function(d) {
        return set1.has(d.id);
    })
};
</code>```

Or, if you want them inside the properties property:

```<code>var region1 = {
    type: "FeatureCollection",
    properties: {
        name: 'My Region',
        features: counties.filter(function(d) {
            return set1.has(d.id);

        })
    }
};
</code>```

Also, the convention in JavaScript is using lowercase for property names, so I advise you to use name, not Name.

Here is a Bostock's bl.ocks with your object, look at the console: https://bl.ocks.org/anonymous/3fb65e6b6204e5731afc4152a35a0179/0d579d98e599cef73284c5e89b92e7fe94be42ab

ContentLicense: CC BY-SA 3.0

Body:
I have hard-coded a merged multipolygon region by filtering the desired FIPS ids like so:

var set1 = d3.set([
  48111, 48421, 48195, 48357, 48295, 48205, 48341, 48233, 48393, 48211,
  48359, 48375, 48065, 48179, 48483, 48485, 48077, 48337, 48237, 48009,
  48503, 48023, 48269, 48125, 48107, 48303, 48219, 48079, 48501, 48445,
  48117, 48381, 48011, 48129, 48087, 48369, 48069, 48437, 48045, 48191,
  48075, 48017, 48279, 48189, 48153, 48345, 48101, 48155, 48197, 48487,
  48305, 48169
]);

var region1 = {type: "FeatureCollection", features: counties.filter(function(d) {return set1.has(d.id); })};

My question is: If I wish to add a name property for this region, how would I proceed? I'm thinking to declare something with the region variable, maybe something like:

var region1 = {type: "FeatureCollection", properties: 'Name': 'My Region', features: counties.filter(function(d) {return set1.has(d.id); })};

Body:
What you have...

properties: 'Name': 'My Region'

... is not a valid JavaScript Object. It should be:

var region1 = {
    type: "FeatureCollection",
    name: 'My Region',
    features: counties.filter(function(d) {
        return set1.has(d.id);
    })
};

Or, if you want them inside the properties property:

var region1 = {
    type: "FeatureCollection",
    properties: {
        name: 'My Region',
        features: counties.filter(function(d) {
            return set1.has(d.id);

        })
    }
};

Also, the convention in JavaScript is using lowercase for property names, so I advise you to use name, not Name.

Here is a Bostock's bl.ocks with your object, look at the console: https://bl.ocks.org/anonymous/3fb65e6b6204e5731afc4152a35a0179/0d579d98e599cef73284c5e89b92e7fe94be42ab


问:
Padleft on numericupdown
I would like to use a numericupdown control on my application. I'm well aware that I could use a plain textbox instead, but I rather like the way this particular control's UI fits with what I'm doing in my application.

It also needs to have 0's at the left, per desired text output. If I'm not mistaken, this is not supported by standard numericupdown controls. It should never exceed 4 digits in length. However, if I input more, it must show favor to new keystrokes and drop left-most digits instead. The up and down arrows should increment/decrement the value per usual behavior. Even after keying in values.

It should never be allowed to run negative. It should only accept whole integers. This is easily handled by the stock functionality though.

答:
Partly posting an answer for others who may follow. Partly looking for assurance that I'm not being an idiot.

Note that this hack depends on firing Sync() before extracting the final value. The timer will fire pretty quickly, but does not guarantee that things will happen in the correct order. It may not hurt to manually trigger Sync() immediately before extracting values.

```<code>public class UpDownWith0 : System.Windows.Forms.NumericUpDown
{

  private System.Windows.Forms.Timer addzeros = new System.Windows.Forms.Timer();

  public UpDownWith0()
  {
    this.addzeros.Interval = 500; //Set delay to allow multiple keystrokes before we start doing things
    this.addzeros.Stop();
    this.addzeros.Tick += new System.EventHandler(this.Sync);
  }

  protected override void OnTextBoxTextChanged(object source, System.EventArgs e)
  {
    this.addzeros.Stop(); //reset the elapsed time every time the event fires, handles multiple quick proximity changes as if they were one
    this.addzeros.Start();
  }

  public void Sync(object sender, System.EventArgs e)
  {
    int val;
    this.addzeros.Stop();
    if (this.Text.Length > 4)
    {
      //I never want to allow input over 4 digits in length. Chop off leftmost values accordingly
      this.Text = this.Text.Remove(0, this.Text.Length - 4);
    }
    int.TryParse(this.Text, out val); //could use Value = int.Parse() here if you preferred to catch the exceptions. I don't.
    if (val > this.Maximum) { val = (int)this.Maximum; }
    else if (val < this.Minimum) { val = (int)this.Minimum; }
    this.Value = val; //Now we can update the value so that up/down buttons work right if we go back to using those instead of keying in input

    this.Text = val.ToString().PadLeft(4, '0'); //IE: display will show 0014 instead of 14
    this.Select(4, 0); //put cursor at end of string, otherwise it moves to the front. Typing more values after the timer fires causes them to insert at the wrong place
  }
}
</code>```

Title: Padleft on numericupdown

Body:
Partly posting an answer for others who may follow. Partly looking for assurance that I'm not being an idiot.

Note that this hack depends on firing Sync() before extracting the final value. The timer will fire pretty quickly, but does not guarantee that things will happen in the correct order. It may not hurt to manually trigger Sync() immediately before extracting values.

public class UpDownWith0 : System.Windows.Forms.NumericUpDown
{

  private System.Windows.Forms.Timer addzeros = new System.Windows.Forms.Timer();

  public UpDownWith0()
  {
    this.addzeros.Interval = 500; //Set delay to allow multiple keystrokes before we start doing things
    this.addzeros.Stop();
    this.addzeros.Tick += new System.EventHandler(this.Sync);
  }

  protected override void OnTextBoxTextChanged(object source, System.EventArgs e)
  {
    this.addzeros.Stop(); //reset the elapsed time every time the event fires, handles multiple quick proximity changes as if they were one
    this.addzeros.Start();
  }

  public void Sync(object sender, System.EventArgs e)
  {
    int val;
    this.addzeros.Stop();
    if (this.Text.Length > 4)
    {
      //I never want to allow input over 4 digits in length. Chop off leftmost values accordingly
      this.Text = this.Text.Remove(0, this.Text.Length - 4);
    }
    int.TryParse(this.Text, out val); //could use Value = int.Parse() here if you preferred to catch the exceptions. I don't.
    if (val > this.Maximum) { val = (int)this.Maximum; }
    else if (val < this.Minimum) { val = (int)this.Minimum; }
    this.Value = val; //Now we can update the value so that up/down buttons work right if we go back to using those instead of keying in input

    this.Text = val.ToString().PadLeft(4, '0'); //IE: display will show 0014 instead of 14
    this.Select(4, 0); //put cursor at end of string, otherwise it moves to the front. Typing more values after the timer fires causes them to insert at the wrong place
  }
}


问:
Can't add new cells using dynamically added buttons using jQuery
I have HTML file with JavaScript code inside, which should add new cell to table with button when user click on any other buttons in document with class name addCell:

```<code><!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $('.addCell').click(function() {
        addNewRow(this);
    });
});
function addNewRow(Sender)
{
    var tbl = document.getElementById('testt');
    var r = tbl.insertRow(tbl.rows.length);
    var c1 = r.insertCell(0);
    c1.className = "addCell";
    c1.innerHTML = "<button class=\"addCell\">New cell by " + Sender.innerHTML + "</button>";
}
</script>
</head>
<body>
<table border="1" id="testt">
    <tr>
        <td><button class="addCell">AddNew 1</button></td>
    </tr>
    <tr>
        <td><button class="addCell">AddNew 2</button></td>
    </tr>
</table>
</body>
</html>
</code>```

When I click on the buttons with class addCell, saved in HTML document in design time, my code work well done.

But when I click on new buttons, added by my script in run time, with same class name, nothing happens.

I use class name, for add buttons by jQuery, onclick method, because, number of buttons is unlimited, and writing to all buttons, attribute onclick with name of function, is not the best way to optimize personal code.

What I make incorrect?
Please help me to change this code for well and right work.

答:
I think you need to use event delegation for dynamic appended elements
https://learn.jquery.com/events/event-delegation/

Instead of

```<code>$('.addCell').click(function() {
    addNewRow(this);
});
</code>```

try this

```<code>$(document).on('click','.addCell',function(){
    foo();
});
</code>```

Body:
I have HTML file with JavaScript code inside, which should add new cell to table with button when user click on any other buttons in document with class name addCell:

<!DOCTYPE html>

        <button class="addCell">AddNew 1</button>

        <button class="addCell">AddNew 2</button>

When I click on the buttons with class addCell, saved in HTML document in design time, my code work well done.

But when I click on new buttons, added by my script in run time, with same class name, nothing happens.

I use class name, for add buttons by jQuery, onclick method, because, number of buttons is unlimited, and writing to all buttons, attribute onclick with name of function, is not the best way to optimize personal code.

What I make incorrect?
Please help me to change this code for well and right work.

Body:
I think you need to use event delegation for dynamic appended elements
https://learn.jquery.com/events/event-delegation/

Instead of

$('.addCell').click(function() {
    addNewRow(this);
});

try this

$(document).on('click','.addCell',function(){
    foo();
});


问:
InternalError: current transaction is aborted, commands ignored until end of transaction block ,on UNIQUE constraint

I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

```<code>import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)
</code>```

答:
You can either modify your python function to rollback the transaction, or modify the sql to not insert a new row if a conflict occurs (postgresql versions 9.5+):

option 1:

```<code>def insert(self,title,author,year,isbn):
  try:
    self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
    self.con.commit()
  except:
    self.con.rollback()
      print("already exists..")
</code>```

option 2 (works for postgresql versions 9.5 or later):

```<code>def insert(self,title,author,year,isbn):
  try:
    self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s) ON CONFLICT DO NOTHING",(title,author,year,isbn))
    self.con.commit()
  except:
      print("already exists..")
</code>```

Body:
I tried to get executed with my except: statement... while attempt to oppose the functionality of UNIQUE constraint..But ended with exceptional error..
The Postgresql database table already contains the row that I have used in

db.insert("The News","AparnaKumar",1995,234569654)

but it works well on inserting unrepeated rows..

import psycopg2
class database:

    def __init__(self):

        self.con=psycopg2.connect("dbname='book_store' user='postgres' password='5283' host='localhost' port='5432' ")
        self.cur=self.con.cursor()
        self.cur.execute("CREATE TABLE if not exists books(id SERIAL PRIMARY KEY,title TEXT NOT NULL UNIQUE,author TEXT NOT NULL,year integer NOT NULL,isbn integer NOT NULL UNIQUE)")
        self.con.commit()

    def insert(self,title,author,year,isbn):
      try:
        self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
        self.con.commit()
      except:
          print("already exists..")

    def view(self):
        self.cur.execute("SELECT * FROM books")
        rows=self.cur.fetchall()
        print(rows)

    def search(self,title=None,author=None,year=None,isbn=None):
        self.cur.execute("SELECT * FROM books WHERE title=%s or author=%s or year=%s or isbn=%s",(title,author,year,isbn))
        row=self.cur.fetchall()
        print(row)

db=database()
db.insert("The News","AparnaKumar",1995,234569654)
db.view()
db.search(year=1995)

Body:
You can either modify your python function to rollback the transaction, or modify the sql to not insert a new row if a conflict occurs (postgresql versions 9.5+):

option 1:

def insert(self,title,author,year,isbn):
  try:
    self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s)",(title,author,year,isbn))
    self.con.commit()
  except:
    self.con.rollback()
      print("already exists..")

option 2 (works for postgresql versions 9.5 or later):

def insert(self,title,author,year,isbn):
  try:
    self.cur.execute("INSERT INTO books(title,author,year,isbn) VALUES(%s,%s,%s,%s) ON CONFLICT DO NOTHING",(title,author,year,isbn))
    self.con.commit()
  except:
      print("already exists..")


问:
Problem with BufferedImage flickering
Hello I'm writing a small game and it's nearly finished, the only thing that doesn't work is the ImageBuffer. Every 10 miliseconds I call the method repaint(). My paint() method is as follows:

```<code>private Graphics2D g2D;

public void paint (Graphics g) {
    BufferedImage bimage = ((Graphics2D)g).getDeviceConfiguration().createCompatibleImage(700, 600, Transparency.OPAQUE);
    g2D = bimage.createGraphics();
    g2D.setFont(font);
    for(Wall wall: walls){
        wall.paint(g2D);
    }
    g2D.setColor(Color.orange);
    paddle.paint(g2D);
    g2D.drawString(score + "", 150,50);
    g2D.drawString("record: "+topscore  , 350,50);
    g2D.setColor(Color.red);
    ball.paint(g2D);
    g.drawImage(bimage,0,0,this);
}
</code>```

But this doesn't seem to remove the flickering. I think somehow the screen is cleared before the bufferedimage starts being painted.
Can anyone help me with solving this problem?
thanks!

答:
I can't really tell what you are doing from the code posted, but I'm guessing that you are trying to paint some background image with some moving images on top. If so, then your approach is wrong.

You don't want to recreate the background image every time painting is invoked. Instead the buffered image should be created once outside of the paintComponent() method. Then when you repaint the component you first just paint the image (as the background). Then you paint the paddle and ball on top of the background.

Also another approach is to just use JLabels to represent your paddle and ball. Then to move the component you just change its location. Then only the old/new location of the component needs to be repainted instead of the entire background which is also more efficient.

ContentLicense: CC BY-SA 2.5

Title: Problem with BufferedImage flickering

Body:
Hello I'm writing a small game and it's nearly finished, the only thing that doesn't work is the ImageBuffer. Every 10 miliseconds I call the method repaint(). My paint() method is as follows:

private Graphics2D g2D;

public void paint (Graphics g) {
    BufferedImage bimage = ((Graphics2D)g).getDeviceConfiguration().createCompatibleImage(700, 600, Transparency.OPAQUE);
    g2D = bimage.createGraphics();
    g2D.setFont(font);
    for(Wall wall: walls){
        wall.paint(g2D);
    }
    g2D.setColor(Color.orange);
    paddle.paint(g2D);
    g2D.drawString(score + "", 150,50);
    g2D.drawString("record: "+topscore  , 350,50);
    g2D.setColor(Color.red);
    ball.paint(g2D);
    g.drawImage(bimage,0,0,this);
}

But this doesn't seem to remove the flickering. I think somehow the screen is cleared before the bufferedimage starts being painted.
Can anyone help me with solving this problem?
thanks!


问:
I cant pick up the carriage return in my program
These are the instructions for my program:

The first line on this file will hold a number indicating how many lines will follow. Every line after that will have a word and an integer on it. Fill up two arrays, one for the word and one for the integer. Once the arrays are filled, go to each element of the String array and print out that String the number of times the parallel number array says for it to print.

However, when I try to print out the answer, an error occurs, saying there's no line to pick up when reading from the file I'm supposed to.

```<code>    Scanner input = new Scanner(new File("parallel.txt"));
    int numLine = input.nextInt();

    int [] array = new int[numLine];
    String [] Stringarray = new String[numLine];

    for (int i = 0; i< numLine; i++)
        {
            Stringarray[i] = input.next();
            array[i] = input.nextInt();
            input.nextLine();
        }

    for (int i = 0; i<Stringarray.length; i++)
        {
            for (int a = 0; a<array[a]; a++)
                out.print(Stringarray[i] + " ");
            out.println();
        }

}
</code>```

}

答:
You want to print the String array element corresponding to the integer in the file

so you have an input file like below

```<code>3 //indicate the line number
string1 6
string2 7
string3 5
</code>```

and you are expecting an output like below

```<code>string1 string1 string1 string1 string1 string1
string2 string2 string2 string2 string2 string2 string2
string3 string3 string3 string3 string3
</code>```

I don't want to change your logic, you can use this for getting the output

```<code>for (int a = 0; a<array.length; a++)
 for(int k=0;k<array[a];k++)
  System.out.print(Stringarray[a] + " ");
 System.out.println()
</code>```

Stringarray[a]-> here we wont get any Arrayindexbound exception as the length of Stringarray and array are always same

Body:
These are the instructions for my program:

The first line on this file will hold a number indicating how many lines will follow. Every line after that will have a word and an integer on it. Fill up two arrays, one for the word and one for the integer. Once the arrays are filled, go to each element of the String array and print out that String the number of times the parallel number array says for it to print.

However, when I try to print out the answer, an error occurs, saying there's no line to pick up when reading from the file I'm supposed to.

    Scanner input = new Scanner(new File("parallel.txt"));
    int numLine = input.nextInt();

    int [] array = new int[numLine];
    String [] Stringarray = new String[numLine];

    for (int i = 0; i< numLine; i++)
        {
            Stringarray[i] = input.next();
            array[i] = input.nextInt();
            input.nextLine();
        }

    for (int i = 0; i<Stringarray.length; i++)
        {
            for (int a = 0; a<array[a]; a++)
                out.print(Stringarray[i] + " ");
            out.println();
        }

}

}

Body:
You want to print the String array element corresponding to the integer in the file

so you have an input file like below

3 //indicate the line number
string1 6
string2 7
string3 5

and you are expecting an output like below

string1 string1 string1 string1 string1 string1
string2 string2 string2 string2 string2 string2 string2
string3 string3 string3 string3 string3

I don't want to change your logic, you can use this for getting the output

for (int a = 0; a<array.length; a++)
 for(int k=0;k<array[a];k++)
  System.out.print(Stringarray[a] + " ");
 System.out.println()

Stringarray[a]-> here we wont get any Arrayindexbound exception as the length of Stringarray and array are always same


问:
Can I break an SQL statement with JOINs into smaller queries or optimize query?
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.</p>

```<code>SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`
</code>```

答:
This is similar to that by Gordon Linoff but I wanted to add a note on syntax you may need at some point. Standard behaviour for SQL is that all columns that do not involve an aggregation function [e.g. sum()] should be listed in the group by clause.

```<code>SELECT
      wp_quiz_users.Id
    , wp_quiz_users.SessionId
    , wp_quiz_users.Score
    , wp_quiz_users.Date
    , wp_quiz_users.Referrer
    , wp_quiz_users.ContactData
    , SUM(CASE WHEN qq.Category = 1 THEN qa.AnswerValue END) AS sectionone
    , SUM(CASE WHEN qq.Category = 2 THEN qa.AnswerValue END) AS sectiontwo
    , SUM(CASE WHEN qq.Category = 3 THEN qa.AnswerValue END) AS sectionthree
    , SUM(CASE WHEN qq.Category = 4 THEN qa.AnswerValue END) AS sectionfour
    , SUM(CASE WHEN qq.Category = 5 THEN qa.AnswerValue END) AS sectionfive
FROM wp_quiz_users qu
LEFT JOIN wp_quiz_users_answers qa ON qa.UserId = q.id
LEFT JOIN wp_quiz_questions qq ON qa.QuestionId = qq.id
GROUP BY
      wp_quiz_users.Id
    , wp_quiz_users.SessionId
    , wp_quiz_users.Score
    , wp_quiz_users.Date
    , wp_quiz_users.Referrer
    , wp_quiz_users.ContactData
;
</code>```

i.e. It is good practice to list out all the columns you need in the select clause, and also all the "non-aggregating" columns also listed in the group by clause.

IF you see a query using like this:

```<code>select * from sometable group by name
</code>```

Then that query relies an a non-standard MySQL extension that can be turned on or off. If that extension is turned off queries reliant on the extension will begin to fail. So, a prudent coder can avoid that potential problem by simply listing all the non-aggregating columns in the group by clause. see: https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html

Regarding the original query it contains many "correlated subqueries" inside the select clause, and as you have discovered that are awful for performance. Be on the lookout for these

```<code> select name
   , (select sum(value) from tablex
      where tablex.id = table1.id   -- the "correlation" of tablex to table1 is here
     )
 from table1
</code>```

Occasionally however they can be a decent option, so while thay are to be avoided most of the time we cannot just say never use them at all.

Body:
I have query that's breaking an area of my website. The site spins forever when attempting to load the following SQL statement! I'm fairly new to sql statements and this particular statement was created by another developer. Is there a way to optimize the following statement? Or break it up into smaller statements so that it will run more quickly? I'm at a loss! I appreciate any help.

SELECT
    `wp_quiz_users`.`Id`,
    `wp_quiz_users`.`SessionId`,
    `wp_quiz_users`.`Score`,
    `wp_quiz_users`.`Date`,
    `wp_quiz_users`.`Referrer`,
    `wp_quiz_users`.`ContactData`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 1) AS `SectionOne`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 2) AS `SectionTwo`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 3) AS `SectionThree`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 4) AS `SectionFour`,
    (SELECT
        SUM(`wp_quiz_users_answers`.`AnswerValue`)
    FROM
        `wp_quiz_users_answers`
    JOIN
        `wp_quiz_questions`
            ON `wp_quiz_users_answers`.`QuestionId` = `wp_quiz_questions`.`id`
    WHERE
        `wp_quiz_users_answers`.`UserId` = `wp_quiz_users`.`Id`
        AND `wp_quiz_questions`.`Category` = 5) AS `SectionFive`
FROM
    `wp_quiz_users`

Body:
This is similar to that by Gordon Linoff but I wanted to add a note on syntax you may need at some point. Standard behaviour for SQL is that all columns that do not involve an aggregation function [e.g. sum()] should be listed in the group by clause.

SELECT
      wp_quiz_users.Id
    , wp_quiz_users.SessionId
    , wp_quiz_users.Score
    , wp_quiz_users.Date
    , wp_quiz_users.Referrer
    , wp_quiz_users.ContactData
    , SUM(CASE WHEN qq.Category = 1 THEN qa.AnswerValue END) AS sectionone
    , SUM(CASE WHEN qq.Category = 2 THEN qa.AnswerValue END) AS sectiontwo
    , SUM(CASE WHEN qq.Category = 3 THEN qa.AnswerValue END) AS sectionthree
    , SUM(CASE WHEN qq.Category = 4 THEN qa.AnswerValue END) AS sectionfour
    , SUM(CASE WHEN qq.Category = 5 THEN qa.AnswerValue END) AS sectionfive
FROM wp_quiz_users qu
LEFT JOIN wp_quiz_users_answers qa ON qa.UserId = q.id
LEFT JOIN wp_quiz_questions qq ON qa.QuestionId = qq.id
GROUP BY
      wp_quiz_users.Id
    , wp_quiz_users.SessionId
    , wp_quiz_users.Score
    , wp_quiz_users.Date
    , wp_quiz_users.Referrer
    , wp_quiz_users.ContactData
;

i.e. It is good practice to list out all the columns you need in the select clause, and also all the "non-aggregating" columns also listed in the group by clause.

IF you see a query using like this:

select * from sometable group by name

Then that query relies an a non-standard MySQL extension that can be turned on or off. If that extension is turned off queries reliant on the extension will begin to fail. So, a prudent coder can avoid that potential problem by simply listing all the non-aggregating columns in the group by clause. see: https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html

Regarding the original query it contains many "correlated subqueries" inside the select clause, and as you have discovered that are awful for performance. Be on the lookout for these

 select name
   , (select sum(value) from tablex
      where tablex.id = table1.id   -- the "correlation" of tablex to table1 is here
     )
 from table1

Occasionally however they can be a decent option, so while thay are to be avoided most of the time we cannot just say never use them at all.


问:
PHP Laravel pass parameters as post data in redirect
After the registration was successful I wanted to pass all the data to a login route as POST. How do you do this in laravel 4?

I know I can just authenticate the user after registration but the login page has other parameters and more required authentication process.

So I wish to push the username and password entered in the registration process into the login process so it can go through with the other processes inside the login route. (ex. Token generation which requires post data of app_id and app_secret)

答:
add namespace on top of your class

```<code>use Redirect;
</code>```

add this code to your redirect stage.

```<code>return Redirect::route('route_name',['username' => $request->username,
                                     'password' => $request->password]);
</code>```

Body:
add namespace on top of your class

use Redirect;

add this code to your redirect stage.

return Redirect::route('route_name',['username' => $request->username,
                                     'password' => $request->password]);


问:
JSON Parsing of ADSB Data
Coding this using Wing IDE. When running my code, it opens up decoder.py and provides the following error: File "C:\Python27\Lib\json\decoder.py", line 367, in decode
  raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 341 - line 29 column 1 (char 340 - 15199)

I've looked around google and SO, but haven't been able to match a root cause to my specific example. Any ideas?

The end goal is to parse ADS-B data from adsbexchange.
For the record, I also replaced the final print line with something more simple like print parsed_json but the results were the same.

```<code>import json

json_string = """{"Id":3429058,"Rcvr":11182,"HasSig":true,"Sig":6,"Icao":"3452C2","Bad":false,"FSeen":"\/Date(1512567030924)\/","CMsgs":2,"AltT":0,"Tisb":false,"TrkH":false,"Sqk":"","VsiT":0,"WTC":0,"Species":0,"EngType":0,"EngMount":0,"Mil":false,"Cou":"Spain","HasPic":false,"Interested":false,"FlightsCount":0,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1},
{"Id":4509293,"Rcvr":13019,"HasSig":false,"Icao":"44CE6D","Bad":false,"Reg":"OO-SSM","FSeen":"\/Date(1512567029549)\/","TSecs":1,"CMsgs":1,"Alt":23700,"GAlt":23700,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A319","Mdl":"Airbus A319 112","Man":"Airbus","CNum":"1388","Op":"Brussels Airlines","OpIcao":"BEL","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Belgium","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2000"},
{"Id":4960709,"Rcvr":11071,"HasSig":true,"Sig":15,"Icao":"4BB1C5","Bad":false,"Reg":"TC-LNE","FSeen":"\/Date(1512567029189)\/","TSecs":1,"CMsgs":4,"Alt":41000,"GAlt":41000,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A333","Mdl":"Airbus A330 303","Man":"Airbus","CNum":"1706","Op":"Turkish Airlines","OpIcao":"THY","Sqk":"","VsiT":0,"WTC":3,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Turkey","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2015"},
{"Id":11260420,"Rcvr":11012,"HasSig":true,"Sig":30,"Icao":"ABD204","Bad":false,"Reg":"N8606C","FSeen":"\/Date(1512567029096)\/","TSecs":2,"CMsgs":1,"AltT":0,"Tisb":false,"TrkH":false,"Type":"B738","Mdl":" BOEING 737-8H4","Man":"Boeing","CNum":"35964","Op":"Southwest Airlines","OpIcao":"SWA","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"United States","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1},
"""

parsed_json = json.loads(json_string)

print(parsed_json['Type'])
</code>```

Title: JSON Parsing of ADSB Data

Body:
Coding this using Wing IDE. When running my code, it opens up decoder.py and provides the following error: File "C:\Python27\Lib\json\decoder.py", line 367, in decode
  raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 341 - line 29 column 1 (char 340 - 15199)

I've looked around google and SO, but haven't been able to match a root cause to my specific example. Any ideas?

The end goal is to parse ADS-B data from adsbexchange.
For the record, I also replaced the final print line with something more simple like print parsed_json but the results were the same.

import json

json_string = """{"Id":3429058,"Rcvr":11182,"HasSig":true,"Sig":6,"Icao":"3452C2","Bad":false,"FSeen":"\/Date(1512567030924)\/","CMsgs":2,"AltT":0,"Tisb":false,"TrkH":false,"Sqk":"","VsiT":0,"WTC":0,"Species":0,"EngType":0,"EngMount":0,"Mil":false,"Cou":"Spain","HasPic":false,"Interested":false,"FlightsCount":0,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1},
{"Id":4509293,"Rcvr":13019,"HasSig":false,"Icao":"44CE6D","Bad":false,"Reg":"OO-SSM","FSeen":"\/Date(1512567029549)\/","TSecs":1,"CMsgs":1,"Alt":23700,"GAlt":23700,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A319","Mdl":"Airbus A319 112","Man":"Airbus","CNum":"1388","Op":"Brussels Airlines","OpIcao":"BEL","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Belgium","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2000"},
{"Id":4960709,"Rcvr":11071,"HasSig":true,"Sig":15,"Icao":"4BB1C5","Bad":false,"Reg":"TC-LNE","FSeen":"\/Date(1512567029189)\/","TSecs":1,"CMsgs":4,"Alt":41000,"GAlt":41000,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A333","Mdl":"Airbus A330 303","Man":"Airbus","CNum":"1706","Op":"Turkish Airlines","OpIcao":"THY","Sqk":"","VsiT":0,"WTC":3,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Turkey","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2015"},
{"Id":11260420,"Rcvr":11012,"HasSig":true,"Sig":30,"Icao":"ABD204","Bad":false,"Reg":"N8606C","FSeen":"\/Date(1512567029096)\/","TSecs":2,"CMsgs":1,"AltT":0,"Tisb":false,"TrkH":false,"Type":"B738","Mdl":" BOEING 737-8H4","Man":"Boeing","CNum":"35964","Op":"Southwest Airlines","OpIcao":"SWA","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"United States","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1},
"""

parsed_json = json.loads(json_string)

print(parsed_json['Type'])

Body:
Your json string is wrong. It contains an array of objects which should be within the square [] brackets.

Change your json string to

json_string = """[{"Id":3429058,"Rcvr":11182,"HasSig":true,"Sig":6,"Icao":"3452C2","Bad":false,"FSeen":"\/Date(1512567030924)\/","CMsgs":2,"AltT":0,"Tisb":false,"TrkH":false,"Sqk":"","VsiT":0,"WTC":0,"Species":0,"EngType":0,"EngMount":0,"Mil":false,"Cou":"Spain","HasPic":false,"Interested":false,"FlightsCount":0,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1},
{"Id":4509293,"Rcvr":13019,"HasSig":false,"Icao":"44CE6D","Bad":false,"Reg":"OO-SSM","FSeen":"\/Date(1512567029549)\/","TSecs":1,"CMsgs":1,"Alt":23700,"GAlt":23700,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A319","Mdl":"Airbus A319 112","Man":"Airbus","CNum":"1388","Op":"Brussels Airlines","OpIcao":"BEL","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Belgium","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2000"},
{"Id":4960709,"Rcvr":11071,"HasSig":true,"Sig":15,"Icao":"4BB1C5","Bad":false,"Reg":"TC-LNE","FSeen":"\/Date(1512567029189)\/","TSecs":1,"CMsgs":4,"Alt":41000,"GAlt":41000,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A333","Mdl":"Airbus A330 303","Man":"Airbus","CNum":"1706","Op":"Turkish Airlines","OpIcao":"THY","Sqk":"","VsiT":0,"WTC":3,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Turkey","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2015"},
{"Id":11260420,"Rcvr":11012,"HasSig":true,"Sig":30,"Icao":"ABD204","Bad":false,"Reg":"N8606C","FSeen":"\/Date(1512567029096)\/","TSecs":2,"CMsgs":1,"AltT":0,"Tisb":false,"TrkH":false,"Type":"B738","Mdl":" BOEING 737-8H4","Man":"Boeing","CNum":"35964","Op":"Southwest Airlines","OpIcao":"SWA","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"United States","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1}]
"""


问:
Add a class to the HTML  tag with React?
I'm making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

I could do this the old jQuery way by running some vanilla JavaScript which adds / removes a class, however this doesn't feel like the normal React philosophy.

Should I instead setState on my top level component to say whether the modal is open or closed? Even if I did this, as it's rendered into the div on the page it's still a side-effect to edit the body element, so is there any benefit for this extra wiring?

答:
Like what @brian mentioned, try having a top-level container component that wraps around your other components. (assuming you're not using redux in your app)

In this top-level component:

Add a boolean state (eg. modalOpen) to toggle the CSS class

Add methods (eg. handleOpenModal & handleCloseModal) to modify the boolean state.

Pass the methods created above as props into your <Modal /> component

ContentLicense: CC BY-SA 4.0

Title: Add a class to the HTML <body> tag with React?


问:
How to get the  in HTML tables to fit content, and let a specific  fill in the rest
This is a hypothetical example:

table, thead, tbody, tr { width: 100%; }
    table { table-layout: fixed }
    table > thead > tr > th { width: auto; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
      <thead>
        <tr>
          <th>Column A</th>
          <th>Column B</th>
          <th>Column C</th>
          <th class="absorbing-column">Column D</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Data A.1 lorem</td>
          <td>Data B.1 ip</td>
          <td>Data C.1 sum l</td>
          <td>Data D.1</td>
        </tr>
        <tr>
          <td>Data A.2 ipsum</td>
          <td>Data B.2 lorem</td>
          <td>Data C.2 some data</td>
          <td>Data D.2 a long line of text that is long</td>
        </tr>
        <tr>
          <td>Data A.3</td>
          <td>Data B.3</td>
          <td>Data C.3</td>
          <td>Data D.3</td>
        </tr>
      </tbody>
    </table></code>```

I want to have every single column's width to fit its content size, and leave the rest of the space for the one column with the "absorbing-column" class, so that it looks like this:

```<code>| HTML                                                                   | 100%
| body                                                                   | 100%
| table                                                                  | 100%
|------------------------------------------------------------------------|
| Column A | Column B       | Column C | Column D                        |
|------------------------------------------------------------------------|
| Column A | Column B lorem | Column C | Column D                        |
| Column A | Column B       | Column C | Column D                        |
| Column A | Column B       | Column C | Column D                        |
|------------------------------------------------------------------------|
</code>```

You see, Column B is a bit bigger than the rest due to the extra data in the first row, but Column D always uses up the remaining space.

I played around with max-width, min-width, auto, etc. and could not figure out how to make this work.

In other words, I want all columns to take whatever width they need and not more, and then I want Column D to use up all of the remaining space inside the 100% width table.

答:
use overflow:</p>

```<code>overflow: visible;
</code>```

Title: How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Body:
This is a hypothetical example:

table, thead, tbody, tr { width: 100%; }
    table { table-layout: fixed }
    table > thead > tr > th { width: auto; }

          Column A
          Column B
          Column C
          Column D

          Data A.1 lorem
          Data B.1 ip
          Data C.1 sum l
          Data D.1

          Data A.2 ipsum
          Data B.2 lorem
          Data C.2 some data
          Data D.2 a long line of text that is long

          Data A.3
          Data B.3
          Data C.3
          Data D.3

I want to have every single column's width to fit its content size, and leave the rest of the space for the one column with the "absorbing-column" class, so that it looks like this:

| HTML                                                                   | 100%
| body                                                                   | 100%
| table                                                                  | 100%
|------------------------------------------------------------------------|
| Column A | Column B       | Column C | Column D                        |
|------------------------------------------------------------------------|
| Column A | Column B lorem | Column C | Column D                        |
| Column A | Column B       | Column C | Column D                        |
| Column A | Column B       | Column C | Column D                        |
|------------------------------------------------------------------------|

You see, Column B is a bit bigger than the rest due to the extra data in the first row, but Column D always uses up the remaining space.

I played around with max-width, min-width, auto, etc. and could not figure out how to make this work.

In other words, I want all columns to take whatever width they need and not more, and then I want Column D to use up all of the remaining space inside the 100% width table.

Body:
use overflow:

overflow: visible;


问:
Passing multiple parameters to NodeJS callback using export module
Scenarios 1:

I have two file in my atom project weather.js and exmaple.js and  weather is using export module to export everything to example.js and  in turn example.js is using require module

my weather.js

```<code>var request = require('request');
module.exports= function(justAnothercallback)
{
    justAnothercallback('This is from weather');
}
</code>```

myExample.js

```<code>var fromWeather = require('./weather.js');
fromWeather(function(weather){
    console.log(weather);
});
</code>```

If I do Node myExample.js the output is :
This is from weather

Scenarios 2:
Now I just pass one more callback in my weather.js

```<code>module.exports= function(justAnothercallback, SecondCallback) {
    justAnothercallback('This is from weather');
    SecondCallback('This is second callback)');
}
</code>```

And my example.js is modified to accommodate the second callback function !!

```<code>var fromWeather = require('./weather.js');
fromWeather(function(weather, anotherfunc){
    console.log(weather);
    console.log(anotherfunc);
});
</code>```

From the terminal we get :

/>node example-callback.js
This is from weather
undefined
/Users/NodeCourse/async/weather.js:7
        SecondCallback('This is second callback)');
        ^

TypeError: SecondCallback is not a function
    at module.exports (/Users/oogway/NodeCourse/async/weath

My question is are they not the same , I just added one more callback and it barfed !! why !!?? but it works fine if I pass just one callback ..
Please help one this .

答:
In your code here, you are only passing one callback with two parameters

```<code>var fromWeather = require('./weather.js');
  fromWeather(function(weather, anotherfunc){
    console.log(weather);
    console.log(anotherfunc);
  });
</code>```

This is what two callbacks would look like

```<code>var fromWeather = require('./weather.js');
  fromWeather(function(){
    console.log('Hello from callback 1');
  }, function(){
    console.log('Hello from callback 2');
  });
</code>```

Body:
Scenarios 1:

I have two file in my atom project weather.js and exmaple.js and  weather is using export module to export everything to example.js and  in turn example.js is using require module

my weather.js

var request = require('request');
module.exports= function(justAnothercallback)
{
    justAnothercallback('This is from weather');
}

myExample.js

var fromWeather = require('./weather.js');
fromWeather(function(weather){
    console.log(weather);
});

If I do Node myExample.js the output is :
This is from weather

Scenarios 2:
Now I just pass one more callback in my weather.js

module.exports= function(justAnothercallback, SecondCallback) {
    justAnothercallback('This is from weather');
    SecondCallback('This is second callback)');
}

And my example.js is modified to accommodate the second callback function !!

var fromWeather = require('./weather.js');
fromWeather(function(weather, anotherfunc){
    console.log(weather);
    console.log(anotherfunc);
});

From the terminal we get :

/>node example-callback.js
This is from weather
undefined
/Users/NodeCourse/async/weather.js:7
        SecondCallback('This is second callback)');
        ^

TypeError: SecondCallback is not a function
    at module.exports (/Users/oogway/NodeCourse/async/weath

My question is are they not the same , I just added one more callback and it barfed !! why !!?? but it works fine if I pass just one callback ..
Please help one this .

Body:
In your code here, you are only passing one callback with two parameters

var fromWeather = require('./weather.js');
  fromWeather(function(weather, anotherfunc){
    console.log(weather);
    console.log(anotherfunc);
  });

This is what two callbacks would look like

var fromWeather = require('./weather.js');
  fromWeather(function(){
    console.log('Hello from callback 1');
  }, function(){
    console.log('Hello from callback 2');
  });


问:
Parse output from k6 data to get specific information
I am trying to extract data from a k6 output (https://docs.k6.io/docs/results-output):

```<code>data_received.........: 246 kB 21 kB/s
data_sent.............: 174 kB 15 kB/s
http_req_blocked......: avg=26.24ms  min=0s      med=13.5ms  max=145.27ms p(90)=61.04ms p(95)=70.04ms
http_req_connecting...: avg=23.96ms  min=0s      med=12ms    max=145.27ms p(90)=57.03ms p(95)=66.04ms
http_req_duration.....: avg=197.41ms min=70.32ms med=91.56ms max=619.44ms p(90)=288.2ms p(95)=326.23ms
http_req_receiving....: avg=141.82µs min=0s      med=0s      max=1ms      p(90)=1ms     p(95)=1ms
http_req_sending......: avg=8.15ms   min=0s      med=0s      max=334.23ms p(90)=1ms     p(95)=1ms
http_req_waiting......: avg=189.12ms min=70.04ms med=91.06ms max=343.42ms p(90)=282.2ms p(95)=309.22ms
http_reqs.............: 190    16.054553/s
iterations............: 5      0.422488/s
vus...................: 200    min=200 max=200
vus_max...............: 200    min=200 max=200
</code>```

The data comes in the above format and I am trying to find a way to get each line in the above along with the values only. As an example:

```<code>http_req_duration: 197.41ms, 70.32ms,91.56ms, 619.44ms, 288.2ms, 326.23ms
</code>```

I have to do this for ~50-100 files and want to find a RegEx or similar quicker way to do it, without writing too much code. Is it possible?

答:
Here's a simple Python solution:

```<code>import re

FIELD = re.compile(r"(\w+)\.*:(.*)", re.DOTALL)  # split the line to name:value
VALUES = re.compile(r"(?<==).*?(?=\s|$)")  # match individual values from http_req_* fields

# open the input file `k6_input.log` for reading, and k6_parsed.log` for parsing
with open("k6_input.log", "r") as f_in, open("k6_parsed.log", "w") as f_out:
    for line in f_in:  # read the input file line by line
        field = FIELD.match(line)  # first match all <field_name>...:<values> fields
        if field:
            name = field.group(1)  # get the field name from the first capture group
            f_out.write(name + ": ")  # write the field name to the output file
            value = field.group(2)  # get the field value from the second capture group
            if name[:9] == "http_req_":  # parse out only http_req_* fields
                f_out.write(", ".join(VALUES.findall(value)) + "\n")  # extract the values
            else:  # verbatim copy of other fields
                f_out.write(value)
        else:  # encountered unrecognizable field, just copy the line
            f_out.write(line)
</code>```

For a file with contents as above you'll get a resulting:

```data_received:  246 kB 21 kB/s
data_sent:  174 kB 15 kB/s
http_req_blocked: 26.24ms, 0s, 13.5ms, 145.27ms, 61.04ms, 70.04ms
http_req_connecting: 23.96ms, 0s, 12ms, 145.27ms, 57.03ms, 66.04ms
http_req_duration: 197.41ms, 70.32ms, 91.56ms, 619.44ms, 288.2ms, 326.23ms
http_req_receiving: 141.82µs, 0s, 0s, 1ms, 1ms, 1ms
http_req_sending: 8.15ms, 0s, 0s, 334.23ms, 1ms, 1ms
http_req_waiting: 189.12ms, 70.04ms, 91.06ms, 343.42ms, 282.2ms, 309.22ms
http_reqs:  190    16.054553/s
iterations:  5      0.422488/s
vus:  200    min=200 max=200
vus_max:  200    min=200 max=200```

If you have to run it over many files, I'd suggest you to investigate os.glob(), os.walk() or os.listdir() to list all the files you need and then loop over them and execute the above, thus further automating the process.

Body:
I am trying to extract data from a k6 output (https://docs.k6.io/docs/results-output):

data_received.........: 246 kB 21 kB/s
data_sent.............: 174 kB 15 kB/s
http_req_blocked......: avg=26.24ms  min=0s      med=13.5ms  max=145.27ms p(90)=61.04ms p(95)=70.04ms
http_req_connecting...: avg=23.96ms  min=0s      med=12ms    max=145.27ms p(90)=57.03ms p(95)=66.04ms
http_req_duration.....: avg=197.41ms min=70.32ms med=91.56ms max=619.44ms p(90)=288.2ms p(95)=326.23ms
http_req_receiving....: avg=141.82µs min=0s      med=0s      max=1ms      p(90)=1ms     p(95)=1ms
http_req_sending......: avg=8.15ms   min=0s      med=0s      max=334.23ms p(90)=1ms     p(95)=1ms
http_req_waiting......: avg=189.12ms min=70.04ms med=91.06ms max=343.42ms p(90)=282.2ms p(95)=309.22ms
http_reqs.............: 190    16.054553/s
iterations............: 5      0.422488/s
vus...................: 200    min=200 max=200
vus_max...............: 200    min=200 max=200

The data comes in the above format and I am trying to find a way to get each line in the above along with the values only. As an example:

http_req_duration: 197.41ms, 70.32ms,91.56ms, 619.44ms, 288.2ms, 326.23ms

I have to do this for ~50-100 files and want to find a RegEx or similar quicker way to do it, without writing too much code. Is it possible?

Body:
Here's a simple Python solution:

import re

FIELD = re.compile(r"(\w+)\.*:(.*)", re.DOTALL)  # split the line to name:value
VALUES = re.compile(r"(?<==).*?(?=\s|$)")  # match individual values from http_req_* fields

# open the input file `k6_input.log` for reading, and k6_parsed.log` for parsing
with open("k6_input.log", "r") as f_in, open("k6_parsed.log", "w") as f_out:
    for line in f_in:  # read the input file line by line
        field = FIELD.match(line)  # first match all <field_name>...:<values> fields
        if field:
            name = field.group(1)  # get the field name from the first capture group
            f_out.write(name + ": ")  # write the field name to the output file
            value = field.group(2)  # get the field value from the second capture group
            if name[:9] == "http_req_":  # parse out only http_req_* fields
                f_out.write(", ".join(VALUES.findall(value)) + "\n")  # extract the values
            else:  # verbatim copy of other fields
                f_out.write(value)
        else:  # encountered unrecognizable field, just copy the line
            f_out.write(line)

For a file with contents as above you'll get a resulting:

data_received:  246 kB 21 kB/s
data_sent:  174 kB 15 kB/s
http_req_blocked: 26.24ms, 0s, 13.5ms, 145.27ms, 61.04ms, 70.04ms
http_req_connecting: 23.96ms, 0s, 12ms, 145.27ms, 57.03ms, 66.04ms
http_req_duration: 197.41ms, 70.32ms, 91.56ms, 619.44ms, 288.2ms, 326.23ms
http_req_receiving: 141.82µs, 0s, 0s, 1ms, 1ms, 1ms
http_req_sending: 8.15ms, 0s, 0s, 334.23ms, 1ms, 1ms
http_req_waiting: 189.12ms, 70.04ms, 91.06ms, 343.42ms, 282.2ms, 309.22ms
http_reqs:  190    16.054553/s
iterations:  5      0.422488/s
vus:  200    min=200 max=200
vus_max:  200    min=200 max=200

If you have to run it over many files, I'd suggest you to investigate os.glob(), os.walk() or os.listdir() to list all the files you need and then loop over them and execute the above, thus further automating the process.


问:
Query consecutive vocals on sql
I had an exam last week and one of the exercises were "Obtain all data of students whom lastnames have at least two consecutive vocals".

I have tried doing the following:

```<code>select
    apellidos
from
    alumnos
where
    apellidos LIKE '[%aeiou%]'
</code>```

I also tried the query with a lot of ORs.

```<code>select
    apellidos
from
    alumnos
where
    apellidos LIKE '[%ae%]'
    OR apellidos LIKE '[%ai%]'
    OR apellidos LIKE '[%ao%]'
    OR apellidos LIKE '[%au%]'
    OR apellidos LIKE '[%ei%]'
    OR apellidos LIKE '[%eo%]'
    OR apellidos LIKE '[%eu%]'
    OR apellidos LIKE '[%io%]'
    OR apellidos LIKE '[%iu%]'
    OR apellidos LIKE '[%ou%]'
</code>```

None of this works, please help!

答:
Assuming "vocal" means "vowel" you want something like:

```<code>where apellidos LIKE '%[aeiou][aeiou]%'
</code>```

You should practice your pattern matching with like.  Then you can move on to real regular expressions.

Title: Query consecutive vocals on sql

Body:
I had an exam last week and one of the exercises were "Obtain all data of students whom lastnames have at least two consecutive vocals".

I have tried doing the following:

select
    apellidos
from
    alumnos
where
    apellidos LIKE '[%aeiou%]'

I also tried the query with a lot of ORs.

select
    apellidos
from
    alumnos
where
    apellidos LIKE '[%ae%]'
    OR apellidos LIKE '[%ai%]'
    OR apellidos LIKE '[%ao%]'
    OR apellidos LIKE '[%au%]'
    OR apellidos LIKE '[%ei%]'
    OR apellidos LIKE '[%eo%]'
    OR apellidos LIKE '[%eu%]'
    OR apellidos LIKE '[%io%]'
    OR apellidos LIKE '[%iu%]'
    OR apellidos LIKE '[%ou%]'

None of this works, please help!

Body:
Assuming "vocal" means "vowel" you want something like:

where apellidos LIKE '%[aeiou][aeiou]%'

You should practice your pattern matching with like.  Then you can move on to real regular expressions.


Title: JSON Parsing of ADSB Data


问:
Excel: I need the VBA to Display Text When An Image Is Clicked
Can I ask the VBA code to display text when I click an image in Excel.

Thank you.

答:
Try this.</p>

```<code>Sub Image1_Click()

'A1 is the cell where you want your text to appear
ActiveSheet.Range("A1").Value = "image clicked"

End Sub
</code>```

Body:
Try this.

Sub Image1_Click()

'A1 is the cell where you want your text to appear
ActiveSheet.Range("A1").Value = "image clicked"

End Sub


问:
How can I access every 5th Div, from a container so i can then use jQuery's add Class
Hey Everyone,
Here's what i'm trying to do..

i have div that will contain numerous other div (products in a shopping cart), say
up 50.

of these contained divs, i need to access every 5th div begging with 1, so it'd be div # 1, 6, 11, 16, 21 etc. and then use jQuery to Add Class to these divs.

can someone point me in the right direction on how to do this?

it would be hugely appreciated, thanks

Body: $('div:nth-child(5n+1)).addClass('my-class');


问:
Javascript: Convert Array of Arrays Into Array of Objects
I am attempting to change an array of arrays containing two value arrays into an array of two objects.

I'm fairly new to JS and I'm not sure where my code is wrong. The array being logged to the console contains the same two objects.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function transformEmployeeData(array) {
  let arrayOfObjects = [];
  let newObj = {};
  // iterates through employees
  for (let i = 0; i < array.length; i++) {
    // resets obj to empty
    newObj = {};
    // iterates through employees properties
    for (let j = 0; j < array[i].length; j++) {
      newObj[array[j][j][0]] = array[j][j][1];
    }
    // pushes object into array
    arrayOfObjects.push(newObj);
  }
  return arrayOfObjects;
}

console.log(transformEmployeeData(myArray));```

答:
This should work. Nested forEach loops then create the object a the end.</p>

```<code>let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function arrayToObj(arr){
    var myObj ={};
    arr.forEach(function(val){
        val.forEach(function(val2){
            myObj[val2[0]] = val2[1];
            console.log(myObj);
        });
    });
}
</code>```

Body:
This should work. Nested forEach loops then create the object a the end.

let myArray = [
  [
    ['name', 'John'],
    ['job', 'Janitor']
  ],
  [
    ['name', 'Rob'],
    ['job', 'CEO']
  ]
];

function arrayToObj(arr){
    var myObj ={};
    arr.forEach(function(val){
        val.forEach(function(val2){
            myObj[val2[0]] = val2[1];
            console.log(myObj);
        });
    });
}


问:
Download APNG File
I am getting some issues related to APNG file, APNG file animation working perfect if i put APNG files in resource bundle , But when i have download same APNG file from assets server and saving APNG file into resource directory and then load using MSSticker like this way. after loading it showing only first frame.if anyone wanna try to check APNG file please have a look to this.

```<code>let imagePath = Bundle.main.path(forResource: imgName, ofType: ".png")

    let pathurl =  URL(fileURLWithPath: imagePath!)

    do {
        try cell.stickerview.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "anything that you want")

    }
    catch {
        fatalError("Failed to create sticker: \(error)")
    }
</code>```

Here i am saving image & getting saved image url from resource directory:

```<code>static func saveImage(image: UIImage , name:String) -> Bool? {

    guard let data = UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent(name)!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}

static func getSavedImageUrl(named: String) -> URL? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named)
    }
    return nil
}
</code>```

I have written the extension in custom MSSticker class

```<code>extension MSStickerView {
func downloadedFrom(url: URL , name: String) {
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { () -> Void in
            // self.sticker = image
            _ = GameUtil.saveImage(image: image, name: name)

            if let pathurl = GameUtil.getSavedImageUrl(named: name) {
                do {

                     try self.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "Raid")
                }
                catch {
                    fatalError("Failed to create sticker: \(error)")
                }
            }
            self.startAnimating()
        }
        }.resume()
}
func downloadedFrom(link: String , name: String) {
    guard let url = URL(string: link) else { return }
    downloadedFrom(url: url ,name: name)
}
</code>```

答:
I think problem is this UIImagePNGRepresentation. Why convert Data to UIImage and then use UIImagePNGRepresentation.

Try saving data directly.

```<code>static func saveData(data: Data , name:String) -> Bool? {

    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent(name)!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}
</code>```

And ignore image just pass data.

```<code>_ = GameUtil.saveImage(data: data, name: name)
</code>```

Title: Download APNG File

Body:
I am getting some issues related to APNG file, APNG file animation working perfect if i put APNG files in resource bundle , But when i have download same APNG file from assets server and saving APNG file into resource directory and then load using MSSticker like this way. after loading it showing only first frame.if anyone wanna try to check APNG file please have a look to this.

let imagePath = Bundle.main.path(forResource: imgName, ofType: ".png")

    let pathurl =  URL(fileURLWithPath: imagePath!)

    do {
        try cell.stickerview.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "anything that you want")

    }
    catch {
        fatalError("Failed to create sticker: \(error)")
    }

Here i am saving image & getting saved image url from resource directory:

static func saveImage(image: UIImage , name:String) -> Bool? {

    guard let data = UIImagePNGRepresentation(image) else {
        return false
    }
    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent(name)!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}

static func getSavedImageUrl(named: String) -> URL? {
    if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
        return URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named)
    }
    return nil
}

I have written the extension in custom MSSticker class

extension MSStickerView {
func downloadedFrom(url: URL , name: String) {
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let image = UIImage(data: data)
            else { return }
        DispatchQueue.main.async() { () -> Void in
            // self.sticker = image
            _ = GameUtil.saveImage(image: image, name: name)

            if let pathurl = GameUtil.getSavedImageUrl(named: name) {
                do {

                     try self.sticker = MSSticker(contentsOfFileURL: pathurl, localizedDescription: "Raid")
                }
                catch {
                    fatalError("Failed to create sticker: \(error)")
                }
            }
            self.startAnimating()
        }
        }.resume()
}
func downloadedFrom(link: String , name: String) {
    guard let url = URL(string: link) else { return }
    downloadedFrom(url: url ,name: name)
}

Body:
I think problem is this UIImagePNGRepresentation. Why convert Data to UIImage and then use UIImagePNGRepresentation.

Try saving data directly.

static func saveData(data: Data , name:String) -> Bool? {

    guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
        return false
    }
    do {
        try data.write(to: directory.appendingPathComponent(name)!)
        return true
    } catch {
        print(error.localizedDescription)
        return false
    }
}

And ignore image just pass data.

_ = GameUtil.saveImage(data: data, name: name)


问:
PrintDocument adds an extra blank page upon a print job
When ever I print a image label to a zebra printer, the label prints normally and then an extra blank label is fed and this subsequently misaligns the top margin of each printed label afterwards.

I have looked online and at a lot of questions that have been already posted (i.e. printdocument adds blank page), with no solution.

I have tested printing the image file directly from Windows Photo Viewer as well as from the label program itself with success. The issue only occurs when running the program using PrintDocument. The following is my code

```<code>    var printDoc = new PrintDocument {PrinterSettings = {PrinterName = printerName}};
    printDoc.PrintPage += (sender, args) =>
    {
        using(Image img = Image.FromFile(filePath))
        {   //file is 900x300, DPI 300, and print page is 3x1 inches
            args.Graphics.PageUnit = GraphicsUnit.Document;
            args.Graphics.DrawImage(img, 0, 0, img.Width, img.Height);
            args.HasMorePages = false;
        }
    };

    printDoc.Print();
</code>```

I have tried to set the width and height to a much smaller value when I draw the image but it will still print a blank label! Any help would be greatly appreciated.

答:
I realized the issue. This only occurs running the program as a windows service. It will override any settings you have to the locally mapped printer and use the default network printer settings. Running the program as a console app worked as expected. The solution was to configure the default printer from its network location!

Many thanks to everyone who left comments and helped :)

Body:
When ever I print a image label to a zebra printer, the label prints normally and then an extra blank label is fed and this subsequently misaligns the top margin of each printed label afterwards.

I have looked online and at a lot of questions that have been already posted (i.e. printdocument adds blank page), with no solution.

I have tested printing the image file directly from Windows Photo Viewer as well as from the label program itself with success. The issue only occurs when running the program using PrintDocument. The following is my code

    var printDoc = new PrintDocument {PrinterSettings = {PrinterName = printerName}};
    printDoc.PrintPage += (sender, args) =>
    {
        using(Image img = Image.FromFile(filePath))
        {   //file is 900x300, DPI 300, and print page is 3x1 inches
            args.Graphics.PageUnit = GraphicsUnit.Document;
            args.Graphics.DrawImage(img, 0, 0, img.Width, img.Height);
            args.HasMorePages = false;
        }
    };

    printDoc.Print();

I have tried to set the width and height to a much smaller value when I draw the image but it will still print a blank label! Any help would be greatly appreciated.


问:
Pick file from storage in react native
I'm developing an app and I need to upload an image and file. The image was successfully done when I use react-native-image-picker library and use RNFetchBlob to upload to the server. But I'm still confuse in how to pick a file in react-native.

Is the process is same with how upload image, I pick the picture from storage and get the uri of that image and send it to server, or something like what?

Can you help me how to upload a file and what's the library i can use to do it?

Thanks

答:
RNFetchBlob can do it. You can try this:

```<code>RNFetchBlob.android.getContentIntent('application/octet-stream').then((path) => {
    // do your work with this path
})
</code>```

But I think there is a bug in this function when your MainActivity is FragmentActivity, it will throw the IllegalArgumentException("Can only use lower 16 bits for requestCode").

Have a try~

Title: Pick file from storage in react native

Body:
RNFetchBlob can do it. You can try this:

RNFetchBlob.android.getContentIntent('application/octet-stream').then((path) => {
    // do your work with this path
})

But I think there is a bug in this function when your MainActivity is FragmentActivity, it will throw the IllegalArgumentException("Can only use lower 16 bits for requestCode").

Have a try~


问:
JavaFx adding images
I keep getting this error no matter what I do to change it. I am very new to JavaFX and thought I would try out a small program. I am just trying to have a picture show up on the scene but I can't even have the image load up on my program. I placed the images in a package(seaapp.images) that is next to the main package(seaapp)

```<code>package seaapp;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SeaApp extends Application {

@Override
public void start(Stage primaryStage) {
    ImageView image = new ImageView(new Image(SeaApp.class.getResourceAsStream("images/space.png")));
    Pane root = new Pane();
    root.getChildren().add(image);
    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

}
</code>```

This gives me this error:

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$50/355629945.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Input stream must not be null
at javafx.scene.image.Image.validateInputStream(Image.java:1109)
at javafx.scene.image.Image.<init>(Image.java:694)
at seaapp.SeaApp.start(SeaApp.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/1175241703.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1685538367.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/435396101.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/485815673.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/1673605040.run(Unknown Source)
... 1 more
Exception running application seaapp.SeaApp
Java Result: 1
</code>```

This works fine when I add a URL of a picture as the new Image but when I have a downloaded picture, it gives me this error. My netbeans is fully updated too. I have put links to screenshots of how I set up the files. Am I missing something?

Setup of Projects:

https://drive.google.com/file/d/0B_KZLduvxt26dE5XS1p5blE5VFE/view?usp=sharing

Setup of Files:

https://drive.google.com/file/d/0B_KZLduvxt26Nm1sZWROSlRMeUE/view?usp=sharing

Link to Entire Project:

https://drive.google.com/file/d/0B_KZLduvxt26dXVFYlFhREFGZW8/view?usp=sharing

答:
Had the same problem with image inside jar wrapped into exe
The problem was the first capital letter in the file name. Paths are case-sensitive in wrapper but not when you run it under IDE on Windows.</p>

Title: JavaFx adding images

Body:
I keep getting this error no matter what I do to change it. I am very new to JavaFX and thought I would try out a small program. I am just trying to have a picture show up on the scene but I can't even have the image load up on my program. I placed the images in a package(seaapp.images) that is next to the main package(seaapp)

package seaapp;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SeaApp extends Application {

@Override
public void start(Stage primaryStage) {
    ImageView image = new ImageView(new Image(SeaApp.class.getResourceAsStream("images/space.png")));
    Pane root = new Pane();
    root.getChildren().add(image);
    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

}

This gives me this error:

Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$50/355629945.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Input stream must not be null
at javafx.scene.image.Image.validateInputStream(Image.java:1109)
at javafx.scene.image.Image.<init>(Image.java:694)
at seaapp.SeaApp.start(SeaApp.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/1175241703.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1685538367.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/435396101.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/485815673.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/1673605040.run(Unknown Source)
... 1 more
Exception running application seaapp.SeaApp
Java Result: 1

This works fine when I add a URL of a picture as the new Image but when I have a downloaded picture, it gives me this error. My netbeans is fully updated too. I have put links to screenshots of how I set up the files. Am I missing something?

Setup of Projects:

https://drive.google.com/file/d/0B_KZLduvxt26dE5XS1p5blE5VFE/view?usp=sharing

Setup of Files:

https://drive.google.com/file/d/0B_KZLduvxt26Nm1sZWROSlRMeUE/view?usp=sharing

Link to Entire Project:

https://drive.google.com/file/d/0B_KZLduvxt26dXVFYlFhREFGZW8/view?usp=sharing


问:
Postgrex expected a boolean, got "1"
I'm trying to pass a boolean value to hidden_input. But Postgrex doesn't seem to understand what I"m trying to pass in.

Here is my error:

```<code>Postgrex expected a boolean, got "1". Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.
</code>```

FORM:

```<code><%= inputs_for f, :users_leagues, fn ff -> %>
  <%= hidden_input ff, :commissioner, value: 1 %>
  <%= hidden_input ff, :user_id, value: assigns.current_user.id %>
  <%= hidden_input ff, :league_id, value: 1 %>
<% end %>
</code>```

It also doesn't work if a just pass in true I'll get this error: Postgrex expected a boolean, got "value"

How do I pass a boolean value to a hidden field?

答:
I found what I was doing wrong:

I had my users_leagues schema set up like this:

```<code>schema "users_leagues" do
  field :commissioner, :string
end
</code>```

It should be setup like this:

```<code>schema "users_leagues" do
  field :commissioner, :boolean
end
</code>```

That matches the database records.

Title: Postgrex expected a boolean, got "1"

Body:
I'm trying to pass a boolean value to hidden_input. But Postgrex doesn't seem to understand what I"m trying to pass in.

Here is my error:

Postgrex expected a boolean, got "1". Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.

FORM:

<%= inputs_for f, :users_leagues, fn ff -> %>
  <%= hidden_input ff, :commissioner, value: 1 %>
  <%= hidden_input ff, :user_id, value: assigns.current_user.id %>
  <%= hidden_input ff, :league_id, value: 1 %>
<% end %>

It also doesn't work if a just pass in true I'll get this error: Postgrex expected a boolean, got "value"

How do I pass a boolean value to a hidden field?

Body:
I found what I was doing wrong:

I had my users_leagues schema set up like this:

schema "users_leagues" do
  field :commissioner, :string
end

It should be setup like this:

schema "users_leagues" do
  field :commissioner, :boolean
end

That matches the database records.


问:
Why does Internet Explorer break each word in my popups?
My blog has popups and only IE breaks the words inside them. Why is it doing this?</p>

答:
Your construction of the table node for the words is not valid.  You should have
 and  elements within your table.

```<code><table class="popup-contents">
    <a href="http://www.polyvore.com/abby/set?id=26056923">
     <center>
         <img id="photo" src="http://24.media.tumblr.com/tumblr_ldm76urVRn1qboy47o1_400.jpg" alt="Simple with great, stand alone pieces." />
     </center>
    </a>
    <div class="caption"><p>Simple with great, stand alone pieces.</p></div>
</table>
</code>```

Body:
Your construction of the table node for the words is not valid.  You should have <tr> and <td> elements within your table.

<table class="popup-contents">
    <a href="http://www.polyvore.com/abby/set?id=26056923">
     <center>
         <img id="photo" src="http://24.media.tumblr.com/tumblr_ldm76urVRn1qboy47o1_400.jpg" alt="Simple with great, stand alone pieces." />
     </center>
    </a>
    <div class="caption"><p>Simple with great, stand alone pieces.</p></div>
</table>


问:
c# Process Arguments and Missing Output
I'm using an FFMPEG Process to gather some information on a file:

```<code>private void GatherFrames()
{
    Process process = new Process();
    process.StartInfo.FileName = "ffmpeg";
    process.StartInfo.Arguments = "-i \"" + filePath + "\"";
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.UseShellExecute = false;

    if (!process.Start())
    {
        Console.WriteLine("Error starting");
        return;
    }
    StreamReader reader = process.StandardError;
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        outputRichTextBox.AppendText(line + "\n");
    }
    process.Close();
}
</code>```

This seems to works fine. Now I want to get just the FrameRate, and thanks to other posts, I've found that ffprobe can be used to do just that:

```<code>public void GetFrameRate()
{
    Process process = new Process();
    process.StartInfo.FileName = "ffprobe";
    process.StartInfo.Arguments = "-v 0 -of compact=p=0 -select_streams 0 -show_entries stream = r_frame_rate \"" + filePath + "\"";
    Console.WriteLine(process.StartInfo.Arguments);
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = false;
    Console.WriteLine(process.StartInfo);

    if (!process.Start())
    {
        Console.WriteLine("Error starting");
        return;
    }

    StreamReader reader = process.StandardError;
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
    process.Close();
}
</code>```

This does not seem to work at all. The process starts, but does not return what I expect to be returned.

If I run the command manually, I do the following in cmd.exe:

```<code>> e:
> cd "FILE_PATH"
> ffprobe -v 0 -of compact=p=0 -select_streams 0 -show_entries stream=r_frame_rate "FILE_NAME.mp4"
r_frame_rate=60/1
</code>```

Note: -show_entries stream = r_frame_rate does not work, only -show_entries stream=r_frame_rate without the spaces.

I'm not sure how to properly go about doing this with a Process.

答:
I tried your argument and got the output through StandardOutput property.
Please just change your code to below and try it again.

```<code>StreamReader reader = process.StandardOutput;
</code>```

Title: c# Process Arguments and Missing Output

Body:
I'm using an FFMPEG Process to gather some information on a file:

private void GatherFrames()
{
    Process process = new Process();
    process.StartInfo.FileName = "ffmpeg";
    process.StartInfo.Arguments = "-i \"" + filePath + "\"";
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.UseShellExecute = false;

    if (!process.Start())
    {
        Console.WriteLine("Error starting");
        return;
    }
    StreamReader reader = process.StandardError;
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        outputRichTextBox.AppendText(line + "\n");
    }
    process.Close();
}

This seems to works fine. Now I want to get just the FrameRate, and thanks to other posts, I've found that ffprobe can be used to do just that:

public void GetFrameRate()
{
    Process process = new Process();
    process.StartInfo.FileName = "ffprobe";
    process.StartInfo.Arguments = "-v 0 -of compact=p=0 -select_streams 0 -show_entries stream = r_frame_rate \"" + filePath + "\"";
    Console.WriteLine(process.StartInfo.Arguments);
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = false;
    Console.WriteLine(process.StartInfo);

    if (!process.Start())
    {
        Console.WriteLine("Error starting");
        return;
    }

    StreamReader reader = process.StandardError;
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
    process.Close();
}

This does not seem to work at all. The process starts, but does not return what I expect to be returned.

If I run the command manually, I do the following in cmd.exe:

> e:
> cd "FILE_PATH"
> ffprobe -v 0 -of compact=p=0 -select_streams 0 -show_entries stream=r_frame_rate "FILE_NAME.mp4"
r_frame_rate=60/1

Note: -show_entries stream = r_frame_rate does not work, only -show_entries stream=r_frame_rate without the spaces.

I'm not sure how to properly go about doing this with a Process.

Body:
I tried your argument and got the output through StandardOutput property.
Please just change your code to below and try it again.

StreamReader reader = process.StandardOutput;