问:
Headless BehaviorSpace cannot load extensions
I am trying to run an experiment with BehaviorSpace from command line, but BehaviorSpace is not loading extensions. There is a similar question, bur I can neither understand the answer nor comment, so I will explain my issue here.

I modify the fire.nlogo model, add a random experiment called "experiment1" through the GUI and copy-paste from guide:

```<code>java -Xmx1024m -Dfile.encoding=UTF-8 -cp ~/Desktop/netlogo-6.0-M6-64/app/NetLogo.jar\
org.nlogo.headless.Main \
--model "~/Desktop/netlogo-6.0-M6-64/app/models/Sample Models/Earth Science/Fire.nlogo" Fire.nlogo" \
--experiment experiment1 \
--table -
</code>```

This works.

Then I add

```<code>"extensions[csv]"
</code>```

as first line in the model and run exact same command. This is what I get:

```<code>Exception in thread "main" Can't find extension: csv at position 11 in
at org.nlogo.core.ErrorSource.signalError(ErrorSource.scala:11)
at org.nlogo.workspace.ExtensionManager.importExtension(ExtensionManager.scala:171)
at org.nlogo.parse.StructureParser$$anonfun$parsingWithExtensions$1.apply(StructureParser.scala:70)
at org.nlogo.parse.StructureParser$$anonfun$parsingWithExtensions$1.apply(StructureParser.scala:69)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.nlogo.parse.StructureParser$.parsingWithExtensions(StructureParser.scala:69)
at org.nlogo.parse.StructureParser$.parseSources(StructureParser.scala:35)
at org.nlogo.parse.FrontEndMain$class.frontEnd(FrontEnd.scala:28)
at org.nlogo.parse.FrontEnd.frontEnd(FrontEnd.scala:16)
at org.nlogo.compiler.CompilerMain$.compile(CompilerMain.scala:28)
at org.nlogo.compiler.Compiler.compileProgram(Compiler.scala:54)
at org.nlogo.headless.HeadlessModelOpener.openFromModel(HeadlessModelOpener.scala:68)
at org.nlogo.headless.HeadlessWorkspace.openModel(HeadlessWorkspace.scala:544)
at org.nlogo.headless.HeadlessWorkspace.openFromSource(HeadlessWorkspace.scala:540)
at org.nlogo.headless.HeadlessWorkspace.openString(HeadlessWorkspace.scala:526)
at org.nlogo.headless.HeadlessWorkspace.open(HeadlessWorkspace.scala:508)
at org.nlogo.headless.Main$.org$nlogo$headless$Main$$newWorkspace$1(Main.scala:19)
at org.nlogo.headless.Main$$anonfun$runExperiment$1.apply(Main.scala:24)
at org.nlogo.headless.Main$$anonfun$runExperiment$1.apply(Main.scala:24)
at org.nlogo.lab.Lab$$anonfun$2.apply(Lab.scala:33)
at org.nlogo.lab.Lab$$anonfun$2.apply(Lab.scala:33)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.immutable.Range.foreach(Range.scala:160)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at org.nlogo.lab.Lab.run(Lab.scala:33)
at org.nlogo.headless.Main$.runExperiment(Main.scala:24)
at org.nlogo.headless.Main$$anonfun$main$1.apply(Main.scala:14)
at org.nlogo.headless.Main$$anonfun$main$1.apply(Main.scala:14)
at scala.Option.foreach(Option.scala:257)
at org.nlogo.headless.Main$.main(Main.scala:14)
at org.nlogo.headless.Main.main(Main.scala)
</code>```

If I repeat the procedure with Netlogo 5.3.1-64, I obtain a different error starting with

```<code>java.lang.IllegalStateException: Can't find extension: csv/csv.jar
</code>```

I tried the bitmap extension instead of CSV, but no luck. Noticeably, the experiment works if I start it from GUI.

I use
Ubuntu 16.10 and
java-1.8.0-openjdk-amd64.

答:
I had a similar problem.

For me it was resolved when I copied the folder extensions from NetLogo/app/ into the NetLogo folder (right where the netlogo-headless.sh is usually located).

Body:
I am trying to run an experiment with BehaviorSpace from command line, but BehaviorSpace is not loading extensions. There is a similar question, bur I can neither understand the answer nor comment, so I will explain my issue here.

I modify the fire.nlogo model, add a random experiment called "experiment1" through the GUI and copy-paste from guide:

java -Xmx1024m -Dfile.encoding=UTF-8 -cp ~/Desktop/netlogo-6.0-M6-64/app/NetLogo.jar\
org.nlogo.headless.Main \
--model "~/Desktop/netlogo-6.0-M6-64/app/models/Sample Models/Earth Science/Fire.nlogo" Fire.nlogo" \
--experiment experiment1 \
--table -

This works.

Then I add

"extensions[csv]"

as first line in the model and run exact same command. This is what I get:

Exception in thread "main" Can't find extension: csv at position 11 in
at org.nlogo.core.ErrorSource.signalError(ErrorSource.scala:11)
at org.nlogo.workspace.ExtensionManager.importExtension(ExtensionManager.scala:171)
at org.nlogo.parse.StructureParser$$anonfun$parsingWithExtensions$1.apply(StructureParser.scala:70)
at org.nlogo.parse.StructureParser$$anonfun$parsingWithExtensions$1.apply(StructureParser.scala:69)
at scala.collection.immutable.List.foreach(List.scala:381)
at org.nlogo.parse.StructureParser$.parsingWithExtensions(StructureParser.scala:69)
at org.nlogo.parse.StructureParser$.parseSources(StructureParser.scala:35)
at org.nlogo.parse.FrontEndMain$class.frontEnd(FrontEnd.scala:28)
at org.nlogo.parse.FrontEnd.frontEnd(FrontEnd.scala:16)
at org.nlogo.compiler.CompilerMain$.compile(CompilerMain.scala:28)
at org.nlogo.compiler.Compiler.compileProgram(Compiler.scala:54)
at org.nlogo.headless.HeadlessModelOpener.openFromModel(HeadlessModelOpener.scala:68)
at org.nlogo.headless.HeadlessWorkspace.openModel(HeadlessWorkspace.scala:544)
at org.nlogo.headless.HeadlessWorkspace.openFromSource(HeadlessWorkspace.scala:540)
at org.nlogo.headless.HeadlessWorkspace.openString(HeadlessWorkspace.scala:526)
at org.nlogo.headless.HeadlessWorkspace.open(HeadlessWorkspace.scala:508)
at org.nlogo.headless.Main$.org$nlogo$headless$Main$$newWorkspace$1(Main.scala:19)
at org.nlogo.headless.Main$$anonfun$runExperiment$1.apply(Main.scala:24)
at org.nlogo.headless.Main$$anonfun$runExperiment$1.apply(Main.scala:24)
at org.nlogo.lab.Lab$$anonfun$2.apply(Lab.scala:33)
at org.nlogo.lab.Lab$$anonfun$2.apply(Lab.scala:33)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
at scala.collection.immutable.Range.foreach(Range.scala:160)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
at scala.collection.AbstractTraversable.map(Traversable.scala:104)
at org.nlogo.lab.Lab.run(Lab.scala:33)
at org.nlogo.headless.Main$.runExperiment(Main.scala:24)
at org.nlogo.headless.Main$$anonfun$main$1.apply(Main.scala:14)
at org.nlogo.headless.Main$$anonfun$main$1.apply(Main.scala:14)
at scala.Option.foreach(Option.scala:257)
at org.nlogo.headless.Main$.main(Main.scala:14)
at org.nlogo.headless.Main.main(Main.scala)

If I repeat the procedure with Netlogo 5.3.1-64, I obtain a different error starting with

java.lang.IllegalStateException: Can't find extension: csv/csv.jar

I tried the bitmap extension instead of CSV, but no luck. Noticeably, the experiment works if I start it from GUI.

I use
Ubuntu 16.10 and
java-1.8.0-openjdk-amd64.


来源: stackexchange

问:
DirectX: "see through" polygons
I've created a simple DirectX app that renders a field of vertices. Vertices are rendered like this (if viewed from top):

```<code>|\|\|\|\|
|\|\|\|\|
</code>```

Each triangle is rendered like this:

```<code>1
|\
2 3
</code>```

Which should mean that the polygon is counterclockwise and not be rendered, but it is. Anyway when viewed from top the plane is perfect.

However, when viewed from another level some polygons are sort of transparent and you can see geometry behind them. I've highlighted some of the place where this is happening.

I am thinking this is some of the basic, beginner problems. What am I missing? My rasterizer description is such:

```<code>new RasterizerStateDescription
                                {
                                    CullMode = CullMode.Front,
                                    IsAntialiasedLineEnabled = true,
                                    IsMultisampleEnabled = true,
                                    IsDepthClipEnabled = true,
                                    IsFrontCounterclockwise = false,
                                    IsScissorEnabled = true,
                                    DepthBias = 1,
                                    DepthBiasClamp = 1000.0f,
                                    FillMode = FillMode.Wireframe,
                                    SlopeScaledDepthBias = 1.0f
                                };
</code>```

答:
This is by design. FillMode.Wireframe only draws edges of each triangle as lines. That's all.

Do a first pass with a solid fill mode and depth writes on and a color mask (RenderTargetWriteMask in D3D11 terminology), and a second one with depth test on (but depth writes off) and wireframe mode on. You will probably need depth bias too since lines and triangles are not rasterized the same way (and their z can differ at equal fragment position).

BTW, this technique is known as hidden line removal. You can check this presentation for more details.

ContentLicense: CC BY-SA 2.5

Title: DirectX: "see through" polygons

Body:
I've created a simple DirectX app that renders a field of vertices. Vertices are rendered like this (if viewed from top):

|\|\|\|\|
|\|\|\|\|

Each triangle is rendered like this:

1
|\
2 3

Which should mean that the polygon is counterclockwise and not be rendered, but it is. Anyway when viewed from top the plane is perfect.

However, when viewed from another level some polygons are sort of transparent and you can see geometry behind them. I've highlighted some of the place where this is happening.

I am thinking this is some of the basic, beginner problems. What am I missing? My rasterizer description is such:

new RasterizerStateDescription
                                {
                                    CullMode = CullMode.Front,
                                    IsAntialiasedLineEnabled = true,
                                    IsMultisampleEnabled = true,
                                    IsDepthClipEnabled = true,
                                    IsFrontCounterclockwise = false,
                                    IsScissorEnabled = true,
                                    DepthBias = 1,
                                    DepthBiasClamp = 1000.0f,
                                    FillMode = FillMode.Wireframe,
                                    SlopeScaledDepthBias = 1.0f
                                };


问:
ProgressDialog won't dismiss, on redirected url
i already created  simple webview with progress dialog, what's in my question is when url got redirected progress dialog wont dismiss. for example : i'm open url like : www.myweb.com/account. then it redirect to : www.myweb.com/login. any solution to handle this?</p>

```<code>//progress dialog
    ProgressDialog loading;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        loading= new ProgressDialog(MainActivity.this, R.style.MyAlertDialogStyle);
        loading.setMessage("Sedang Memuat...");
        loading.setCancelable(false);
        loading.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
            if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);
    }
</code>```

答:
```<code>webView.setWebViewClient(new WebViewClientClass());
 String url = "http://google.com/";
 webView.getSettings().setJavaScriptEnabled(true);
       webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.loadUrl(url);

private class WebViewClientClass extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            prDialog = new ProgressDialog(NewsActivity.this);
            prDialog.setMessage("Please wait ...");
            prDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if(prDialog!=null){
                prDialog.dismiss();
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i already created  simple webview with progress dialog, what's in my question is when url got redirected progress dialog wont dismiss. for example : i'm open url like : www.myweb.com/account. then it redirect to : www.myweb.com/login. any solution to handle this?

//progress dialog
    ProgressDialog loading;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        loading= new ProgressDialog(MainActivity.this, R.style.MyAlertDialogStyle);
        loading.setMessage("Sedang Memuat...");
        loading.setCancelable(false);
        loading.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
            if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);
    }


问:
Function inside component - ReactJS
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

```<code>getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}
</code>```

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

```<code>class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

    <table className="table is-striped is-narrow is-fullwidth"><thead>
        <tr>
          <td>Rank</td>
          <td>Name</td>
          <td>Symbol</td>
          <td>Price (USD)</td>
          <td>1h</td>
          <td>24h</td>
          <td>1 Week</td>
          <td>Market Cap</td>
        </tr>
      </thead>
      <tbody>{Object.keys(this.state.cryptos).map((key) => (
        <tr>
          <td>{this.state.cryptos[key].rank}</td>
          <td>{this.state.cryptos[key].name}</td>
          <td>{this.state.cryptos[key].symbol}</td>
          <td>{this.state.cryptos[key].price_usd}</td>
          <td>{this.state.cryptos[key].percent_change_1h}</td>
          <td>{this.state.cryptos[key].percent_change_24h}</td>
          <td>{this.state.cryptos[key].percent_change_7d}</td>
          <td>{this.state.cryptos[key].market_cap_usd}</td>
        </tr>
 ))};
      </tbody>
    </table>

);
}
}
</code>```

答:
Even in React you can have method in a component. Just create a method called getCoinImage in your component. Then externally keep a reference to the component and finally call it this way:</p>

```<code>this.refs.myComponentReference.getCoinImage();
</code>```

Title: Function inside component - ReactJS

Body:
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

          Rank
          Name
          Symbol
          Price (USD)
          1h
          24h
          1 Week
          Market Cap

{Object.keys(this.state.cryptos).map((key) => (

          {this.state.cryptos[key].rank}
          {this.state.cryptos[key].name}
          {this.state.cryptos[key].symbol}
          {this.state.cryptos[key].price_usd}
          {this.state.cryptos[key].percent_change_1h}
          {this.state.cryptos[key].percent_change_24h}
          {this.state.cryptos[key].percent_change_7d}
          {this.state.cryptos[key].market_cap_usd}

 ))};

);
}
}

Body:
Even in React you can have method in a component. Just create a method called getCoinImage in your component. Then externally keep a reference to the component and finally call it this way:

this.refs.myComponentReference.getCoinImage();


问:
How to deselect an invisible cell in a custom layout collection view?
Fetching the invisible cell may or may not gets the cell, even if the index position is not null.

Summary: I've tried selecting and deselecting logic inside shouldSelectItemAt function. Selection goes well. But upon selecting a new cell, the previously selected cell needed to be deselected. As I am using custom collection view layout, I doubt the problem is occurring due to reusability of cells.

Code:

```<code>func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if(collectionView == customContentCollectionView){
let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell

// DESELECTION CODE
if(previouslySelectedIndex != nil){
                                    // following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesnt)
                                    let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                                    // Also tried with this following (executes but fails sometimes, in case not fetching the cell)
                                    //let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex)! as! MyCollectionViewController.MyContentCell

                                    // Tried this one as well, fetching the previously selected cell using datasource, not directly from collection view
                                    // let prevCell = customContentCollectionView.dataSource?.collectionView(collectionView, cellForItemAt: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                                    prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
                                    prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
                                    prevCell?.shapeLayer.shadowOpacity = 0.0
                                    prevCell?.labelCount.textColor = bubbleBorder
}

// SELECTION CODE HERE GOES PRETTY WELL
...
previouslySelectedIndex = indexPath
}
</code>```

N.B. : I am using CustomUICollectionViewFlowLayout, I need to use only shouldSelectItemAt function. No other function for selection and deselection.

答:
```<code>let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell
</code>```

returns nil because if user scrolled collectionView cell might have been reused for some other indexPath and hence returns nil.

So you should not ask for cell from collectionView rather you should ask datasource

```<code>let cell = self.collectionView?.dataSource?.collectionView(self.collectionView!, cellForItemAt: IndexPath(row: 0, section: 0))
</code>```

Other approach would be to use prepareForReuse to reset the cell states before it gets reused. prepareForReuse sounds more legitimate solution to me though :)

EDIT:

On a second thought though above code will return the cell, updating the UI of cell not loaded/reused will result in adverse effects. Rather what you can do is in shouldSelectItemAt update the UI of the deselected cell only if cell is available

```<code>func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        if(collectionView == customContentCollectionView){
            let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell

            // DESELECTION CODE
            if(previouslySelectedIndex != nil){
                // following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesnt)
                if let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell {

                    // Also tried with this following (executes but fails sometimes, in case not fetching the cell)
                    //let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex)! as! MyCollectionViewController.MyContentCell

                    // Tried this one as well, fetching the previously selected cell using datasource, not directly from collection view
                    // let prevCell = customContentCollectionView.dataSource?.collectionView(collectionView, cellForItemAt: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                    prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
                    prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
                    prevCell?.shapeLayer.shadowOpacity = 0.0
                    prevCell?.labelCount.textColor = bubbleBorder
                }
            }

            // SELECTION CODE HERE GOES PRETTY WELL
                previouslySelectedIndex = indexPath
        }
    }
</code>```

If let added above should take care of ensuring the you update the UI of cell to deselect it only if it is available.

Now implement prepareForReuse in cell

```<code>override func prepareForReuse() {
    //reset all the fields of cell
    self.shapeLayer.strokeColor = bubbleBorder.cgColor
    self.shapeLayer.fillColor = bubbleFill.cgColor
    self.shapeLayer.shadowOpacity = 0.0
    self.labelCount.textColor = bubbleBorder
}
</code>```

Finally in cellForItemAtIndexPath

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     //your code to create cell n all

     if(indexPath == previouslySelectedIndex) {
         //your code to select the cell
     }

     return cell
 }
</code>```

Hope this helps

Body:
Fetching the invisible cell may or may not gets the cell, even if the index position is not null.

Summary: I've tried selecting and deselecting logic inside shouldSelectItemAt function. Selection goes well. But upon selecting a new cell, the previously selected cell needed to be deselected. As I am using custom collection view layout, I doubt the problem is occurring due to reusability of cells.

Code:

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if(collectionView == customContentCollectionView){
let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell

// DESELECTION CODE
if(previouslySelectedIndex != nil){
                                    // following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesnt)
                                    let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                                    // Also tried with this following (executes but fails sometimes, in case not fetching the cell)
                                    //let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex)! as! MyCollectionViewController.MyContentCell

                                    // Tried this one as well, fetching the previously selected cell using datasource, not directly from collection view
                                    // let prevCell = customContentCollectionView.dataSource?.collectionView(collectionView, cellForItemAt: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                                    prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
                                    prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
                                    prevCell?.shapeLayer.shadowOpacity = 0.0
                                    prevCell?.labelCount.textColor = bubbleBorder
}

// SELECTION CODE HERE GOES PRETTY WELL
...
previouslySelectedIndex = indexPath
}

N.B. : I am using CustomUICollectionViewFlowLayout, I need to use only shouldSelectItemAt function. No other function for selection and deselection.

Body:
let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

returns nil because if user scrolled collectionView cell might have been reused for some other indexPath and hence returns nil.

So you should not ask for cell from collectionView rather you should ask datasource

let cell = self.collectionView?.dataSource?.collectionView(self.collectionView!, cellForItemAt: IndexPath(row: 0, section: 0))

Other approach would be to use prepareForReuse to reset the cell states before it gets reused. prepareForReuse sounds more legitimate solution to me though :)

EDIT:

On a second thought though above code will return the cell, updating the UI of cell not loaded/reused will result in adverse effects. Rather what you can do is in shouldSelectItemAt update the UI of the deselected cell only if cell is available

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        if(collectionView == customContentCollectionView){
            let cell:MyContentCell = collectionView.cellForItem(at: indexPath)! as! MyCollectionViewController.MyContentCell

            // DESELECTION CODE
            if(previouslySelectedIndex != nil){
                // following line is error prone (executes but may or may not fetch the cell, sometimes deselect sometimes doesnt)
                if let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell {

                    // Also tried with this following (executes but fails sometimes, in case not fetching the cell)
                    //let prevCell = try collectionView.cellForItem(at: previouslySelectedIndex)! as! MyCollectionViewController.MyContentCell

                    // Tried this one as well, fetching the previously selected cell using datasource, not directly from collection view
                    // let prevCell = customContentCollectionView.dataSource?.collectionView(collectionView, cellForItemAt: previouslySelectedIndex) as? MyCollectionViewController.MyContentCell

                    prevCell?.shapeLayer.strokeColor = bubbleBorder.cgColor
                    prevCell?.shapeLayer.fillColor = bubbleFill.cgColor
                    prevCell?.shapeLayer.shadowOpacity = 0.0
                    prevCell?.labelCount.textColor = bubbleBorder
                }
            }

            // SELECTION CODE HERE GOES PRETTY WELL
                previouslySelectedIndex = indexPath
        }
    }

If let added above should take care of ensuring the you update the UI of cell to deselect it only if it is available.

Now implement prepareForReuse in cell

override func prepareForReuse() {
    //reset all the fields of cell
    self.shapeLayer.strokeColor = bubbleBorder.cgColor
    self.shapeLayer.fillColor = bubbleFill.cgColor
    self.shapeLayer.shadowOpacity = 0.0
    self.labelCount.textColor = bubbleBorder
}

Finally in cellForItemAtIndexPath

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     //your code to create cell n all

     if(indexPath == previouslySelectedIndex) {
         //your code to select the cell
     }

     return cell
 }

Hope this helps


问:
Which letter of the English alphabet takes up most pixels?
I am trying to do some dynamic programming based on the number of characters in a sentence. Which letter of the English alphabet takes up the most pixels on the screen?</p>

答:
I know the accepted answer here is W, W is for WIN.

However, in this case, W is also for Width. The case study used employed a simple width test to examine pixels, but it was only the width, not the total pixel count. As an easy counter example, the accepted answer assumes that O and Q take up the same amount of pixels, yet they only take up the same amount of space.

Thus, W takes up the most space. But, is it all the pixels it's cracked up to be?

Let's get some empirical data. I created imgur images from the following B, M and W. I then analyzed their pixel count (see below), here are the results:

B : 114 pixels

M : 150 pixels

W : 157 pixels

Here is how I fed them into canvas and analyzed the raw pixel data from the images.

var imgs = {
 B : "//i.imgur.com/YOuEPOn.png",
 M : "//i.imgur.com/Aev3ZKQ.png",
 W : "//i.imgur.com/xSUwE7w.png"
};
window.onload = function(){
  for(var key in imgs){(function(img,key){
    var Out = document.querySelector("#"+key+"Out");
    img.crossOrigin = "Anonymous";
    img.src=imgs[key];
    img.onload = function() {
      var canvas = document.querySelector('#'+key);
      (canvas.width = img.width,canvas.height = img.height);
      var context = canvas.getContext('2d');
      context.drawImage(img, 0, 0);
      var data = context.getImageData(0, 0, img.width, img.height).data;
      Out.innerHTML = "Total Pixels: " + data.length/4 + "
";
      var pixelObject = {};
      for(var i = 0; i < data.length; i += 4){
        var rgba = "rgba("+data[i]+","+data[i+1]+","+data[i+2]+","+data[i+3]+")";
       pixelObject[rgba] = pixelObject[rgba] ? pixelObject[rgba]+1 : 1;
      }
      Out.innerHTML += "Total Whitespace: " + pixelObject["rgba(255,255,255,255)"] + "
";
      Out.innerHTML += "Total Pixels In "+ key +": " + ((data.length/4)-pixelObject["rgba(255,255,255,255)"]) + "
";
    };
  })(new Image(),key)}
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
  <td>
    <canvas id="B" width="100%" height="100%"></canvas>
  </td>
  <td id="BOut">
  </td>
</tr>
<tr>
  <td>
    <canvas id="M" width="100%" height="100%"></canvas>
  </td>
  <td id="MOut">
  </td>
</tr>
<tr>
  <td>
    <canvas id="W" width="100%" height="100%"></canvas>
  </td>
  <td id="WOut">
  </td>
</tr>
</table></code>```

Body:
I know the accepted answer here is W, W is for WIN.

However, in this case, W is also for Width. The case study used employed a simple width test to examine pixels, but it was only the width, not the total pixel count. As an easy counter example, the accepted answer assumes that O and Q take up the same amount of pixels, yet they only take up the same amount of space.

Thus, W takes up the most space. But, is it all the pixels it's cracked up to be?

Let's get some empirical data. I created imgur images from the following B, M and W. I then analyzed their pixel count (see below), here are the results:

B : 114 pixels

M : 150 pixels

W : 157 pixels

Here is how I fed them into canvas and analyzed the raw pixel data from the images.

var imgs = {
 B : "//i.imgur.com/YOuEPOn.png",
 M : "//i.imgur.com/Aev3ZKQ.png",
 W : "//i.imgur.com/xSUwE7w.png"
};
window.onload = function(){
  for(var key in imgs){(function(img,key){
    var Out = document.querySelector("#"+key+"Out");
    img.crossOrigin = "Anonymous";
    img.src=imgs[key];
    img.onload = function() {
      var canvas = document.querySelector('#'+key);
      (canvas.width = img.width,canvas.height = img.height);
      var context = canvas.getContext('2d');
      context.drawImage(img, 0, 0);
      var data = context.getImageData(0, 0, img.width, img.height).data;
      Out.innerHTML = "Total Pixels: " + data.length/4 + "<br>";
      var pixelObject = {};
      for(var i = 0; i < data.length; i += 4){
        var rgba = "rgba("+data[i]+","+data[i+1]+","+data[i+2]+","+data[i+3]+")";
       pixelObject[rgba] = pixelObject[rgba] ? pixelObject[rgba]+1 : 1;
      }
      Out.innerHTML += "Total Whitespace: " + pixelObject["rgba(255,255,255,255)"] + "<br>";
      Out.innerHTML += "Total Pixels In "+ key +": " + ((data.length/4)-pixelObject["rgba(255,255,255,255)"]) + "<br>";
    };
  })(new Image(),key)}
};

<table>
<tr>
  <td>
    <canvas id="B" width="100%" height="100%"></canvas>
  </td>
  <td id="BOut">
  </td>
</tr>
<tr>
  <td>
    <canvas id="M" width="100%" height="100%"></canvas>
  </td>
  <td id="MOut">
  </td>
</tr>
<tr>
  <td>
    <canvas id="W" width="100%" height="100%"></canvas>
  </td>
  <td id="WOut">
  </td>
</tr>
</table>


问:
Objective c: iBeacon ranging doesn't fire didEnterRegion
I´ve implemented a beacon region monitoring in my AppDelegate.

I test my code in foreground.
The didRangeBeacons event is thrown successfully and regularly. (I see the amount of beacons and also the count change in the didRangeBeacons if i turn off my beacon.)
My didEnterRegion event was not fired.

AppDelegate.m

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //....
    self->beaconLocationManager = [[CLLocationManager alloc] init];
    self->beaconLocationManager.delegate = self;//(AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSUUID *uuid=[[NSUUID alloc]initWithUUIDString:@"200F0B26-2215-1518-442B-5F0616412530"];
    clBeconRegion=[[CLBeaconRegion alloc]initWithProximityUUID:uuid identifier:@"BluetoothExample"];
    clBeconRegion.notifyOnEntry=YES;
    [self->beaconLocationManager requestAlwaysAuthorization];
    [self->beaconLocationManager startMonitoringForRegion:clBeconRegion];
    [self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion];
    return YES;
}

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");//not fired
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
    NSLog(@"beacons list %@ ",beacons);//successfully fired regularly
}
</code>```

I also enabled Background App Refresh in general settings.

Info.plist entry:
<key>NSLocationAlwaysUsageDescription</key><string>bla bla bla</string>
<key>NSLocationWhenInUseUsageDescription</key><string>bla bla bla</string>

The monitoringDidFailForRegion writes the following error:
CLBeaconRegion (identifier:'BluetoothExample', uuid:200F0B26-2215-1518-442B-5F0616412530, major:(null), minor:(null)) The operation couldn’t be completed. (kCLErrorDomain error 4.)

答:
I found my problem.
It is an existing app and I granted the location in a fewer version only for "in usage".
Now I need "always".

I deleted an reinstalled the app and it works. (only update doesn't help)

Body:
I´ve implemented a beacon region monitoring in my AppDelegate.

I test my code in foreground.
The didRangeBeacons event is thrown successfully and regularly. (I see the amount of beacons and also the count change in the didRangeBeacons if i turn off my beacon.)
My didEnterRegion event was not fired.

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //....
    self->beaconLocationManager = [[CLLocationManager alloc] init];
    self->beaconLocationManager.delegate = self;//(AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSUUID *uuid=[[NSUUID alloc]initWithUUIDString:@"200F0B26-2215-1518-442B-5F0616412530"];
    clBeconRegion=[[CLBeaconRegion alloc]initWithProximityUUID:uuid identifier:@"BluetoothExample"];
    clBeconRegion.notifyOnEntry=YES;
    [self->beaconLocationManager requestAlwaysAuthorization];
    [self->beaconLocationManager startMonitoringForRegion:clBeconRegion];
    [self->beaconLocationManager startRangingBeaconsInRegion:clBeconRegion];
    return YES;
}

- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    NSLog(@"ENTER REGION");//not fired
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region{
    NSLog(@"beacons list %@ ",beacons);//successfully fired regularly
}

I also enabled Background App Refresh in general settings.

Info.plist entry:
<key>NSLocationAlwaysUsageDescription</key><string>bla bla bla</string>
<key>NSLocationWhenInUseUsageDescription</key><string>bla bla bla</string>

The monitoringDidFailForRegion writes the following error:
CLBeaconRegion (identifier:'BluetoothExample', uuid:200F0B26-2215-1518-442B-5F0616412530, major:(null), minor:(null)) The operation couldn’t be completed. (kCLErrorDomain error 4.)


答:
```<code>loading.setCancelable(false);
</code>```

Set this to true as :

```<code>loading.setCancelable(true);
</code>```

Also instead of this:

```<code>if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);
</code>```

Use this:

```<code>super.onPageFinished(view, url);
if (loading!=null) {
            loading.dismiss();
        }
</code>```

Also try commenting this line :

```<code>super.onPageFinished(view, url);
</code>```

Another way is if its not dismissing somehow you can hide this in that case you have to do this:

After:

```<code>loading.show();
</code>```

Add this:

```<code>loading.setVisibility(View.VISIBLE);
</code>```

and after this:

```<code>loading.dismiss();
</code>```

add this:

```<code>loading.setVisibility(View.INVISIBLE);
</code>```

Title: ProgressDialog won't dismiss, on redirected url

Body:
loading.setCancelable(false);

Set this to true as :

loading.setCancelable(true);

Also instead of this:

if (loading.isShowing()) {
                loading.dismiss();
            }
        super.onPageFinished(view, url);

Use this:

super.onPageFinished(view, url);
if (loading!=null) {
            loading.dismiss();
        }

Also try commenting this line :

super.onPageFinished(view, url);

Another way is if its not dismissing somehow you can hide this in that case you have to do this:

After:

loading.show();

Add this:

loading.setVisibility(View.VISIBLE);

and after this:

loading.dismiss();

add this:

loading.setVisibility(View.INVISIBLE);


问:
How to check in Java color of text when I have .html and .css files?
I have html with css and I want to check what is real color (and other visual text attributes) of specified text in html document. Can I do this with JSoup or must I look for some real-like html engine/processor? Speed of processing this operation is one of main factor.</p>

答:
I think he wants to retreive this data in Java program. So you need few things to do.

Download stylesheet files.

Parse html and find class attribute.

Match .class in css with html attribute and find specific information you want.

But beware if you want to find information about any html element without class attribute. In such case you need to find xpath of html element e.g:

```<code><table class="entityTable">
<tr>
<td> <input type="text" value="abcdef" /></td>
</tr>
</code>```

Then you need to find xpath like : body/div/.../table/tr/td/input and you need to match any css rules which can influence your input tag attributes.

```<code>.entityTable tr td input
{
 color:red;
}
</code>```

This is much more difficult so if html to parse is your page put everywhere class attribute into your html tags. Otherwise you need to find way to mach html tags to css rules.

Cheers.

Body:
I think he wants to retreive this data in Java program. So you need few things to do.

Download stylesheet files.

Parse html and find class attribute.

Match .class in css with html attribute and find specific information you want.

But beware if you want to find information about any html element without class attribute. In such case you need to find xpath of html element e.g:

<table class="entityTable">
<tr>
<td> <input type="text" value="abcdef" /></td>
</tr>

Then you need to find xpath like : body/div/.../table/tr/td/input and you need to match any css rules which can influence your input tag attributes.

.entityTable tr td input
{
 color:red;
}

This is much more difficult so if html to parse is your page put everywhere class attribute into your html tags. Otherwise you need to find way to mach html tags to css rules.

Cheers.


问:
Saving and restoring text when rotating
I have seen a few examples on how to achieve this but still I can't get it working.

I followed this example, but the TextView is empty in OnCreate and when I rotate the screen. Here is how I implemented it:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    //Getting the fileName
    Bundle extras = getIntent().getExtras();
    uri = extras.getString("uriAsString");
    Uri myUri = Uri.parse(uri);
    filename = uri.substring(uri.lastIndexOf("/") + 1);
    nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));

    //Checking if Text was stored
    if (savedInstanceState != null) {
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
        displayFileName.setText(savedText);
    }

}

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}
</code>```

What I'm trying to achieve is to set nameWitoutExtention to displayFileName and when the device is rotated to let the text remain.

I got a null pointer on the text and that is why I'm trying this, any help on what I'm doing wrong?

EDIT:

This is how my implementation looks like at the moment:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    if(savedInstanceState != null){
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);

        //When displaying this toast the correct filename gets displayed
        //Toast.makeText(getApplicationContext(), savedText, Toast.LENGTH_LONG).show();

        displayFileName.setText(savedText+"");
    }
    else{
        //Getting the fileName
        Bundle extrsas = getIntent().getExtras();
        uri = extrsas.getString("selectedStudentVid");
        Uri mUri = Uri.parse(uri);
        filename = uri.substring(uri.lastIndexOf("/") + 1);
        nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
        displayFileName.setText(nameWitoutExtention);
    }

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}
</code>```

I have also tried onRestoreInstanceState() as suggested by @PorasBhardwaj

The exception I'm getting is:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
</code>```

答:
Try doing it this way:

```<code>//Checking if Text was stored
 if(savedInstanceState != null){
       CharSequence savedText =
      savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
      displayFileName.setText(savedText + "");
 }
else{
 //Getting the fileName
Bundle extras = getIntent().getExtras();
uri = extras.getString("uriAsString");
Uri myUri = Uri.parse(uri);
filename = uri.substring(uri.lastIndexOf("/") + 1);
nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
}
</code>```

What you are doing wrong is. Whenever the orientation changes it gets the value again from extras which is null after the rotation change and it passes the same value to it. That's why you are getting the exception.
try this hope it will help you.

Title: Saving and restoring text when rotating

Body:
I have seen a few examples on how to achieve this but still I can't get it working.

I followed this example, but the TextView is empty in OnCreate and when I rotate the screen. Here is how I implemented it:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    //Getting the fileName
    Bundle extras = getIntent().getExtras();
    uri = extras.getString("uriAsString");
    Uri myUri = Uri.parse(uri);
    filename = uri.substring(uri.lastIndexOf("/") + 1);
    nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));

    //Checking if Text was stored
    if (savedInstanceState != null) {
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
        displayFileName.setText(savedText);
    }

}

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}

What I'm trying to achieve is to set nameWitoutExtention to displayFileName and when the device is rotated to let the text remain.

I got a null pointer on the text and that is why I'm trying this, any help on what I'm doing wrong?

EDIT:

This is how my implementation looks like at the moment:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_image_viewer);

    displayFileName = (TextView) findViewById(R.id.displayFileName);

    if(savedInstanceState != null){
        CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);

        //When displaying this toast the correct filename gets displayed
        //Toast.makeText(getApplicationContext(), savedText, Toast.LENGTH_LONG).show();

        displayFileName.setText(savedText+"");
    }
    else{
        //Getting the fileName
        Bundle extrsas = getIntent().getExtras();
        uri = extrsas.getString("selectedStudentVid");
        Uri mUri = Uri.parse(uri);
        filename = uri.substring(uri.lastIndexOf("/") + 1);
        nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
        displayFileName.setText(nameWitoutExtention);
    }

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putCharSequence(KEY_TEXT_VALUE, displayFileName.getText());
}

I have also tried onRestoreInstanceState() as suggested by @PorasBhardwaj

The exception I'm getting is:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

Body:
Try doing it this way:

//Checking if Text was stored
 if(savedInstanceState != null){
       CharSequence savedText =
      savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
      displayFileName.setText(savedText + "");
 }
else{
 //Getting the fileName
Bundle extras = getIntent().getExtras();
uri = extras.getString("uriAsString");
Uri myUri = Uri.parse(uri);
filename = uri.substring(uri.lastIndexOf("/") + 1);
nameWitoutExtention = filename.substring(0, filename.lastIndexOf('.'));
}

What you are doing wrong is. Whenever the orientation changes it gets the value again from extras which is null after the rotation change and it passes the same value to it. That's why you are getting the exception.
try this hope it will help you.


问:
What is the meaning of UriComponentsBuilder?
I get an example UriComponentsBuilder while learning spring boot. I don't know the meaning of UriComponentsBuilder and the function of UriComponentsBuilder.</p>

答:
It is a factory class for getting instances of UriComponents which are helpful for constructing URIs.

Please go through the tutorial below, examples are also given here.

http://www.baeldung.com/spring-uricomponentsbuilder


问:
Thread management in asp.net core / kestrel
I'm troubleshooting performance / scalability issues with an asp.net app we've migrated to asp.net core 2.0. Our app is hosted on azure as an app service, and is falling over far too easily with any moderate traffic.

One thing that's puzzling me is how multiple concurrent requests are handled. From what I've read here, Kestrel uses multiple event loops to handle your requests. But the actual user code is handled on the .net thread pool (that's from here).

So, as an experiment - I've created a new asp.net core 2.0 MVC app, and added a rather nasty action method:

```<code>    [AllowAnonymous]
    public ActionResult Wait1()
    {
        System.Threading.Tasks.Task.Delay(1000).Wait();
        return new StatusCodeResult((int)HttpStatusCode.OK);
    }
</code>```

Now, when I push this to azure, I'd expect that if I send say 100 requests at the same time, then I should be OK, because 100 requests sounds like minor load, right? And the waiting will happen on the thread pool threads, right?

So - I do just this and get some rather poor results - sample highlighted in red:

Hmm, not what I expected, about 50 seconds per request... If however I change the frequency so the requests are spaced a second apart, then the response time is fine - back to just over 1000ms as you'd expect. It seems if I go over 30 requests at the same time, it starts to suffer, which seems somewhat low to me.

So - I realise that my nasty action method blocks, but I'd have expected it to block on a thread pool thread, and therefore be able to cope with more than my 30.

Is this expected behaviour - and if so is it just a case of making sure that no IO-bound work is done without using async code?

答:
Is this expected behaviour - and if so is it just a case of making sure that no IO-bound work is done without using async code?

Based on my experience, it seems that is as expected behaviour. We could get answer from this blog.

Now suppose you are running your ASP.Net application on IIS and your web server has a total of four CPUs. Assume that at any given point in time, there are 100 requests to be processed. By default the runtime would create four threads, which would be available to service the first four requests. Because no additional threads will be added until 500 milliseconds have elapsed, the other 96 requests will have to wait in the queue. After 500 milliseconds have passed, a new thread is created.

As you can see, it will take 100*500ms intervals to catch up with the workload.

This is a good reason for using asynchronous programming. With async programming, threads aren’t blocked while requests are being handled, so the four threads would be freed up almost immediately.

I recommand that you could use async code to improve the performance.

```<code>public async Task<ActionResult> Wait1()
{
    await Task.Delay(TimeSpan.FromSeconds(15));
    return new StatusCodeResult((int)HttpStatusCode.OK);
}
</code>```

I also find another SO thread, you could refernce to it.

Body:
I'm troubleshooting performance / scalability issues with an asp.net app we've migrated to asp.net core 2.0. Our app is hosted on azure as an app service, and is falling over far too easily with any moderate traffic.

One thing that's puzzling me is how multiple concurrent requests are handled. From what I've read here, Kestrel uses multiple event loops to handle your requests. But the actual user code is handled on the .net thread pool (that's from here).

So, as an experiment - I've created a new asp.net core 2.0 MVC app, and added a rather nasty action method:

    [AllowAnonymous]
    public ActionResult Wait1()
    {
        System.Threading.Tasks.Task.Delay(1000).Wait();
        return new StatusCodeResult((int)HttpStatusCode.OK);
    }

Now, when I push this to azure, I'd expect that if I send say 100 requests at the same time, then I should be OK, because 100 requests sounds like minor load, right? And the waiting will happen on the thread pool threads, right?

So - I do just this and get some rather poor results - sample highlighted in red:

Hmm, not what I expected, about 50 seconds per request... If however I change the frequency so the requests are spaced a second apart, then the response time is fine - back to just over 1000ms as you'd expect. It seems if I go over 30 requests at the same time, it starts to suffer, which seems somewhat low to me.

So - I realise that my nasty action method blocks, but I'd have expected it to block on a thread pool thread, and therefore be able to cope with more than my 30.

Is this expected behaviour - and if so is it just a case of making sure that no IO-bound work is done without using async code?

Body:
Is this expected behaviour - and if so is it just a case of making sure that no IO-bound work is done without using async code?

Based on my experience, it seems that is as expected behaviour. We could get answer from this blog.

Now suppose you are running your ASP.Net application on IIS and your web server has a total of four CPUs. Assume that at any given point in time, there are 100 requests to be processed. By default the runtime would create four threads, which would be available to service the first four requests. Because no additional threads will be added until 500 milliseconds have elapsed, the other 96 requests will have to wait in the queue. After 500 milliseconds have passed, a new thread is created.

As you can see, it will take 100*500ms intervals to catch up with the workload.

This is a good reason for using asynchronous programming. With async programming, threads aren’t blocked while requests are being handled, so the four threads would be freed up almost immediately.

I recommand that you could use async code to improve the performance.

public async Task<ActionResult> Wait1()
{
    await Task.Delay(TimeSpan.FromSeconds(15));
    return new StatusCodeResult((int)HttpStatusCode.OK);
}

I also find another SO thread, you could refernce to it.


问:
How to create an Oracle sequence starting with max value from a table?
Trying to create a sequence in Oracle that starts with the max value from a specific table. Why does this not work?</p>

```<code>CREATE SEQUENCE transaction_sequence
  MINVALUE 0
  START WITH (SELECT MAX(trans_seq_no)
     FROM TRANSACTION_LOG)
  INCREMENT BY 1
  CACHE 20;
</code>```

答:
```<code>DECLARE
    v_max NUMBER;
BEGIN
    SELECT (NVL (MAX (<COLUMN_NAME>), 0) + 1) INTO v_max FROM <TABLE_NAME>;
    EXECUTE IMMEDIATE 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || v_max || ' NOCYCLE CACHE 20 NOORDER';
END;
</code>```

Body:
Trying to create a sequence in Oracle that starts with the max value from a specific table. Why does this not work?

CREATE SEQUENCE transaction_sequence
  MINVALUE 0
  START WITH (SELECT MAX(trans_seq_no)
     FROM TRANSACTION_LOG)
  INCREMENT BY 1
  CACHE 20;


问:
Eclipse - Errors running builder on project
I was getting this error constantly in eclipse:

Errors during build. Errors running builder "Integrated External Tool
  Builder" on project  project. The builder launch configuration could
  not be found. Errors running builder "Integrated External Tool
  Builder" on project  project. The builder launch configuration could
  not be found.

答:
I was facing the same issue,

"Errors running builder 'Integrated External Tool Builder' on project
  {PROJECT NAME}"

you must go to your .project file in your work space, and you can put in comment or delete this lines

```<code><buildCommand>
            <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
            <triggers>full,incremental,</triggers>
            ...
            ...

</buildCommand>
</code>```

and after that, you can rebuild your project and it will work correctly.

Reference: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118294

Body:
I was facing the same issue,

"Errors running builder 'Integrated External Tool Builder' on project
  {PROJECT NAME}"

you must go to your .project file in your work space, and you can put in comment or delete this lines

<buildCommand>
            <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
            <triggers>full,incremental,</triggers>
            ...
            ...

</buildCommand>

and after that, you can rebuild your project and it will work correctly.

Reference: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118294


问:
Fedex Shipping Label API required fields
I can't find this information anywhere in the documentation or online. I'm looking to know what are the required fields and in what circumstances they are required.

Right now I'm getting: RequestedShipment Shipper contact - phoneNumber is required as a response from Fedex and my problem is that I have customers that don't have a phone number or, in some cases, the formatting for the phone number is international (which also fails).

Is there any way to not make the phone number a required field when printing a fedex shipping label?

答:
You can read out this ship service document:
https://www.fedex.com/templates/components/apps/wpor/secure/downloads/pdf/201707/FedEx_WebServices_ShipService_WSDLGuide_v2017.pdf

On page number 22 you can get all the parameters, required ones are mentioned in there you have to send in a request for creating a shipping label and getting a tracking number for that shipping service. This pdf may be accessible to you only after login in your FedEx account and you can get success only if you have credentials: test account number, key, password, meter number.

When your whole request is ready if you are in testing mode try sending on:
https://wsbeta.fedex.com:443/web-services/ship or https://wsbeta.fedex.com:443/web-services
and if you are in production remove beta from these links.


问:
How to resize image height and width in php codeigniter

public function resize() {
  $config['width'] = $this->input->post('width');
  $config['height'] = $this->input->post('height');
  $config['maintain_ratio'] = TRUE;
  $config['source_image'] = './uploads1/book.jpg';
  $config['new_image'] = './uploads1/book_new.jpg';
  $this->image_lib->initialize($config);
  $resize = $this->image_lib->resize();

 }```

How to resize image height and width  in php codeigniter, only height is not resizing properly but width i am getting

答:
You have to initialize the library to use it after setting config values:

```<code>$this->load->library('image_lib', $config);
</code>```

Be sure the input values of height is not empty too!

Body:
public function resize() {
  $config['width'] = $this->input->post('width');
  $config['height'] = $this->input->post('height');
  $config['maintain_ratio'] = TRUE;
  $config['source_image'] = './uploads1/book.jpg';
  $config['new_image'] = './uploads1/book_new.jpg';
  $this->image_lib->initialize($config);
  $resize = $this->image_lib->resize();

 }

How to resize image height and width  in php codeigniter, only height is not resizing properly but width i am getting

Body:
You have to initialize the library to use it after setting config values:

$this->load->library('image_lib', $config);

Be sure the input values of height is not empty too!


问:
How do have text appear over my images?
I have written the code the way I like it so far (this site is a work in progress) and I have realized that I need text to appear over the images when I hover my cursor over them. I am a rookie and I have so much going on in my code that I have confused myself so bad I am going to the forums for the first time.

Here is the html:

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding; 80px 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <nav>
    <ul>
      <li> Home </li>
        <div class="logo"></div>
      <li class="dropdown">
        My Work
        <div class="dropdown-content">
          Cars
          Dogs
          Landscapes
          Concerts
          Nature
          Misc
        </div>
      <li> About me </li>
      <li> Contact Me </li>
    </ul>
  </nav>
  <main>
    <div class="port-box">
      <div class="wrapper">

          <div class="img-single">
            <img src="images/hud.jpg">
          </div>

          <div class="img-single">
            <img src="images/rocky.jpeg">
          </div>

          <div class="img-single">
            <img src="images/sunset.jpg">
          </div>

          <div class="img-single">
            <img src="images/concert.jpeg">
          </div>

          <div class="img-single">
            <img src="images/nature.jpg">
          </div>

          <div class="img-single">
            <img src="images/misc.jpeg">
          </div>

      </div>
    </div>
  </main>
  <div class="footer">
  Copyright © 2017 Richard Spradling
  </div>
</body></code>```

I realize there is already a hover effect, I would like to replace that with text appearing. Thank you.

答:
First you should place the text over the image by adding position: relative for parent div and add position: absolute for text and hide it on loading.

And when hover on parent div show the text.

```<code>.img-single {
  position: relative;
}

.img-single .text {
  position: absolute;
  bottom: 0;
  left: 0;
  display: none;
}

.img-single:hover .text {
  display: block;
}
</code>```

Below is the working code

.img-single {
  width: 400px;
  float: left;
  margin: 40px 15px;
  position: relative;
}
.img-single img {
  width: 100%;
  min-height: 100px;
}

.img-single .text {
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 30px;
  color:#fff;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  display: none;
}

.img-single:hover .text {
  display: block;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li> Home </li>

      <div class="logo"></div>

    <li class="dropdown">
      My Work
      <div class="dropdown-content">
        Cars
        Dogs
        Landscapes
        Concerts
        Nature
        Misc
      </div>
      <li> About me </li>
      <li> Contact Me </li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">

        <div class="img-single">
          <img src="http://lorempixel.com/400/200/" alt="img">
          <span class="text">Some text</span>
        </div>

    </div>
  </div>
</main>
<div class="footer">
  Copyright © 2017 Richard Spradling
</div></code>```

Title: How do have text appear over my images?

Body:
I have written the code the way I like it so far (this site is a work in progress) and I have realized that I need text to appear over the images when I hover my cursor over them. I am a rookie and I have so much going on in my code that I have confused myself so bad I am going to the forums for the first time.

Here is the html:

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding; 80px 0px;
}

 Home

        My Work

          Cars
          Dogs
          Landscapes
          Concerts
          Nature
          Misc

 About me

 Contact Me

  Copyright © 2017 Richard Spradling

I realize there is already a hover effect, I would like to replace that with text appearing. Thank you.

Body:
First you should place the text over the image by adding position: relative for parent div and add position: absolute for text and hide it on loading.

And when hover on parent div show the text.

.img-single {
  position: relative;
}

.img-single .text {
  position: absolute;
  bottom: 0;
  left: 0;
  display: none;
}

.img-single:hover .text {
  display: block;
}

Below is the working code

.img-single {
  width: 400px;
  float: left;
  margin: 40px 15px;
  position: relative;
}
.img-single img {
  width: 100%;
  min-height: 100px;
}

.img-single .text {
  position: absolute;
  bottom: 0;
  left: 0;
  font-size: 30px;
  color:#fff;
  background: rgba(0, 0, 0, 0.5);
  width: 100%;
  display: none;
}

.img-single:hover .text {
  display: block;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}

<nav>
  <ul>
    <li><a href="home.html"> Home </a></li>
    <a href="home.html">
      <div class="logo"></div>
    </a>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn active">My Work</a>
      <div class="dropdown-content">
        <a href="#">Cars</a>
        <a href="#">Dogs</a>
        <a href="#">Landscapes</a>
        <a href="#">Concerts</a>
        <a href="#">Nature</a>
        <a href="#">Misc</a>
      </div>
      <li><a href="about.html"> About me </a></li>
      <li><a href="contact.html"> Contact Me </a></li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">
      <a href="cars.html">
        <div class="img-single">
          <img src="http://lorempixel.com/400/200/" alt="img">
          <span class="text">Some text</span>
        </div>
      </a>
    </div>
  </div>
</main>
<div class="footer">
  Copyright &copy; 2017 Richard Spradling
</div>


问:
With Java Spark how do I send a html file as a repsonse
How do I use spark to return an existing page

I have the example working where I just return some text

```<code>import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}
</code>```

I have changed to

```<code>import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}
</code>```

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files

答:
Static content only can be served using the URL of the actual file like you mention in your original question. If you want to map this static file to a specific endpoint, you need to read the content of the file programatically and return the String.

An other method would be to implement your own template engine that just returns the content of the HTML file even though it might be a bit overkill it should be simple enough to do.

Body:
How do I use spark to return an existing page

I have the example working where I just return some text

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

I have changed to

import spark.Service;
import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        staticFiles.externalLocation("C:\\HtmlFolder\\"); // Static files
        init();
        get("/hello", (req, res) -> "Report00001.html");
    }
}

and I want it to display the contents of HtmlFolder\Report00001.hml but it just displays Report0001.html

I cannot see any examples showing how to do this

So if I place a index.html within C:\HtmlFolder\ then that is now displayed when open browser at http://localhost:4567/ but I cannnot see how do a mapping for get requests to display other files


答:
Try using onRestoreInstanceState() callback method to get saved data.

```<code>@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onRestoreInstanceState(savedInstanceState);
 CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
 displayFileName.setText(savedText);
}
</code>```

As per official documentation.

Most implementations will simply use onCreate(Bundle) to restore their
  state, but it is sometimes convenient to do it here after all of the
  initialization has been done or to allow subclasses to decide whether
  to use your default implementation.

So for best practice, keep your view hierarchy in onCreate and restore the previous state in onRestoreInstanceState.

Title: Saving and restoring text when rotating

Body:
Try using onRestoreInstanceState() callback method to get saved data.

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onRestoreInstanceState(savedInstanceState);
 CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
 displayFileName.setText(savedText);
}

As per official documentation.

Most implementations will simply use onCreate(Bundle) to restore their
  state, but it is sometimes convenient to do it here after all of the
  initialization has been done or to allow subclasses to decide whether
  to use your default implementation.

So for best practice, keep your view hierarchy in onCreate and restore the previous state in onRestoreInstanceState.


问:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException when trying to execute Javascript
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

```<code>myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407
</code>```

Once in a while I get the following exception. The Java application does not terminate or crash.

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)
</code>```

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

```<code>int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}
</code>```

UPDATE:

This is the Javascript function returnAllLinkTexts();

```<code>function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}
</code>```

答:
The only thing I can think of why returnAllLinkTexts is breaking (thus you get null) is when it's called before jQuery was loaded.

If possible, try calling browser.executeJavascript after the page finished loading otherwise check for null as others already suggested and you can keep trying to invoke it (using timer for example) until it's not null.

Edit: since you're already using the return value as string, you can return string to begin with, for example:

```<code>return mydata.join(",");
</code>```

Will return the links text separated with comma.

Body:
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407

Once in a while I get the following exception. The Java application does not terminate or crash.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}

UPDATE:

This is the Javascript function returnAllLinkTexts();

function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}

Body:
The only thing I can think of why returnAllLinkTexts is breaking (thus you get null) is when it's called before jQuery was loaded.

If possible, try calling browser.executeJavascript after the page finished loading otherwise check for null as others already suggested and you can keep trying to invoke it (using timer for example) until it's not null.

Edit: since you're already using the return value as string, you can return string to begin with, for example:

return mydata.join(",");

Will return the links text separated with comma.


问:
How to build a dictionary with the values of each country in the same group
I have the following data in a dictionary or a list:

```<code>{'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'}
{'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'}
{'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'}
{'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'}
{'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'}
{'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'}
{'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'}
{'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'}
{'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'}
{'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'}
{'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'}
{'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'}
{'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'}
{'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'}
{'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'}
{'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'}
{'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'}
{'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'}
{'time': '2017 May', 'value': 24.5, 'Country': 'Finland'}
{'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'}
{'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'}
{'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'}
{'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'}
{'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}
</code>```

I would like to know how can I buld a dictionary that for each date, it shows the value for each country like this:

```<code>{'time': '2016 Nov', 'Denmark': 8.0, 'Finland': 19.9 },
{'time': '2016 Dec', 'Denmark': 8.5, 'Finland': 22.4 },
</code>```

And so on...

答:
If input is list of dictionaries first create DataFrame and then pivot, last convert to dict by to_dict:

```<code>d = pd.DataFrame(d).pivot('time','Country','value').reset_index().to_dict('r')
</code>```

Or use set_index with unstack:

```<code>d=pd.DataFrame(d).set_index(['time','Country'])['value'].unstack().reset_index().to_dict('r')
</code>```

```<code>print (d)
[{'Denmark': 8.5, 'time': '2016 Dec', 'Finland': 22.4},
 {'Denmark': 8.0, 'time': '2016 Nov', 'Finland': 19.9},
 {'Denmark': 14.6, 'time': '2017 Apr', 'Finland': 23.6}...
</code>```

Detail:

```<code>#check first 5 rows of DataFrame
print (pd.DataFrame(d).head())
   Country      time  value
0  Denmark  2016 Nov    8.0
1  Denmark  2016 Dec    8.5
2  Denmark  2017 Jan   11.9
3  Denmark  2017 Feb   13.5
4  Denmark  2017 Mar   13.9

print (pd.DataFrame(d).pivot('time','Country','value'))
Country   Denmark  Finland
time
2016 Dec      8.5     22.4
2016 Nov      8.0     19.9
2017 Apr     14.6     23.6
2017 Aug     14.7     25.5
2017 Feb     13.5     20.9
2017 Jan     11.9     22.6
2017 Jul     16.6     24.7
2017 Jun     15.0     24.3
2017 Mar     13.9     23.2
2017 May     13.4     24.5
2017 Oct     14.9     27.2
2017 Sep     16.2     27.1
</code>```

EDIT:

For sorting convert dates to datetimes and then reindex:

```<code>df = pd.DataFrame(d).pivot('time','Country','value')
sort = pd.to_datetime(df.index).sort_values().strftime('%Y %b')
d = df.reindex(sort).reset_index().to_dict('r')
print (d)
</code>```

Detail:

```<code>print (df.reindex(sort))
Country   Denmark  Finland
time
2016 Nov      8.0     19.9
2016 Dec      8.5     22.4
2017 Jan     11.9     22.6
2017 Feb     13.5     20.9
2017 Mar     13.9     23.2
2017 Apr     14.6     23.6
2017 May     13.4     24.5
2017 Jun     15.0     24.3
2017 Jul     16.6     24.7
2017 Aug     14.7     25.5
2017 Sep     16.2     27.1
2017 Oct     14.9     27.2
</code>```

Body:
I have the following data in a dictionary or a list:

{'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'}
{'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'}
{'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'}
{'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'}
{'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'}
{'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'}
{'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'}
{'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'}
{'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'}
{'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'}
{'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'}
{'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'}
{'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'}
{'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'}
{'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'}
{'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'}
{'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'}
{'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'}
{'time': '2017 May', 'value': 24.5, 'Country': 'Finland'}
{'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'}
{'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'}
{'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'}
{'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'}
{'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}

I would like to know how can I buld a dictionary that for each date, it shows the value for each country like this:

{'time': '2016 Nov', 'Denmark': 8.0, 'Finland': 19.9 },
{'time': '2016 Dec', 'Denmark': 8.5, 'Finland': 22.4 },

And so on...

Body:
If input is list of dictionaries first create DataFrame and then pivot, last convert to dict by to_dict:

d = pd.DataFrame(d).pivot('time','Country','value').reset_index().to_dict('r')

Or use set_index with unstack:

d=pd.DataFrame(d).set_index(['time','Country'])['value'].unstack().reset_index().to_dict('r')

print (d)
[{'Denmark': 8.5, 'time': '2016 Dec', 'Finland': 22.4},
 {'Denmark': 8.0, 'time': '2016 Nov', 'Finland': 19.9},
 {'Denmark': 14.6, 'time': '2017 Apr', 'Finland': 23.6}...

Detail:

#check first 5 rows of DataFrame
print (pd.DataFrame(d).head())
   Country      time  value
0  Denmark  2016 Nov    8.0
1  Denmark  2016 Dec    8.5
2  Denmark  2017 Jan   11.9
3  Denmark  2017 Feb   13.5
4  Denmark  2017 Mar   13.9

print (pd.DataFrame(d).pivot('time','Country','value'))
Country   Denmark  Finland
time
2016 Dec      8.5     22.4
2016 Nov      8.0     19.9
2017 Apr     14.6     23.6
2017 Aug     14.7     25.5
2017 Feb     13.5     20.9
2017 Jan     11.9     22.6
2017 Jul     16.6     24.7
2017 Jun     15.0     24.3
2017 Mar     13.9     23.2
2017 May     13.4     24.5
2017 Oct     14.9     27.2
2017 Sep     16.2     27.1

EDIT:

For sorting convert dates to datetimes and then reindex:

df = pd.DataFrame(d).pivot('time','Country','value')
sort = pd.to_datetime(df.index).sort_values().strftime('%Y %b')
d = df.reindex(sort).reset_index().to_dict('r')
print (d)

Detail:

print (df.reindex(sort))
Country   Denmark  Finland
time
2016 Nov      8.0     19.9
2016 Dec      8.5     22.4
2017 Jan     11.9     22.6
2017 Feb     13.5     20.9
2017 Mar     13.9     23.2
2017 Apr     14.6     23.6
2017 May     13.4     24.5
2017 Jun     15.0     24.3
2017 Jul     16.6     24.7
2017 Aug     14.7     25.5
2017 Sep     16.2     27.1
2017 Oct     14.9     27.2


问:
Ionic 3 make promise funtion in constructor
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

```<code>constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}
</code>```

output of above is

```<code>Start
End
Mid
</code>```

Expected output is

```<code>Start
Mid
End
</code>```

答:
Since getData function return a promise, resolve it and put the console inside it </p>

```<code>constructor(){
    console.log("Start");
    this.getData().then(function (snapshot) {
        console.log("End");
    })
}
</code>```

Body:
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}

output of above is

Start
End
Mid

Expected output is

Start
Mid
End

Body:
Since getData function return a promise, resolve it and put the console inside it

constructor(){
    console.log("Start");
    this.getData().then(function (snapshot) {
        console.log("End");
    })
}


问:
Android - Keep ActionBar/Toolbar in front of Fragment animations
I'm using translate animations to slide a fragment in from the bottom and out the top. During this animation, though, the Toolbar or ActionBar is sent to the back, making it look like there's some kind of glitch in the animation (the animated Fragment covers the Toolbar).

Is there a way to make sure the Toolbar is always shown in front of the animation? I did try setting the :zAdjustment to bottom, but that didn't change anything.

Here's one of the animations. The others are just variations of :fromYDelta and :toYDelta.

```<code><set>
    <translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromYDelta="-100%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:duration="1000"/>
</set>
</code>```

The FragmentTransaction

```<code>getSupportFragmentManager().beginTransaction()
        .setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
        .replace(R.id.master_container, getManageFragment())
        .addToBackStack(null)
        .commit();
</code>```

This is my activity_main.xml

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- The main content view -->
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/master_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/navigation_toolbar" />

    </LinearLayout>

    <include layout="@layout/navigation_view" />

</android.support.v4.widget.DrawerLayout>
</code>```

And then this layout is added to master_container

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/global_background"
    app:layout_behavior="com.cohenadair.anglerslog.views.FloatingButtonBehavior">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/main_recycler_view"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingTop="@dimen/margin_half"
        android:paddingBottom="@dimen/margin_half"
        android:clipToPadding="false"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/new_button"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_margin="@dimen/margin_default"
        android:src="@drawable/ic_add"
        app:elevation="0dp"
        app:layout_anchor="@id/main_recycler_view"
        app:layout_anchorGravity="bottom|right|end"
        app:layout_behavior="com.cohenadair.anglerslog.utilities.ScrollingFabBehavior"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

Thank you.

EDIT: This seems to be a similar issue.

答:
If you set Toolbar in Activity then transitions in FrameLayout won't affect toolbar. I have tried like this & it's working

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:contentInsetStartWithNavigation="0dp"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            android:title="@string/app_name"
            android:background="@color/colorPrimaryDark"
            app:contentInsetStartWithNavigation="0dp"/>

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar"/>
    </RelativeLayout>
    <include layout="@layout/navigation_drawer_layout"/>
</android.support.v4.widget.DrawerLayout>
</code>```

For animations:

```<code>getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter_from_top, R.anim.exit_to_bottom, R.anim.enter_from_bottom, R.anim.exit_to_top)
                    .replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
                    .commitAllowingStateLoss();
</code>```

enter_from_bottom.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="100%" android:toYDelta="0%"
        android:duration="700" />
</set>
</code>```

enter_from_top.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="-100%" android:toYDelta="0%"
        android:duration="700"/>
</set>
</code>```

exit_to_bottom.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="100%"
        android:duration="700" />
</set>
</code>```

exit_to_top.xml

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="-100%"
        android:duration="700"/>
</set>
</code>```

Body:
I'm using translate animations to slide a fragment in from the bottom and out the top. During this animation, though, the Toolbar or ActionBar is sent to the back, making it look like there's some kind of glitch in the animation (the animated Fragment covers the Toolbar).

Is there a way to make sure the Toolbar is always shown in front of the animation? I did try setting the :zAdjustment to bottom, but that didn't change anything.

Here's one of the animations. The others are just variations of :fromYDelta and :toYDelta.

<set>
    <translate
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromYDelta="-100%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:duration="1000"/>
</set>

The FragmentTransaction

getSupportFragmentManager().beginTransaction()
        .setCustomAnimations(R.anim.slide_in_bottom, R.anim.slide_out_top, R.anim.slide_in_top, R.anim.slide_out_bottom)
        .replace(R.id.master_container, getManageFragment())
        .addToBackStack(null)
        .commit();

This is my activity_main.xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/master_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include layout="@layout/navigation_toolbar" />

    </LinearLayout>

    <include layout="@layout/navigation_view" />

</android.support.v4.widget.DrawerLayout>

And then this layout is added to master_container

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/global_background"
    app:layout_behavior="com.cohenadair.anglerslog.views.FloatingButtonBehavior">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/main_recycler_view"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingTop="@dimen/margin_half"
        android:paddingBottom="@dimen/margin_half"
        android:clipToPadding="false"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/new_button"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_margin="@dimen/margin_default"
        android:src="@drawable/ic_add"
        app:elevation="0dp"
        app:layout_anchor="@id/main_recycler_view"
        app:layout_anchorGravity="bottom|right|end"
        app:layout_behavior="com.cohenadair.anglerslog.utilities.ScrollingFabBehavior"/>

</android.support.design.widget.CoordinatorLayout>

Thank you.

EDIT: This seems to be a similar issue.

Body:
If you set Toolbar in Activity then transitions in FrameLayout won't affect toolbar. I have tried like this & it's working

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:contentInsetStartWithNavigation="0dp"
            app:layout_collapseMode="pin"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            android:title="@string/app_name"
            android:background="@color/colorPrimaryDark"
            app:contentInsetStartWithNavigation="0dp"/>

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar"/>
    </RelativeLayout>
    <include layout="@layout/navigation_drawer_layout"/>
</android.support.v4.widget.DrawerLayout>

For animations:

getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter_from_top, R.anim.exit_to_bottom, R.anim.enter_from_bottom, R.anim.exit_to_top)
                    .replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName())
                    .commitAllowingStateLoss();

enter_from_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="100%" android:toYDelta="0%"
        android:duration="700" />
</set>

enter_from_top.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="-100%" android:toYDelta="0%"
        android:duration="700"/>
</set>

exit_to_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="100%"
        android:duration="700" />
</set>

exit_to_top.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
    <translate
        android:fromXDelta="0%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="-100%"
        android:duration="700"/>
</set>