问:
Dynamic radio button form react
I am building a dynamic form that fetches an entry from a db. The row results will render in a form and I have a component to render each entry in the form

The component of the form-row:

```<code>class Juego extends React.Component {
    render () {
        return(
            <tr>
                <td>{shortDate(this.props.juego.fecha)}</td>
                <td>
                    <input type="radio" name={`apuesta[${this.props.juego.id}]`}  value="G" id={this.props.juego.id} onChange={this.props.handleChange} />
                    <label>{this.props.juego.local}</label>
                    <span className="pull-right">{this.props.juego.spread_eq_local}</span>
                </td>

                <td>
                    <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="E" id={this.props.juego.id} onChange={this.props.handleChange} />
                    <label>Empate</label>
                    <span className="pull-right">{this.props.juego.spread_empate}</span>
                </td>

                <td>
                    <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="P" id={this.props.juego.id} onChange={this.props.handleChange} />
                    <label>{this.props.juego.visitante}</label>
                    <span className="pull-right">{this.props.juego.spread_eq_visitante}</span>
                </td>
                <td>
                    <input type="number" name={`puntos[${this.props.juego.id}]`} id={this.props.juego.id} onChange={this.props.handleChange} />
                </td>
            </tr>
        )
    }
}
</code>```

The rows are mapped this way:

```<code>juegosList=()=>{
    return (
        <div className="lista-juegos">

            <table className="table table-striped">
                <tbody>
                    {this.props.juegos.map(jueg=><Juego juego={jueg}  key={jueg.id} handleChange={this.handleAddBet} addToState={this.addState}/>)}
                </tbody>
            </table>
        </div>
    )
}
</code>```

And finally rendered on the main component:

```<code>render () {
    return (
        <div className="juegos-form">
            <form onSubmit={this.handleSubmit}>
                {this.props.juegos.length===0?this.empty:this.juegosList()}
                <button className="btn btn-lg btn-success pull-right">Apostar</button>
            </form>
        </div>

    )
}
</code>```

I am trying to achieve this by passing the values of the Juego component into the state of the main component as an array:

```<code>apuestas:[
            {id,
            apuesta,
            puntos},
            {id,
            apuesta,
            puntos}
        ]
</code>```

Something like this, but I am having trouble passing these values into the state of the main component.

Can anyone think of how to make this work or a better approach?

I am using
NodeJS, React, Redux, Express and MySQL.

答:
What you are trying to do is change the state from the parent component using event handled by the child component.

Your parent should look like:

```<code>class MainApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: ''
    }
  }

  handleChange(e) {
    this.setState({
      value: e.target.value
    })
  }

  render() {
    return (
      <div>
        <MainInput
          onChange={this.handleChange.bind(this)}
          />
      </div>
    )
  }
}
</code>```

And your child component:

```<code>class MainInput extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <input
        onChange={this.props.onChange}/>
    )
  }
}
</code>```

Here's a demo: https://codesandbox.io/s/pQJvX03X2

You can see that the state changes dynamically when you start typing on the input.

Title: Dynamic radio button form react

Body:
I am building a dynamic form that fetches an entry from a db. The row results will render in a form and I have a component to render each entry in the form

The component of the form-row:

class Juego extends React.Component {
    render () {
        return(

                {shortDate(this.props.juego.fecha)}

                    <input type="radio" name={`apuesta[${this.props.juego.id}]`}  value="G" id={this.props.juego.id} onChange={this.props.handleChange} />
                    {this.props.juego.local}
                    {this.props.juego.spread_eq_local}

                    <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="E" id={this.props.juego.id} onChange={this.props.handleChange} />
                    Empate
                    {this.props.juego.spread_empate}

                    <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="P" id={this.props.juego.id} onChange={this.props.handleChange} />
                    {this.props.juego.visitante}
                    {this.props.juego.spread_eq_visitante}

                    <input type="number" name={`puntos[${this.props.juego.id}]`} id={this.props.juego.id} onChange={this.props.handleChange} />

        )
    }
}

The rows are mapped this way:

juegosList=()=>{
    return (

                    {this.props.juegos.map(jueg=><Juego juego={jueg}  key={jueg.id} handleChange={this.handleAddBet} addToState={this.addState}/>)}

    )
}

And finally rendered on the main component:

render () {
    return (

            <form onSubmit={this.handleSubmit}>
                {this.props.juegos.length===0?this.empty:this.juegosList()}
                <button className="btn btn-lg btn-success pull-right">Apostar</button>
            </form>

    )
}

I am trying to achieve this by passing the values of the Juego component into the state of the main component as an array:

apuestas:[
            {id,
            apuesta,
            puntos},
            {id,
            apuesta,
            puntos}
        ]

Something like this, but I am having trouble passing these values into the state of the main component.

Can anyone think of how to make this work or a better approach?

I am using
NodeJS, React, Redux, Express and MySQL.

Body:
What you are trying to do is change the state from the parent component using event handled by the child component.

Your parent should look like:

class MainApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: ''
    }
  }

  handleChange(e) {
    this.setState({
      value: e.target.value
    })
  }

  render() {
    return (
      <div>
        <MainInput
          onChange={this.handleChange.bind(this)}
          />
      </div>
    )
  }
}

And your child component:

class MainInput extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <input
        onChange={this.props.onChange}/>
    )
  }
}

Here's a demo: https://codesandbox.io/s/pQJvX03X2

You can see that the state changes dynamically when you start typing on the input.


来源: stackexchange

问:
How to get browser history in android
Is there any way that a firefox browser history can be read using content provider.
I am able to read crome browser history.</p>

答:
It is not possible to get firefox history uri like the chrome provide, i have asked the question on support team of firefox.
https://support.mozilla.org/en-US/questions/1162505</p>

ContentLicense: CC BY-SA 3.0

Title: How to get browser history in android


问:
Go decode json string
discovered that go json decoding is a big pain in the butt so please help.
Here's my json:

```<code> {
   "BTC_BCN":{
      "id":7,
      "last":"0.00000156",
      "lowestAsk":"0.00000156",
      "highestBid":"0.00000155",
      "percentChange":"0.01960784",
      "baseVolume":"4920.84786257",
      "quoteVolume":"3016048494.19305944",
      "isFrozen":"0",
      "high24hr":"0.00000183",
      "low24hr":"0.00000145"
   },
   "BTC_BELA":{
      "id":8,
      "last":"0.00008847",
      "lowestAsk":"0.00008848",
      "highestBid":"0.00008847",
      "percentChange":"-0.00405268",
      "baseVolume":"169.66498061",
      "quoteVolume":"1981232.44495809",
      "isFrozen":"0",
      "high24hr":"0.00008995",
      "low24hr":"0.00008120"
   }, ...
}
</code>```

So I need to put that in a type that I created

```<code>//Crypto is the currency object
type Crypto struct {
    iso           string //this is the key (ex: BTC_BCN)
    id            int
    last          float64
    lowestAsk     float64
    highestBid    float64
    percentChange float64
    baseVolume    float64
    quoteVolume   float64
    isFrozen      int
    high24hr      float64
    low24hr       float64
}
</code>```

and here is what I did so far, but I ended up with the keys in place and an empty value

```<code>func main() {
    // sendEmail("Some text")
    currencies := getCurrencies()
    if currencies == nil {
        return
    }
    fmt.Println(len(currencies))

}

func getCurrencies() map[string]Crypto {
    curList := make(map[string]Crypto)
    resp, err := http.Get("https://poloniex.com/public?command=returnTicker")
    // fmt.Println(err)
    if err != nil {
        sendEmail("Error getting data from poloniex " + err.Error())
        return nil
    }
    body, readErr := ioutil.ReadAll(resp.Body)
    reader := strings.NewReader(string(body))
    jsonErr := json.NewDecoder(reader).Decode(&curList)
    // fmt.Printf("curList is : %#v\n", curList)
    // fmt.Printf("body is : %s\n", string(body))
    if readErr != nil {
        fmt.Printf("readErr: %s\n", readErr.Error())
    }
    if jsonErr != nil {
        fmt.Printf("jsonErr: %s\n", jsonErr.Error())
    }
    for k, v := range curList {
        fmt.Println("k:", k, "v:", v)
    }
    defer resp.Body.Close()
    return curList
}
</code>```

output:

```<code>k: BTC_MAID v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_NOTE v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_VRC v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_DOGE v: {0 0 0 0 0 0 0 0 0 0}...
</code>```

Please excuse my stupid question but I've spent days on it and I think I am missing something.
Cheers.

答:
```<code>//Crypto is the currency object
type Crypto struct {
    Iso           string //this is the key (ex: BTC_BCN)
    Id            int
    Last          string
    LowestAsk     string
    HighestBid    string
    PercentChange string
    BaseVolume    string
    QuoteVolume   string
    IsFrozen      int
    High24hr      string
    Low24hr       string
}
</code>```

You need to to export the fields by capitalising first character. On top of that, your float64 datas are in type: string,hence either you read as string or format before assign to object  Crypto.

Updated:

As pointed by @skomp, you may use a tag to annotate the type you're receiving from json file.

```<code>type Crypto struct {
    CryptoKey
    Id            int
    Last          float64 `json:"last,string"`
    LowestAsk     float64 `json:"lowestAsk,string"`
    HighestBid    float64 `json:"highestBid,string"`
    PercentChange float64 `json:"percentChange,string"`
    BaseVolume    float64 `json:"baseVolume,string"`
    QuoteVolume   float64 `json:"quoteVolume,string"`
    IsFrozen      int
    High24hr      float64 `json:"high24hr,string"`
    Low24hr       float64 `json:"low24hr,string"`
}
</code>```

Title: Go decode json string

Body:
discovered that go json decoding is a big pain in the butt so please help.
Here's my json:

 {
   "BTC_BCN":{
      "id":7,
      "last":"0.00000156",
      "lowestAsk":"0.00000156",
      "highestBid":"0.00000155",
      "percentChange":"0.01960784",
      "baseVolume":"4920.84786257",
      "quoteVolume":"3016048494.19305944",
      "isFrozen":"0",
      "high24hr":"0.00000183",
      "low24hr":"0.00000145"
   },
   "BTC_BELA":{
      "id":8,
      "last":"0.00008847",
      "lowestAsk":"0.00008848",
      "highestBid":"0.00008847",
      "percentChange":"-0.00405268",
      "baseVolume":"169.66498061",
      "quoteVolume":"1981232.44495809",
      "isFrozen":"0",
      "high24hr":"0.00008995",
      "low24hr":"0.00008120"
   }, ...
}

So I need to put that in a type that I created

//Crypto is the currency object
type Crypto struct {
    iso           string //this is the key (ex: BTC_BCN)
    id            int
    last          float64
    lowestAsk     float64
    highestBid    float64
    percentChange float64
    baseVolume    float64
    quoteVolume   float64
    isFrozen      int
    high24hr      float64
    low24hr       float64
}

and here is what I did so far, but I ended up with the keys in place and an empty value

func main() {
    // sendEmail("Some text")
    currencies := getCurrencies()
    if currencies == nil {
        return
    }
    fmt.Println(len(currencies))

}

func getCurrencies() map[string]Crypto {
    curList := make(map[string]Crypto)
    resp, err := http.Get("https://poloniex.com/public?command=returnTicker")
    // fmt.Println(err)
    if err != nil {
        sendEmail("Error getting data from poloniex " + err.Error())
        return nil
    }
    body, readErr := ioutil.ReadAll(resp.Body)
    reader := strings.NewReader(string(body))
    jsonErr := json.NewDecoder(reader).Decode(&curList)
    // fmt.Printf("curList is : %#v\n", curList)
    // fmt.Printf("body is : %s\n", string(body))
    if readErr != nil {
        fmt.Printf("readErr: %s\n", readErr.Error())
    }
    if jsonErr != nil {
        fmt.Printf("jsonErr: %s\n", jsonErr.Error())
    }
    for k, v := range curList {
        fmt.Println("k:", k, "v:", v)
    }
    defer resp.Body.Close()
    return curList
}

output:

k: BTC_MAID v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_NOTE v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_VRC v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_DOGE v: {0 0 0 0 0 0 0 0 0 0}...

Please excuse my stupid question but I've spent days on it and I think I am missing something.
Cheers.

Body:
//Crypto is the currency object
type Crypto struct {
    Iso           string //this is the key (ex: BTC_BCN)
    Id            int
    Last          string
    LowestAsk     string
    HighestBid    string
    PercentChange string
    BaseVolume    string
    QuoteVolume   string
    IsFrozen      int
    High24hr      string
    Low24hr       string
}

You need to to export the fields by capitalising first character. On top of that, your float64 datas are in type: string,hence either you read as string or format before assign to object  Crypto.

Updated:

As pointed by @skomp, you may use a tag to annotate the type you're receiving from json file.

type Crypto struct {
    CryptoKey
    Id            int
    Last          float64 `json:"last,string"`
    LowestAsk     float64 `json:"lowestAsk,string"`
    HighestBid    float64 `json:"highestBid,string"`
    PercentChange float64 `json:"percentChange,string"`
    BaseVolume    float64 `json:"baseVolume,string"`
    QuoteVolume   float64 `json:"quoteVolume,string"`
    IsFrozen      int
    High24hr      float64 `json:"high24hr,string"`
    Low24hr       float64 `json:"low24hr,string"`
}


问:
Is there a “createObject” in java?
In VBScript (and VBA/VB6) there is a function called CreateObject

like this:

```<code>Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")
</code>```

The above code creates an instance of the Excel.Application class, without requiring an early-bound reference to the Excel type library.

Is there something comparable in Java?

答:
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:

Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

```<code>MyObject object = new MyObject();
</code>```

Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

```<code>MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
</code>```

Using clone()
The clone() can be used to create a copy of an existing object.

```<code>MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
</code>```

Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

```<code>ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
</code>```

Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

From https://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/

Title: Is there a “createObject” in java?

Body:
In VBScript (and VBA/VB6) there is a function called CreateObject

like this:

Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")

The above code creates an instance of the Excel.Application class, without requiring an early-bound reference to the Excel type library.

Is there something comparable in Java?

Body:
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:

Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

MyObject object = new MyObject();

Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

Using clone()
The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();

Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

From https://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/


问:
CSS Animation Not Recognizing Nested Spans
I have some HTML, animated by CSS, that nth-child iterates through a list of spans.

/*Body*/
body{
 background-color: #fff;
 font-family: 'Century Gothic', sans-serif;
  font-weight:300;
/*   white-space: pre-wrap; */
}
/*Sentence*/
.sentence{
     color: #222;
     font-size: 20px;
     text-align: left;
}

.orange{
  color: orange !important;
}

/*Vertical Flip*/
.verticalFlip{
 display: inline;
 text-indent: 8px;
}
.verticalFlip span{
 animation: vertical 15s linear infinite 0s;
 -ms-animation: vertical 15s linear infinite 0s;
 -webkit-animation: vertical 15s linear infinite 0s;
 color: #000;
 opacity: 0;
 overflow: hidden;
 position: absolute;
}
.verticalFlip span:nth-child(2){
 animation-delay: 2.5s;
 -ms-animation-delay: 2.5s;
 -webkit-animation-delay: 2.5s;
}
.verticalFlip span:nth-child(3){
 animation-delay: 5s;
 -ms-animation-delay: 5s;
 -webkit-animation-delay: 5s;
}
.verticalFlip span:nth-child(4){
 animation-delay: 7.5s;
 -ms-animation-delay: 7.5s;
 -webkit-animation-delay: 7.5s;
}
.verticalFlip span:nth-child(5){
 animation-delay: 10s;
 -ms-animation-delay: 10s;
 -webkit-animation-delay: 10s;
}

.verticalFlip span:nth-child(6){
 animation-delay: 12.5s;
 -ms-animation-delay: 12.5s;
 -webkit-animation-delay: 12.5s;
}

/*Vertical Flip Animation*/
@-moz-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -moz-transform: rotateX(180deg); }
 10% { opacity: 1; -moz-transform: translateY(0px); }
 25% { opacity: 1; -moz-transform: translateY(0px); }
 30% { opacity: 0; -moz-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0;}
}
@-webkit-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -webkit-transform: rotateX(180deg); }
 10% { opacity: 1; -webkit-transform: translateY(0px); }
 25% { opacity: 1; -webkit-transform: translateY(0px); }
 30% { opacity: 0; -webkit-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}
@-ms-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -ms-transform: rotateX(180deg); }
 10% { opacity: 1; -ms-transform: translateY(0px); }
 25% { opacity: 1; -ms-transform: translateY(0px); }
 30% { opacity: 0; -ms-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="wrapper">

 <h2 class="sentence">
    <div class="verticalFlip">
      <span>1.  Write a Blog post </span>
      <span>2. Click <span class="orange"></span> to open it</span>
      <span>3. ✎ Edit it. </span>
      <span>4. ⇧ Readers upvote best writers</span>
        <span> (✿◠‿◠)  </span>
      <span> ☆</span>
    </div>
  </h2>

</section></code>```

I nested a span inside a span to color one character orange:

```<code>Click <span class="orange"></span> to open it</span>
</code>```

Nth-child triggers the spans one by one, but the colored span throws the timing off. I can see an orange flash, but the character doesn't come up in the sentence. I can retime the nth child animations, but I'm looking for a CSS property like 'not', 'ignore', 'skip this span' or 'recognize this span is nested'.

https://codepen.io/Teeke/pen/Mmdboe

答:
In CSS, it is possible to only target the direct children of an element using the > selector. In your case, each instance of .verticalFlip span would be replaced with .verticalFlip > span. See below:

/*Body*/
body{
 background-color: #fff;
 font-family: 'Century Gothic', sans-serif;
  font-weight:300;
/*   white-space: pre-wrap; */
}
/*Sentence*/
.sentence{
     color: #222;
     font-size: 20px;
     text-align: left;
}

.orange{
  color: orange !important;
}
/*Wrapper*/
/* .wrapper{
    background-color: #f5f5f5;
    font-family: 'Raleway', sans-serif;
    margin: 100px auto;
    padding: 40px 40px;
    position: relative;
    width: 70%;
} */

/*Vertical Flip*/
.verticalFlip{
 display: inline;
 text-indent: 8px;
}
.verticalFlip > span{
 animation: vertical 15s linear infinite 0s;
 -ms-animation: vertical 15s linear infinite 0s;
 -webkit-animation: vertical 15s linear infinite 0s;
 color: #000;
 opacity: 0;
 overflow: hidden;
 position: absolute;
}
.verticalFlip > span:nth-child(2){
 animation-delay: 2.5s;
 -ms-animation-delay: 2.5s;
 -webkit-animation-delay: 2.5s;
}
.verticalFlip > span:nth-child(3){
 animation-delay: 5s;
 -ms-animation-delay: 5s;
 -webkit-animation-delay: 5s;
}
.verticalFlip > span:nth-child(4){
 animation-delay: 7.5s;
 -ms-animation-delay: 7.5s;
 -webkit-animation-delay: 7.5s;
}
.verticalFlip > span:nth-child(5){
 animation-delay: 10s;
 -ms-animation-delay: 10s;
 -webkit-animation-delay: 10s;
}

.verticalFlip > span:nth-child(6){
 animation-delay: 12.5s;
 -ms-animation-delay: 12.5s;
 -webkit-animation-delay: 12.5s;
}

/*Vertical Flip Animation*/
@-moz-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -moz-transform: rotateX(180deg); }
 10% { opacity: 1; -moz-transform: translateY(0px); }
 25% { opacity: 1; -moz-transform: translateY(0px); }
 30% { opacity: 0; -moz-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0;}
}
@-webkit-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -webkit-transform: rotateX(180deg); }
 10% { opacity: 1; -webkit-transform: translateY(0px); }
 25% { opacity: 1; -webkit-transform: translateY(0px); }
 30% { opacity: 0; -webkit-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}
@-ms-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -ms-transform: rotateX(180deg); }
 10% { opacity: 1; -ms-transform: translateY(0px); }
 25% { opacity: 1; -ms-transform: translateY(0px); }
 30% { opacity: 0; -ms-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="wrapper">

 <h2 class="sentence">
    <div class="verticalFlip">
      <span>1.  Write a Blog post </span>
      <span>2. Click <span class="orange"></span> to open it</span>
      <span>3. ✎ Edit it. </span>
      <span>4. ⇧ Readers upvote best writers</span>
        <span> (✿◠‿◠)  </span>
      <span> ☆</span>
    </div>
  </h2>

</section></code>```

Body:
I have some HTML, animated by CSS, that nth-child iterates through a list of spans.

/*Body*/
body{
 background-color: #fff;
 font-family: 'Century Gothic', sans-serif;
  font-weight:300;
/*   white-space: pre-wrap; */
}
/*Sentence*/
.sentence{
     color: #222;
     font-size: 20px;
     text-align: left;
}

.orange{
  color: orange !important;
}

/*Vertical Flip*/
.verticalFlip{
 display: inline;
 text-indent: 8px;
}
.verticalFlip span{
 animation: vertical 15s linear infinite 0s;
 -ms-animation: vertical 15s linear infinite 0s;
 -webkit-animation: vertical 15s linear infinite 0s;
 color: #000;
 opacity: 0;
 overflow: hidden;
 position: absolute;
}
.verticalFlip span:nth-child(2){
 animation-delay: 2.5s;
 -ms-animation-delay: 2.5s;
 -webkit-animation-delay: 2.5s;
}
.verticalFlip span:nth-child(3){
 animation-delay: 5s;
 -ms-animation-delay: 5s;
 -webkit-animation-delay: 5s;
}
.verticalFlip span:nth-child(4){
 animation-delay: 7.5s;
 -ms-animation-delay: 7.5s;
 -webkit-animation-delay: 7.5s;
}
.verticalFlip span:nth-child(5){
 animation-delay: 10s;
 -ms-animation-delay: 10s;
 -webkit-animation-delay: 10s;
}

.verticalFlip span:nth-child(6){
 animation-delay: 12.5s;
 -ms-animation-delay: 12.5s;
 -webkit-animation-delay: 12.5s;
}

/*Vertical Flip Animation*/
@-moz-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -moz-transform: rotateX(180deg); }
 10% { opacity: 1; -moz-transform: translateY(0px); }
 25% { opacity: 1; -moz-transform: translateY(0px); }
 30% { opacity: 0; -moz-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0;}
}
@-webkit-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -webkit-transform: rotateX(180deg); }
 10% { opacity: 1; -webkit-transform: translateY(0px); }
 25% { opacity: 1; -webkit-transform: translateY(0px); }
 30% { opacity: 0; -webkit-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}
@-ms-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -ms-transform: rotateX(180deg); }
 10% { opacity: 1; -ms-transform: translateY(0px); }
 25% { opacity: 1; -ms-transform: translateY(0px); }
 30% { opacity: 0; -ms-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}

      1.  Write a Blog post
      2. Click  to open it
      3. ✎ Edit it.
      4. ⇧ Readers upvote best writers
         (✿◠‿◠)
       ☆

I nested a span inside a span to color one character orange:

Click  to open it

Nth-child triggers the spans one by one, but the colored span throws the timing off. I can see an orange flash, but the character doesn't come up in the sentence. I can retime the nth child animations, but I'm looking for a CSS property like 'not', 'ignore', 'skip this span' or 'recognize this span is nested'.

https://codepen.io/Teeke/pen/Mmdboe

Body:
In CSS, it is possible to only target the direct children of an element using the > selector. In your case, each instance of .verticalFlip span would be replaced with .verticalFlip > span. See below:

/*Body*/
body{
 background-color: #fff;
 font-family: 'Century Gothic', sans-serif;
  font-weight:300;
/*   white-space: pre-wrap; */
}
/*Sentence*/
.sentence{
     color: #222;
     font-size: 20px;
     text-align: left;
}

.orange{
  color: orange !important;
}
/*Wrapper*/
/* .wrapper{
    background-color: #f5f5f5;
    font-family: 'Raleway', sans-serif;
    margin: 100px auto;
    padding: 40px 40px;
    position: relative;
    width: 70%;
} */

/*Vertical Flip*/
.verticalFlip{
 display: inline;
 text-indent: 8px;
}
.verticalFlip > span{
 animation: vertical 15s linear infinite 0s;
 -ms-animation: vertical 15s linear infinite 0s;
 -webkit-animation: vertical 15s linear infinite 0s;
 color: #000;
 opacity: 0;
 overflow: hidden;
 position: absolute;
}
.verticalFlip > span:nth-child(2){
 animation-delay: 2.5s;
 -ms-animation-delay: 2.5s;
 -webkit-animation-delay: 2.5s;
}
.verticalFlip > span:nth-child(3){
 animation-delay: 5s;
 -ms-animation-delay: 5s;
 -webkit-animation-delay: 5s;
}
.verticalFlip > span:nth-child(4){
 animation-delay: 7.5s;
 -ms-animation-delay: 7.5s;
 -webkit-animation-delay: 7.5s;
}
.verticalFlip > span:nth-child(5){
 animation-delay: 10s;
 -ms-animation-delay: 10s;
 -webkit-animation-delay: 10s;
}

.verticalFlip > span:nth-child(6){
 animation-delay: 12.5s;
 -ms-animation-delay: 12.5s;
 -webkit-animation-delay: 12.5s;
}

/*Vertical Flip Animation*/
@-moz-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -moz-transform: rotateX(180deg); }
 10% { opacity: 1; -moz-transform: translateY(0px); }
 25% { opacity: 1; -moz-transform: translateY(0px); }
 30% { opacity: 0; -moz-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0;}
}
@-webkit-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -webkit-transform: rotateX(180deg); }
 10% { opacity: 1; -webkit-transform: translateY(0px); }
 25% { opacity: 1; -webkit-transform: translateY(0px); }
 30% { opacity: 0; -webkit-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}
@-ms-keyframes vertical{
 0% { opacity: 0; }
 5% { opacity: 0; -ms-transform: rotateX(180deg); }
 10% { opacity: 1; -ms-transform: translateY(0px); }
 25% { opacity: 1; -ms-transform: translateY(0px); }
 30% { opacity: 0; -ms-transform: translateY(0px); }
 80% { opacity: 0; }
 100% { opacity: 0; }
}

<section class="wrapper">

 <h2 class="sentence">
    <div class="verticalFlip">
      <span>1.  Write a Blog post </span>
      <span>2. Click <span class="orange"></span> to open it</span>
      <span>3. ✎ Edit it. </span>
      <span>4. ⇧ Readers upvote best writers</span>
        <span> (✿◠‿◠)  </span>
      <span> ☆</span>
    </div>
  </h2>

</section>


问:
Text field in same line HTML
How to make multiple text fields in the same line.

This is my code:

```<code><div class="col-lg-2">
    <div class="form-group">
        <label>Working experience</label>
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day
    </div>
</div>
</code>```

答:
Use Bootstrap:</p>

```<code><form class="form-inline" action="/action_page.php">
  <label>Working experience : </label>
  <div class="form-group">
      <input type="text" class="form-control" id="year" placeholder="Year" name="year">
  </div>

  <div class="form-group">
      <input type="text" class="form-control" id="month" placeholder="Month" name="month">
  </div>
  <div class="form-group">
      <input type="text" class="form-control" id="day" placeholder="Day" name="day">
  </div>
</form>
</code>```

Title: Text field in same line HTML

Body:
How to make multiple text fields in the same line.

This is my code:

        Working experience
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day

Body:
Use Bootstrap:

<form class="form-inline" action="/action_page.php">
  <label>Working experience : </label>
  <div class="form-group">
      <input type="text" class="form-control" id="year" placeholder="Year" name="year">
  </div>

  <div class="form-group">
      <input type="text" class="form-control" id="month" placeholder="Month" name="month">
  </div>
  <div class="form-group">
      <input type="text" class="form-control" id="day" placeholder="Day" name="day">
  </div>
</form>


问:
How to use python-request to post a file on a Rails App
I have a Rails app server. I want to build a Python client that uploads an image.

I want to do something like this:

```<code>def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        json    = {
            'entry': {
                'entry_id': entry_id,
            }
        },
        files   = {
            "entry['photo']": (
                os.path.basename(image_path),
                open(image_path, 'rb'),
                'image/jpg',
                {'Expires': '0'}
            )
        }
    )
</code>```

I need the image nested into the 'entry' key. The above code does not work because the key "entry['photo']" isn't valid.

How do I do this?

Thank you so much for your help!

答:
I figured it out:</p>

```<code>def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        files   = {
            'entry[entry_id]': (None, entry_id, 'text'),
            'entry[photo]': (os.path.basename(image_path), open(image_path, 'rb'), 'image/jpg', {'Expires': '0'})
        }
    )
</code>```

Body:
I have a Rails app server. I want to build a Python client that uploads an image.

I want to do something like this:

def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        json    = {
            'entry': {
                'entry_id': entry_id,
            }
        },
        files   = {
            "entry['photo']": (
                os.path.basename(image_path),
                open(image_path, 'rb'),
                'image/jpg',
                {'Expires': '0'}
            )
        }
    )

I need the image nested into the 'entry' key. The above code does not work because the key "entry['photo']" isn't valid.

How do I do this?

Thank you so much for your help!

Body:
I figured it out:

def add_photo(entry_id, image_path):

    return requests.post(
        url     = URL,
        headers = HEADER,
        files   = {
            'entry[entry_id]': (None, entry_id, 'text'),
            'entry[photo]': (os.path.basename(image_path), open(image_path, 'rb'), 'image/jpg', {'Expires': '0'})
        }
    )


问:
How do I use a Perl package known only in runtime?
I have a Perl program, that needs to use packages (that I also write). Some of those packages are only chosen in Runtime (based on some environment variable). I don't want to put in my code a "use" line for all of those packages, of course, but only one "use" line, based on this variable, something like:

```<code>use $ENV{a};
</code>```

Unfortunately, this doesn't work, of course. Any ideas on how to do this?

Thanks in advance,
Oren

答:
I think that a module loaded in runtime can be a Plugin. I have this kind of problem, having specific modules to some cases that are loaded in run time as plugins with Module::Pluggable.

Maybe you need to change the logic of your modules, but it works and scale very well  (my app started with four modules and now have twenty and it's growing).

OwnerDisplayName: Oren Sarid

ContentLicense: CC BY-SA 2.5

Body:
I have a Perl program, that needs to use packages (that I also write). Some of those packages are only chosen in Runtime (based on some environment variable). I don't want to put in my code a "use" line for all of those packages, of course, but only one "use" line, based on this variable, something like:

use $ENV{a};

Unfortunately, this doesn't work, of course. Any ideas on how to do this?

Thanks in advance,
Oren

LastEditorDisplayName: brian d foy

OwnerDisplayName: Frederico


问:
what is the actual use of interface in java?

Possible Duplicates:

  Abstract class and Interface class?

  Java: interface / abstract classes / abstract method

In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

答:
What you like : thousands of abstract methods in one Abstract Class and inherit this class OR make as many interfaces for specific abstract methods and use those only you want by inheriting as many interfaces as needed...

```<code>abstract class A
{
 //thousands of abstract method();
 abstract methodA();
 abstract methodB();
 abstract methodC();
}

//OR
interface ForOnlymethodA
{
 void methodA();
}
interface FormethodBandmethodC
{
 void methodB();
 void methodC();
}
</code>```

So, use that method only what you just need by inheriting particular interface, if you are inheriting Abstract classes then you are unnecessarily inheriting all methods that you don't need in one class and may be needed in some other classes..

Body:
What you like : thousands of abstract methods in one Abstract Class and inherit this class OR make as many interfaces for specific abstract methods and use those only you want by inheriting as many interfaces as needed...

abstract class A
{
 //thousands of abstract method();
 abstract methodA();
 abstract methodB();
 abstract methodC();
}

//OR
interface ForOnlymethodA
{
 void methodA();
}
interface FormethodBandmethodC
{
 void methodB();
 void methodC();
}

So, use that method only what you just need by inheriting particular interface, if you are inheriting Abstract classes then you are unnecessarily inheriting all methods that you don't need in one class and may be needed in some other classes..


问:
How to deal with csrf security in codeigniter
I have a project that we should interacting within 2 different application using CI. I use post method for sending request from 1st aplication to 2nd aplication. After I configure the csrf and test using form i got output

```<code>An Error Was Encountered.The action you have requested is not allowed.
</code>```

I want to know how to handle this?
and i'm using CI v2

答:
Well I believe that you have done proper setup for CSRF. If not please refer Codeigniter CSRF documentation. For this below is link.
https://www.codeigniter.com/user_guide/libraries/security.html#cross-site-request-forgery-csrf

Now, for APIs you need to whitelist that URIs from CSRF.

for this use like this,

```<code>$config['csrf_exclude_uris'] = array('api/person/add', 'api/person/edit/[0-9]+');
</code>```

Regular expressions are also supported (case-insensitive):

```<code>    $config['csrf_exclude_uris'] = array(
        'api/record/[0-9]+',
        'api/title/[a-z]+'
    );
</code>```

Body:
I have a project that we should interacting within 2 different application using CI. I use post method for sending request from 1st aplication to 2nd aplication. After I configure the csrf and test using form i got output

An Error Was Encountered.The action you have requested is not allowed.

I want to know how to handle this?
and i'm using CI v2

Body:
Well I believe that you have done proper setup for CSRF. If not please refer Codeigniter CSRF documentation. For this below is link.
https://www.codeigniter.com/user_guide/libraries/security.html#cross-site-request-forgery-csrf

Now, for APIs you need to whitelist that URIs from CSRF.

for this use like this,

$config['csrf_exclude_uris'] = array('api/person/add', 'api/person/edit/[0-9]+');

Regular expressions are also supported (case-insensitive):

    $config['csrf_exclude_uris'] = array(
        'api/record/[0-9]+',
        'api/title/[a-z]+'
    );


问:
how to call a string from a method from another class Android
Hello I am new to android,java and I want to use the string from a method from another class. Specifically  I want to use the String s from to class Test to class MainActivity. I tried to call it like

```<code>Test.AnswerQ1
</code>```

but it says that cannot resolve symbol "AnswerQ1"

This is my Test class

```<code>public class Test extends Activity {

 private RadioGroup radioGroupQuestion1;
 private RadioButton radioButtonQuestion1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   radioGroupQuestion1 = (RadioGroup) findViewById(R.id.radioGroupQ1);

   Button NextButton = (Button) findViewById(R.id.Q1NextButton);
    NextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

           int selectedId =  radioGroupQuestion1.getCheckedRadioButtonId();
            radioButtonQuestion1 = (RadioButton) findViewById(selectedId);
            String AnswerQ1 = radioButtonQuestion1.getText().toString();
            String Question1 = getString(R.string.Q1);
            System.out.println(Question1);

           System.out.println(AnswerQ1);

           Intent myIntent = new Intent(view.getContext(),  Question2.class);
            startActivityForResult(myIntent, 0);
        }
    });
}
</code>```

And this is my MainActivity class

```<code>public class MainActivity extends Activity{

String myData = Test.s;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   System.out.println(myData);

   }
}
</code>```

答:
```<code>Try with initializing string on the top of an onCreate method.

public class Test extends Activity {

public static String s = "hello world";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   }
}
</code>```

Body:
Hello I am new to android,java and I want to use the string from a method from another class. Specifically  I want to use the String s from to class Test to class MainActivity. I tried to call it like

Test.AnswerQ1

but it says that cannot resolve symbol "AnswerQ1"

This is my Test class

public class Test extends Activity {

 private RadioGroup radioGroupQuestion1;
 private RadioButton radioButtonQuestion1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   radioGroupQuestion1 = (RadioGroup) findViewById(R.id.radioGroupQ1);

   Button NextButton = (Button) findViewById(R.id.Q1NextButton);
    NextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

           int selectedId =  radioGroupQuestion1.getCheckedRadioButtonId();
            radioButtonQuestion1 = (RadioButton) findViewById(selectedId);
            String AnswerQ1 = radioButtonQuestion1.getText().toString();
            String Question1 = getString(R.string.Q1);
            System.out.println(Question1);

           System.out.println(AnswerQ1);

           Intent myIntent = new Intent(view.getContext(),  Question2.class);
            startActivityForResult(myIntent, 0);
        }
    });
}

And this is my MainActivity class

public class MainActivity extends Activity{

String myData = Test.s;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   System.out.println(myData);

   }
}


问:
Can I use Firebase for sending SMS to users without using Twilio?
I used to use Firebase + Twilio to send SMS to any devices,
but I'm not sure that I can send SMS by using Firebase only or not?

Does Firebase have an API for sending SMS?

答:
You can send SMS Verification using Firebase and you cannot send ordinary SMS through Firebase. You can send using Twilio instead.

Even for SMS verification, you have to wait until they release the API docs for SMS verification through Android.
https://firebase.google.com/docs/auth/android/phone-auth


问:
Multiple join in Entity Framework and include all data
I want to write a query in Entity Framework that has multiple joins.  The only problem is the tables arn't related using their primary / foreign keys (its the Umbraco database), as such I can't use .Include and the Navigation properties.

Essentially the query I would like to run is this:

```<code>select t.*, n.* from cmsContentType t
inner join cmsContentTypeAllowedContentType a on t.nodeId = a.Id
inner join vicinity.DocumentTypeExtendedProperty x on x.UmbracoDocumentTypeId = t.pk
inner join umbracoNode n on n.id = t.nodeId
</code>```

I have two EF entities mapped to cmsContentType and umbracoNode as such I would like them to be populated as if I was running the query like

```<code>var q = from p in cmsContentType.Include("umbracoNode")
</code>```

How can this be done

答:
Try this it will surely work

```<code>var Salary = from SalaryTable in testEntity.Salary
             from MonthTable in testEntity.Month
             where SalaryTable.Month == MonthTable.Month1
             select SalaryTable,
</code>```

Also keep in mind that you cant return an anonymous type ie data from both the tables in a single list or var for that you have to create a class with properties you need to return and iterate through it and return the newly created class as a  list to get the desired output.

Body:
I want to write a query in Entity Framework that has multiple joins.  The only problem is the tables arn't related using their primary / foreign keys (its the Umbraco database), as such I can't use .Include and the Navigation properties.

Essentially the query I would like to run is this:

select t.*, n.* from cmsContentType t
inner join cmsContentTypeAllowedContentType a on t.nodeId = a.Id
inner join vicinity.DocumentTypeExtendedProperty x on x.UmbracoDocumentTypeId = t.pk
inner join umbracoNode n on n.id = t.nodeId

I have two EF entities mapped to cmsContentType and umbracoNode as such I would like them to be populated as if I was running the query like

var q = from p in cmsContentType.Include("umbracoNode")

How can this be done

Body:
Try this it will surely work

var Salary = from SalaryTable in testEntity.Salary
             from MonthTable in testEntity.Month
             where SalaryTable.Month == MonthTable.Month1
             select SalaryTable,

Also keep in mind that you cant return an anonymous type ie data from both the tables in a single list or var for that you have to create a class with properties you need to return and iterate through it and return the newly created class as a  list to get the desired output.


问:
VB.Net Window Programming database coonection open close
I am working on a window project using VB.net. On every form of my project I opened Microsoft access database connection on form load and closed on form closing event. So I want to ask that this is good practice to open/close database connection on every form.</p>

答:
It is good practice to create/open/close db connection every time you execute some query.

Notice that by create/open/close I mean instantiating new instance of SqlConnection.

Under the hood ADO.NET will open real, physical connection to the database server only once and re-use it every time you will open new connection by your code.

So every query should be execute with own new connection

```<code>Using connection As SqlConnection = new SqlConnection(yourConnectionString)
    Using command As SqlCommand = new SqlCommand(sqlQuery, connection)
        return command.ExecuteNonQuery();
    End Using
End Using
</code>```

If you open connection in Form_Load and close it in Form_Closing it possible that when exception thrown while form is opened your connection will remain opened.

By reducing amount of time when connection is "opened" in your code you can handle this situation by using Using keyword and avoid using of "ugly" try .. catch everywhere

And I hope you are using sql parameters (SqlParameter) in your queries.

Body:
It is good practice to create/open/close db connection every time you execute some query.

Notice that by create/open/close I mean instantiating new instance of SqlConnection.

Under the hood ADO.NET will open real, physical connection to the database server only once and re-use it every time you will open new connection by your code.

So every query should be execute with own new connection

Using connection As SqlConnection = new SqlConnection(yourConnectionString)
    Using command As SqlCommand = new SqlCommand(sqlQuery, connection)
        return command.ExecuteNonQuery();
    End Using
End Using

If you open connection in Form_Load and close it in Form_Closing it possible that when exception thrown while form is opened your connection will remain opened.

By reducing amount of time when connection is "opened" in your code you can handle this situation by using Using keyword and avoid using of "ugly" try .. catch everywhere

And I hope you are using sql parameters (SqlParameter) in your queries.


问:
How to Http post to django server from android?
I am trying to send post request to my django APi from but It does not give any error it works fine but still django does not recieve any data.
My view goes like this.

```<code>def add(request):
    if request.method == "POST":
        form = bookForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            data.save()
            return redirect('/books')
    else:
        form = bookForm
return render(request, 'book_edit.html', {'form': form})
</code>```

And my Http post method is.

```<code>try{
                Log.w("this","Started");
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new  HttpPost("http://vidu171.pythonanywhere.com/books/add");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("title", params[0]));
                nameValuePairs.add(new BasicNameValuePair("author","vidu"));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                Log.w("htt response",response.toString());
 }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());

            }
</code>```

I have given the permission the url to the form is
http://vidu171.pythonanywhere.com/books/add . Thanks in advance

答: I would suggest that for making API calls in Django from other sources like Android Apps, its better to use Rest APIs, in case of Django, try using Django Rest Framework.You can start by this Tutorial</p>

Body:
I am trying to send post request to my django APi from but It does not give any error it works fine but still django does not recieve any data.
My view goes like this.

def add(request):
    if request.method == "POST":
        form = bookForm(request.POST)
        if form.is_valid():
            data = form.save(commit=False)
            data.save()
            return redirect('/books')
    else:
        form = bookForm
return render(request, 'book_edit.html', {'form': form})

And my Http post method is.

try{
                Log.w("this","Started");
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new  HttpPost("http://vidu171.pythonanywhere.com/books/add");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("title", params[0]));
                nameValuePairs.add(new BasicNameValuePair("author","vidu"));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                Log.w("htt response",response.toString());
 }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());

            }

I have given the permission the url to the form is
http://vidu171.pythonanywhere.com/books/add . Thanks in advance


问:
Split responsive menu into two coloumns
This is the website I'm working on http://www.jokerleb.com/ and I'm using this https://responsive.menu, the free version. it will appear on devices 400px and smaller.

How to split its columns into 2 like so?

Don't know how to edit the CSS to make it look right, if it's possible in the first place.

答:
You'll want to use media queries, so something like this should do it for you:

```<code><style>
@media screen and (max-width: 400px) {
     #responsive-menu-container li.responsive-menu-item {
         width: 50%;
         display: inline-block;
     }
}
</style>
</code>```

Note that you may need to play around with this CSS a little, since widths will vary based upon padding, margin and the display type.  If you provide a sample of your CSS (or better yet a fiddle) I can help you more exactly.

The lines above make it look like this once the category button is clicked:

If you'd prefer the thing go the whole width, include this in your @media option as well:

```<code>#responsive-menu-container {
    width:100%;
}
</code>```

OwnerDisplayName: Lynob

Title: Split responsive menu into two coloumns

Body:
You'll want to use media queries, so something like this should do it for you:

<style>
@media screen and (max-width: 400px) {
     #responsive-menu-container li.responsive-menu-item {
         width: 50%;
         display: inline-block;
     }
}
</style>

Note that you may need to play around with this CSS a little, since widths will vary based upon padding, margin and the display type.  If you provide a sample of your CSS (or better yet a fiddle) I can help you more exactly.

The lines above make it look like this once the category button is clicked:

If you'd prefer the thing go the whole width, include this in your @media option as well:

#responsive-menu-container {
    width:100%;
}


问:
Record reader that can split by two kinds of separators
I have a case where I need to read files with lines of the format

```<code>Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3
</code>```

While one way to achive this would be to use a record reader like KeyValueLineRecordReader with the separator #. But I will have to split the key and value on , in my UDF using String.split which I feel can slow down the execution.

 1. Are there any record readers that serve formats of this type?
 2. If one such a record writer doesn't exist, what are my alternatives for reading such a line efficiently?

Input data is ~10GB.

答:
You can use regex in the split</p>

```<code>String line = "Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3";

String arr [] = line.split(",|#");

for (String s : arr) {
    System.out.println(s);
}
</code>```

Body:
I have a case where I need to read files with lines of the format

Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3

While one way to achive this would be to use a record reader like KeyValueLineRecordReader with the separator #. But I will have to split the key and value on , in my UDF using String.split which I feel can slow down the execution.

 1. Are there any record readers that serve formats of this type?
 2. If one such a record writer doesn't exist, what are my alternatives for reading such a line efficiently?

Input data is ~10GB.

Body:
You can use regex in the split

String line = "Field1,Field2,Field3,Field4,Field5,Field6#Field1,Field2,Field3";

String arr [] = line.split(",|#");

for (String s : arr) {
    System.out.println(s);
}


问:
CasperJS - DOM methods don't get executed inside evaluate() function
This is the the part of the code which is problametic:

```<code>var obj = {};

function putInObject() {
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;
}

casper.then(function(){
    casper.wait(1000,function(){

        links = this.evaluate(getItemLinks);

        casper.each(links, function(self, link) {
            self.thenOpen(link, function() {

                this.echo(this.getTitle());

                this.wait(7000, function(){
                    console.log("**************** \n WebPage is loaded \n ****************");

                    // Appearantly, The putInObject() doesn't run and "obj" remains null

                    casper.evaluate(putInObject);
                    this.echo(obj);

                });

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

the putInObject() function doesn't run, even I replaced casper.evaluate(putInObject); with this:

```<code>this.evaluate(function() {
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;
});
</code>```

But it didn't work either and obj is printed to console like [object Object].

The this.echo(this.getTitle()); however, works fine and prints the title of the page in the console.

This the log of the above code:

```<code>[debug] [phantom] opening url: https://example.com/category/section/, HTTP GET
[debug] [phantom] Navigation requested: url=https://example.com/category/section/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "https://example.com/category/section/"
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://staticxx.facebook.com/connect/xd_arbiter/r/0F7S7QWJ0Ac.js?version=42#channel=f1413c20e7ccaa&origin=https%3A%2F%2Fexample.com, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 12/28 https://example.com/category/section/ (HTTP 200)
WebPage's Title: Section Name
[info] [phantom] Step anonymous 12/28: done in 81055ms.
[info] [phantom] Step _step 13/29 https://example.com/category/section/ (HTTP 200)
[info] [phantom] Step _step 13/29: done in 81075ms.
[info] [phantom] wait() finished waiting for 7000ms.
[info] [phantom] Step anonymous 14/30 https://example.com/category/section/ (HTTP 200)
****************
WebPage is loaded
****************
[object Object]
</code>```

答:
page.evaluate is like a portal into another world that is not the same as ours. There may be an object by the name of obj there, but it's not the same as obj declared at the start of your CasperJs script. These are differrent objects. What happens in page.evaluate, stays in page.evaluate - unless you specifically request some data be returned back.

```<code>// This function will run inside of a web-page, not in the CasperJS script
function putInObject() {
     var obj = {}; // UPDATED: here we also need to init this object
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;

     // return data from a web page context to CasperJS context
     return obj;
}

...

     // receive data in CasperJS context
     obj = casper.evaluate(putInObject);

     // If you want to view object's contents
     console.log(JSON.stringify(obj));
</code>```

Body:
This is the the part of the code which is problametic:

var obj = {};

function putInObject() {
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;
}

casper.then(function(){
    casper.wait(1000,function(){

        links = this.evaluate(getItemLinks);

        casper.each(links, function(self, link) {
            self.thenOpen(link, function() {

                this.echo(this.getTitle());

                this.wait(7000, function(){
                    console.log("**************** \n WebPage is loaded \n ****************");

                    // Appearantly, The putInObject() doesn't run and "obj" remains null

                    casper.evaluate(putInObject);
                    this.echo(obj);

                });

            });
        });
    });
});

the putInObject() function doesn't run, even I replaced casper.evaluate(putInObject); with this:

this.evaluate(function() {
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;
});

But it didn't work either and obj is printed to console like [object Object].

The this.echo(this.getTitle()); however, works fine and prints the title of the page in the console.

This the log of the above code:

[debug] [phantom] opening url: https://example.com/category/section/, HTTP GET
[debug] [phantom] Navigation requested: url=https://example.com/category/section/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "https://example.com/category/section/"
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://staticxx.facebook.com/connect/xd_arbiter/r/0F7S7QWJ0Ac.js?version=42#channel=f1413c20e7ccaa&origin=https%3A%2F%2Fexample.com, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 12/28 https://example.com/category/section/ (HTTP 200)
WebPage's Title: Section Name
[info] [phantom] Step anonymous 12/28: done in 81055ms.
[info] [phantom] Step _step 13/29 https://example.com/category/section/ (HTTP 200)
[info] [phantom] Step _step 13/29: done in 81075ms.
[info] [phantom] wait() finished waiting for 7000ms.
[info] [phantom] Step anonymous 14/30 https://example.com/category/section/ (HTTP 200)
****************
WebPage is loaded
****************
[object Object]

Body:
page.evaluate is like a portal into another world that is not the same as ours. There may be an object by the name of obj there, but it's not the same as obj declared at the start of your CasperJs script. These are differrent objects. What happens in page.evaluate, stays in page.evaluate - unless you specifically request some data be returned back.

// This function will run inside of a web-page, not in the CasperJS script
function putInObject() {
     var obj = {}; // UPDATED: here we also need to init this object
     obj.title = document.querySelector('[itemprop="title"]').innerText;
     obj.description = document.querySelector('[itemprop="description"]').innerText;

     // return data from a web page context to CasperJS context
     return obj;
}

...

     // receive data in CasperJS context
     obj = casper.evaluate(putInObject);

     // If you want to view object's contents
     console.log(JSON.stringify(obj));


答:
Don't declare a static member inside instance method.

You must declare a static member as class member not local member.

Example:

```<code>public class Test extends Activity {
    public static String s = "hello world";

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

Title: how to call a string from a method from another class Android

Body:
Don't declare a static member inside instance method.

You must declare a static member as class member not local member.

Example:

public class Test extends Activity {
    public static String s = "hello world";

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}


答:
You can try this way too.

```<code><!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>

<div class="col-lg-2">
    <div class="form-group" >
        <label style="width:25%; float:left;">Working experience</label>
         <div style="width:25%; float:left;">
            <input type="text" class="form-control  " placeholder="Year"/>Year
         </div>
         <div style="width:25%;  float:left;">
            <input type="text" class="form-control " placeholder="Month"/>Month
         </div>
         <div style="width:25%;  float:left;">
            <input type="text" class="form-control  " placeholder="Day"/>Day
         </div>
    </div>
</div>
</body>

</html>
</code>```

Title: Text field in same line HTML

Body:
How to make multiple text fields in the same line.

This is my code:

        Working experience
        <input type="text" class="form-control  " placeholder="Year"/>Year
        <input type="text" class="form-control " placeholder="Month"/>Month
        <input type="text" class="form-control  " placeholder="Day" />Day

Body:
You can try this way too.

<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>

<div class="col-lg-2">
    <div class="form-group" >
        <label style="width:25%; float:left;">Working experience</label>
         <div style="width:25%; float:left;">
            <input type="text" class="form-control  " placeholder="Year"/>Year
         </div>
         <div style="width:25%;  float:left;">
            <input type="text" class="form-control " placeholder="Month"/>Month
         </div>
         <div style="width:25%;  float:left;">
            <input type="text" class="form-control  " placeholder="Day"/>Day
         </div>
    </div>
</div>
</body>

</html>


问:
Square an array's size with the same pattern repeated
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

```<code>int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}
</code>```

答:
I am adding in a generalized logic:</p>

```<code>y_size=x_size*x_size;
i=0;
for(j=0;j<y_size;j++)
{
   if (i<x_size)
   {
        y[j]=x[i++];
    }
    else
    {
        i=0;
        y[j]=x[i++];
    }
}
</code>```

Body:
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}

Body:
I am adding in a generalized logic:

y_size=x_size*x_size;
i=0;
for(j=0;j<y_size;j++)
{
   if (i<x_size)
   {
        y[j]=x[i++];
    }
    else
    {
        i=0;
        y[j]=x[i++];
    }
}


问:
How to make Jmeter version 3.12 script running into older version 2.11?
I created a Jmeter script that runs with version 3.12 on my local and it works.
I need to run it through Jenkins where Jmeter Version 2.12 is installed.
When I try to run the same test plan with Jenkins it shows error
ERROR - jmeter.save.SaveService: Conversion error com.thoughtworks.xstream.converters.ConversionException: No field 'sentBytes' found in class 'org.apache.jmeter.samplers.SampleSaveConfiguration' : No field 'sentBytes' found in class 'org.apache.jmeter.samplers.SampleSaveConfiguration'

Can anyone suggest how to make it run with the lower version? Is it possible to run it with version 2.12 with out any error?

Please help.

答:
Theoretically is should not be a problem to run the test on older JMeter version, just make sure it is not impacted by one of the incompatible changes so inspect JMeter Changes history and amend your script accordingly.

In regards to your question itself, it looks like you are using a Listener with Save sent bytes count option enabled somewhere in your Test Plan.

If this is the case - just delete the Listener(s) and your test should work normally. Also be aware that having listeners in the test plan is some form of anti-pattern as they are very resource intensive and given you are storing results into .jtl file, aren't you, they are not required at all. See Greedy Listeners - Memory Leeches of Performance Testing article for details.


问:
Android deprecated camera issue
My app uses android.hardware.camera class. The class was deprecated, and even when the app works fine on Android 5.0+ when the client installs it on Android 7.0 the app crash.

I find similar questions (Use of camera2 versus deprecated Camera - what is best practice?), but there is no answer to my specific question.

Since the app is already finished and the camera is not the essential feature. Is there a way to avoid this crash and keep the old camera class?

Crash:

```<code>java.lang.RuntimeException:
  at android.hardware.Camera.<init>(Camera.java:519)
  at android.hardware.Camera.open(Camera.java:379)
  at info.blacktrail.catedral.Camaracap.onResume(Camaracap.java:216)
  at android.support.v4.app.Fragment.performResume(Fragment.java:2235)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1346)
  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

Fragment:

```<code>public class Cameracap extends Fragment implements View.OnClickListener {

ProgressDialog mProgressDialog;
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private FrameLayout camera_preview;

ImageView image, captured_image,image_frame,imageshare,imagetakepic;
Bitmap bmp;
static Bitmap mutableBitmap;
File imageFileName = null;

private MediaScannerConnection msConn;
ProgressDialog dialog;

FragmentManager mFragmentManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cameraselfie, container, false);

   ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA);

    image = (ImageView) rootView.findViewById(R.id.image);

    imageshare= (ImageView) rootView.findViewById(R.id.imageshare);
    imagetakepic= (ImageView) rootView.findViewById(R.id.imagetakepic);

    image_frame = (ImageView) rootView.findViewById(R.id.imageView18);

    captured_image = (ImageView) rootView.findViewById(R.id.captured_image);
    preview = (SurfaceView) rootView.findViewById(R.id.surface_cam);
    camera_preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);

    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    previewHolder.setFixedSize(getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getWidth(), getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getHeight());

    final Button captureButton = (Button) rootView.findViewById(R.id.foto);
    final Button share_image = (Button) rootView.findViewById(R.id.shareface);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            imageshare.setVisibility(View.VISIBLE);
            share_image.setVisibility(View.VISIBLE);
            imagetakepic.setVisibility(View.GONE);
            captureButton.setVisibility(View.GONE);

            capture();
        }
    });

    share_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            imageshare.setVisibility(View.GONE);
            share_image.setVisibility(View.GONE);
            imagetakepic.setVisibility(View.VISIBLE);
            captureButton.setVisibility(View.VISIBLE);

            new Title().execute();

        }
    });

    Button button_back=(Button)rootView.findViewById(R.id.button_back);

    button_back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();
        }
    });

    Button emergencia=(Button)rootView.findViewById(R.id.button_sos);
    emergencia.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Emergencia()).commit();

        }
    });

    Button buttoncam=(Button)rootView.findViewById(R.id.buttoncam);
    buttoncam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Camera2BasicFragment()).commit();

        }
    });

    Button configbut=(Button)rootView.findViewById(R.id.button_config);
    configbut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    camera = Camera.open();
}

@Override
public void onPause() {
    if (inPreview) {
        camera.stopPreview();
    }

    camera.release();
    camera = null;
    inPreview = false;
    super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }
    return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {

            Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height,
                parameters);

        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
            camera.startPreview();
            inPreview = true;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
    public void onPictureTaken(final byte[] data, final Camera camera) {
        dialog = ProgressDialog.show(getActivity(), "", "Guardando foto");
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {
                }
                onPictureTake(data, camera);
            }
        }.start();
    }
};

public void onPictureTake(byte[] data, Camera camera) {

    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
    savePhoto(mutableBitmap);

    dialog.dismiss();

}

public void savePhoto(Bitmap bmp) {

    FileOutputStream out = null;

    try {
        out = new FileOutputStream("/sdcard/"
                + "catedralselfie"
                + ".jpg");
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void scanPhoto(final String imageFileName) {
    msConn = new MediaScannerConnection(getActivity(), new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            msConn.scanFile(imageFileName, null);

        }

        public void onScanCompleted(String path, Uri uri) {
            msConn.disconnect();

        }
    });
    msConn.connect();
}

public void capture() {
    Log.e("onBack :", "yes");
    camera.takePicture(null, null, photoCallback);
    inPreview = false;
}

@Override
public void onClick(View v) {

}

// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {

    Drawable drawable;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Cerro Catedral");
        mProgressDialog.setMessage("cargando datos...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        Elements elements, elements1, elements2;

        File imgFile = new File("/sdcard/catedralselfie.jpg");

        if (imgFile.exists()) {

            Bitmap myBitmap2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(myBitmap2 , 0, 0, myBitmap2.getWidth(), myBitmap2.getHeight(), matrix, true);
            drawable = new BitmapDrawable(getResources(), rotatedBitmap);

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        image_frame.setBackground(drawable);

        shareintento();
        mProgressDialog.dismiss();

    }

}

protected void shareintento() {

    camera_preview.setDrawingCacheEnabled(true);

    camera_preview.buildDrawingCache();

    Bitmap bitmap = camera_preview.getDrawingCache();

    try {
        FileOutputStream out = new FileOutputStream("/sdcard/"
                + "catedralselfie2"
                + ".jpg");
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    File file = new File("/sdcard/catedralselfie2.jpg");

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    String _text = "#CatedralSelfie #MiSelfieEnCatedral #CatedralInvierno #Bariloche @CerroCatedralok";

    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(String.valueOf(file))));  //optional//use this when you want to send an image

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, (CharSequence) _text);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/sdcard/catedralselfie2.jpg")));  //optional//use this when you want to send an image
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "send"));

    mFragmentManager = getActivity().getSupportFragmentManager();

    android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();

}
</code>```

}

答:
Your stack trace shows that your app calls Cameta.open() from Fragment.onResume method on the main Ui thread. This alone may cause RuntimeException on Android 7, which imposes even tighter restrictions on performing time consuming operations on UI thread.

Another cause could be the permissions: you don't need to implement full runtime permissions if your target API is less than 21, but still, your code must be prepared to handle the case when camera permission is revoked, at any time.

There may be other issues with your camera related code, please share it for further analysis.

Title: Android deprecated camera issue

Body:
My app uses android.hardware.camera class. The class was deprecated, and even when the app works fine on Android 5.0+ when the client installs it on Android 7.0 the app crash.

I find similar questions (Use of camera2 versus deprecated Camera - what is best practice?), but there is no answer to my specific question.

Since the app is already finished and the camera is not the essential feature. Is there a way to avoid this crash and keep the old camera class?

Crash:

java.lang.RuntimeException:
  at android.hardware.Camera.<init>(Camera.java:519)
  at android.hardware.Camera.open(Camera.java:379)
  at info.blacktrail.catedral.Camaracap.onResume(Camaracap.java:216)
  at android.support.v4.app.Fragment.performResume(Fragment.java:2235)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1346)
  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:757)
  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2355)
  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2146)
  at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2098)
  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2008)
  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
  at android.os.Handler.handleCallback(Handler.java:751)
  at android.os.Handler.dispatchMessage(Handler.java:95)
  at android.os.Looper.loop(Looper.java:154)
  at android.app.ActivityThread.main(ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Fragment:

public class Cameracap extends Fragment implements View.OnClickListener {

ProgressDialog mProgressDialog;
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private FrameLayout camera_preview;

ImageView image, captured_image,image_frame,imageshare,imagetakepic;
Bitmap bmp;
static Bitmap mutableBitmap;
File imageFileName = null;

private MediaScannerConnection msConn;
ProgressDialog dialog;

FragmentManager mFragmentManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.cameraselfie, container, false);

   ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CAMERA);

    image = (ImageView) rootView.findViewById(R.id.image);

    imageshare= (ImageView) rootView.findViewById(R.id.imageshare);
    imagetakepic= (ImageView) rootView.findViewById(R.id.imagetakepic);

    image_frame = (ImageView) rootView.findViewById(R.id.imageView18);

    captured_image = (ImageView) rootView.findViewById(R.id.captured_image);
    preview = (SurfaceView) rootView.findViewById(R.id.surface_cam);
    camera_preview = (FrameLayout) rootView.findViewById(R.id.camera_preview);

    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    previewHolder.setFixedSize(getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getWidth(), getActivity().getWindow().getWindowManager()
            .getDefaultDisplay().getHeight());

    final Button captureButton = (Button) rootView.findViewById(R.id.foto);
    final Button share_image = (Button) rootView.findViewById(R.id.shareface);
    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            imageshare.setVisibility(View.VISIBLE);
            share_image.setVisibility(View.VISIBLE);
            imagetakepic.setVisibility(View.GONE);
            captureButton.setVisibility(View.GONE);

            capture();
        }
    });

    share_image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            imageshare.setVisibility(View.GONE);
            share_image.setVisibility(View.GONE);
            imagetakepic.setVisibility(View.VISIBLE);
            captureButton.setVisibility(View.VISIBLE);

            new Title().execute();

        }
    });

    Button button_back=(Button)rootView.findViewById(R.id.button_back);

    button_back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();
        }
    });

    Button emergencia=(Button)rootView.findViewById(R.id.button_sos);
    emergencia.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Emergencia()).commit();

        }
    });

    Button buttoncam=(Button)rootView.findViewById(R.id.buttoncam);
    buttoncam.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            mFragmentManager = getActivity().getSupportFragmentManager();

            android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contenedor_principal,new Camera2BasicFragment()).commit();

        }
    });

    Button configbut=(Button)rootView.findViewById(R.id.button_config);
    configbut.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    camera = Camera.open();
}

@Override
public void onPause() {
    if (inPreview) {
        camera.stopPreview();
    }

    camera.release();
    camera = null;
    inPreview = false;
    super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea > resultArea) {
                    result = size;
                }
            }
        }
    }
    return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (Throwable t) {

            Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = getBestPreviewSize(width, height,
                parameters);

        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
            camera.startPreview();
            inPreview = true;
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
    public void onPictureTaken(final byte[] data, final Camera camera) {
        dialog = ProgressDialog.show(getActivity(), "", "Guardando foto");
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {
                }
                onPictureTake(data, camera);
            }
        }.start();
    }
};

public void onPictureTake(byte[] data, Camera camera) {

    bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
    mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
    savePhoto(mutableBitmap);

    dialog.dismiss();

}

public void savePhoto(Bitmap bmp) {

    FileOutputStream out = null;

    try {
        out = new FileOutputStream("/sdcard/"
                + "catedralselfie"
                + ".jpg");
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void scanPhoto(final String imageFileName) {
    msConn = new MediaScannerConnection(getActivity(), new MediaScannerConnection.MediaScannerConnectionClient() {
        public void onMediaScannerConnected() {
            msConn.scanFile(imageFileName, null);

        }

        public void onScanCompleted(String path, Uri uri) {
            msConn.disconnect();

        }
    });
    msConn.connect();
}

public void capture() {
    Log.e("onBack :", "yes");
    camera.takePicture(null, null, photoCallback);
    inPreview = false;
}

@Override
public void onClick(View v) {

}

// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {

    Drawable drawable;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setTitle("Cerro Catedral");
        mProgressDialog.setMessage("cargando datos...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        Elements elements, elements1, elements2;

        File imgFile = new File("/sdcard/catedralselfie.jpg");

        if (imgFile.exists()) {

            Bitmap myBitmap2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(myBitmap2 , 0, 0, myBitmap2.getWidth(), myBitmap2.getHeight(), matrix, true);
            drawable = new BitmapDrawable(getResources(), rotatedBitmap);

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        image_frame.setBackground(drawable);

        shareintento();
        mProgressDialog.dismiss();

    }

}

protected void shareintento() {

    camera_preview.setDrawingCacheEnabled(true);

    camera_preview.buildDrawingCache();

    Bitmap bitmap = camera_preview.getDrawingCache();

    try {
        FileOutputStream out = new FileOutputStream("/sdcard/"
                + "catedralselfie2"
                + ".jpg");
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    File file = new File("/sdcard/catedralselfie2.jpg");

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    String _text = "#CatedralSelfie #MiSelfieEnCatedral #CatedralInvierno #Bariloche @CerroCatedralok";

    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(String.valueOf(file))));  //optional//use this when you want to send an image

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, (CharSequence) _text);
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/sdcard/catedralselfie2.jpg")));  //optional//use this when you want to send an image
    shareIntent.setType("image/jpeg");
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "send"));

    mFragmentManager = getActivity().getSupportFragmentManager();

    android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.contenedor_principal,new FragmentoInicio()).commit();

}

}


问:
How to show the image name as the title of the window in matlab
How to get the name of the image as the title of the window when using imshow in matlab.

Eg: I use the following code as to show the original image and the skeletonized image.

```<code>figure
subplot(1,2,1)
imshow(BW_Original)
subplot(1,2,2)
imshow(BW_Thinned)
</code>```

I want to show the image name as the title of the window that pop ups. Can someone help me with this. Thank you.

答:
You'll want to change the 'Name' property of the figure to your image name, as well as setting the 'NumberTitle' property to 'off' (to remove the "Figure #:" that appears):

```<code>set(gcf, 'Name', 'image_name', 'NumberTitle', 'off');
</code>```

Body:
How to get the name of the image as the title of the window when using imshow in matlab.

Eg: I use the following code as to show the original image and the skeletonized image.

figure
subplot(1,2,1)
imshow(BW_Original)
subplot(1,2,2)
imshow(BW_Thinned)

I want to show the image name as the title of the window that pop ups. Can someone help me with this. Thank you.

Body:
You'll want to change the 'Name' property of the figure to your image name, as well as setting the 'NumberTitle' property to 'off' (to remove the "Figure #:" that appears):

set(gcf, 'Name', 'image_name', 'NumberTitle', 'off');


问:
Formatting the way a string is entered into my database
I am wanting to format data entered into a string column (confusingly named time) of my database in a certain way. Because of legacy data issues on this project I can't simply change the column type from string to time because I would lose the old entries.

I simply want to require that the format of the information entered into the form and then submitted to the database is as follows:

00:00 where a 0 can by any integer 0-9.

How would I do that within a form_for.

I am using Rails 2.3.8.

答:
A work around that might help:

First create a migration doing:

```<code>rename_column :the_models, :time, :old_time
add_column :the_models, :time, :time
</code>```

So now, the model will have a field called old_time containing the original time data, and a new time field having the correct field type.

As a result, the existing forms would seems like lost all the time data, but at least they are calling the_model.time to get the result.

The real work around part:

```<code>class TheModel < ActiveRecord::Base
  def time
    read_attribute(:time) || Time.parse(read_attribute(:old_time))
  end
end
</code>```

So now the time value will be saved into the time filed.

When time is nil, it will try to get the time value from the old_time and convert it to a time object.

There are two drawbacks:

Time.parse("12:34") would give you something like: 2010-12-14 12:34:00 +0800
Because you gave it only the hr and min, other fields are not reliable.

You have a nearly deprecated field called old_time in the database. So in the future, you may want to completely remove that field, after you have confidence that all old_time values has been converted to the time field.

One more note:

You should convert existing forms, for :time field which probably using text_field.
The text_field may become showing something like 2010-12-14 12:34:00 +0800.

If you really still want to use text_field, you could:

```<code>def time
  t = read_attribute(:time)
  t.nil? ? read_attribute(:old_time) : t.strftime("%H:%M")
end

def time=(val)
  write_attribute(:time, Time.parse(val))
end
</code>```

Body:
A work around that might help:

First create a migration doing:

rename_column :the_models, :time, :old_time
add_column :the_models, :time, :time

So now, the model will have a field called old_time containing the original time data, and a new time field having the correct field type.

As a result, the existing forms would seems like lost all the time data, but at least they are calling the_model.time to get the result.

The real work around part:

class TheModel < ActiveRecord::Base
  def time
    read_attribute(:time) || Time.parse(read_attribute(:old_time))
  end
end

So now the time value will be saved into the time filed.

When time is nil, it will try to get the time value from the old_time and convert it to a time object.

There are two drawbacks:

Time.parse("12:34") would give you something like: 2010-12-14 12:34:00 +0800
Because you gave it only the hr and min, other fields are not reliable.

You have a nearly deprecated field called old_time in the database. So in the future, you may want to completely remove that field, after you have confidence that all old_time values has been converted to the time field.

One more note:

You should convert existing forms, for :time field which probably using text_field.
The text_field may become showing something like 2010-12-14 12:34:00 +0800.

If you really still want to use text_field, you could:

def time
  t = read_attribute(:time)
  t.nil? ? read_attribute(:old_time) : t.strftime("%H:%M")
end

def time=(val)
  write_attribute(:time, Time.parse(val))
end