问:
Why does my Android app keep telling me I need to define a ListView id when it is already defined?
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

```<code><ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>
</code>```

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?

答:
hi Todd
whatever u give listview's id in XML
thst id u want to declare in java class.

sample code in XML

 & In java class

ListView list=(ListView)findViewById(R.id.list);

Body:
Whenever I try to run my app, the following exception is thrown:

01-22 00:40:51.868: ERROR/AndroidRuntime(2219): java.lang.RuntimeException: Unable to start activity ComponentInfo{[Redacted]}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

Here is the markup for the ListView in question:

<ListView
 android:id="@+id/list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:dividerHeight="1px"></ListView>

So, since the id is clearly defined as "list," what gives here? I've run through my code multiple times in the past couple of hours trying to track down the cause of this and I'm stumped. Can anyone offer any pointers?


来源: stackexchange

问:
java.math.BigInteger cannot be cast to fr.pc30.bean.Intervention
I have an error with java.math.BigInteger cannot be cast to a class name.

This is my request

```<code>public List<Intervention> findTicketTaskAnnuler(long partnaireId,InterventionType type)
return   getSession().createSQLQuery(new StringBuilder("")
                .append("SELECT i.id FROM intervention i ")
                .append("INNER JOIN logged_event lo on lo.NEW_ID = i.id and lo.OPERATION ='ANNULATION' and lo.DATE_CREATION =CURDATE() and lo.USER != :name ")
                .append("WHERE i.ID_PARTENAIRE = :partnaireId ")
                .append("and i.annulee=1 ")
                .append("order by i.id desc ").toString())
                .setParameter("partnaireId", partnaireId)
                .setParameter("name", type.getName())
                .list();
</code>```

答:
The return type of findTicketTaskAnnuler is a List of Intervention, but in your query you specify

```<code>SELECT i.id FROM intervention i
</code>```

essentially only selecting the id (that i suppose is a BigInteger)
so hibernate returns that type and your code try to cast it to Intervention class

Change your return type as List<Long>
or change your query to get all the fields you need to map to the entity

ContentLicense: CC BY-SA 3.0

Body:
I have an error with java.math.BigInteger cannot be cast to a class name.

This is my request

public List<Intervention> findTicketTaskAnnuler(long partnaireId,InterventionType type)
return   getSession().createSQLQuery(new StringBuilder("")
                .append("SELECT i.id FROM intervention i ")
                .append("INNER JOIN logged_event lo on lo.NEW_ID = i.id and lo.OPERATION ='ANNULATION' and lo.DATE_CREATION =CURDATE() and lo.USER != :name ")
                .append("WHERE i.ID_PARTENAIRE = :partnaireId ")
                .append("and i.annulee=1 ")
                .append("order by i.id desc ").toString())
                .setParameter("partnaireId", partnaireId)
                .setParameter("name", type.getName())
                .list();

Body:
The return type of findTicketTaskAnnuler is a List of Intervention, but in your query you specify

SELECT i.id FROM intervention i

essentially only selecting the id (that i suppose is a BigInteger)
so hibernate returns that type and your code try to cast it to Intervention class

Change your return type as List<Long>
or change your query to get all the fields you need to map to the entity


问:
How to wait for .map() to finish executing before continuing on to next lines of code
How do I go about waiting for all the posts to be pushed to the posts array before updating the state?

I had to iterate over an array of post ID's to get the top posts on HackerNews and then turned all those ID's into singular post links and want to store the data from the single post links in an array so I can iterate over that array to render it in the DOM.

import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post';

class ContentWrapper extends Component {
  constructor(props){
    super(props);
    this.state = {
      posts: []
    }
  }

  componentDidMount(){
    const topStories = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty';
    // `https://hacker-news.firebaseio.com/v0/item/.json?print=pretty`
    axios(topStories).then(res => {
      const posts = [];
      res.data.map(val => {
        const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
        return axios.get(url).then(res => {
          posts.push(res.data);
        }).then(res => this.setState({posts: res}));
      });
    });
  }

  render() {
    const posts = this.state.posts.map((val, i) => {
      return <Post key={i} title={val.title} author={val.by} />
    });
    return (

{this.props.currentSource}

        {posts}

    )
  }
}

export default ContentWrapper;```

答:
You will have to use Promise.all - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

```<code>const topStories =
  "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";

axios(topStories).then(res => {
  const posts = [];

  const requests = res.data.map(val => {
    const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
    return axios.get(url).then(res => {
      posts.push(res.data);
    });
  });

  // Wait for all requests, and then setState
  return Promise.all(requests).then(() => {
    this.setState({
      posts
    });
  });
});
</code>```

Test it here: https://runkit.com/embed/8pac53dhmy2y

Update There is also Promise.allSettled which might be better in some cases if there are any errors in the promise array; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

Body:
You will have to use Promise.all - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const topStories =
  "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";

axios(topStories).then(res => {
  const posts = [];

  const requests = res.data.map(val => {
    const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
    return axios.get(url).then(res => {
      posts.push(res.data);
    });
  });

  // Wait for all requests, and then setState
  return Promise.all(requests).then(() => {
    this.setState({
      posts
    });
  });
});

Test it here: https://runkit.com/embed/8pac53dhmy2y

Update There is also Promise.allSettled which might be better in some cases if there are any errors in the promise array; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

ContentLicense: CC BY-SA 4.0


问:
What code do I need for my Unity character to shoot the bullet correctly?
I am not new to programming, but I am new to C#. I am experienced in Python, Java, and HTML. My game is 2D I have a game where my character currently has to touch the enemy to kill it. Now I added code for shooting a bullet to kill the enemy. I also want the bullet to be shot if the spacebar is pressed. The character is supposed to a shoot bullet in either direction. I have taken my code from an example my professor gave me which was originally Javascript and I converted it to C#. Unity no longer supports Javascript. The example code he gave me was basically a rocket shooting as many bullets as I clicked (clicking the mouse shoots bullets) to eliminate an enemy, however the rocket in that example does not move. In my game, the character moves, so the bullet has to get the position of the character. What is the correct code for getting the character position and shooting a bullet correctly?

I tested my game with my current code. The bullet is being spit out of nowhere (from the bottom of my background wallpaper [smack in the middle of the bottom] to a little below the wallpaper). Not even from the character...
Also, I added the Hit class script to my Bullet category in Unity.

Complete Camera Controller (no issues here at all)

```<code>using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

    public GameObject player;       //Public variable to store a reference to the player game object

    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}
</code>```

Complete Player Control Class (If you read the comments in the code that say the "BULLET CODE", that's new code I have placed in the game for the bullets.

```<code>using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class CompletePlayerController : MonoBehaviour
{

    public float speed;             //Floating point variable to store the player's movement speed.
    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    public Text winText;            //Store a reference to the UI Text component which will display the 'You win' message.

    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    private int count;              //Integer to store the number of pickups collected so far.
    Rigidbody2D bullet;
    float speed2 = 30f; //BULLET CODE

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        winText.text = "";

        //Call our SetCountText function which will update the text with the current value for count.
        SetCountText ();
    }

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis ("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis ("Vertical");

        Rigidbody2D bulletInstance; //BULLET CODE

        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

        //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
         rb2d.AddForce (movement * speed);

         if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE
        {
            // ... instantiate the bullet facing right and set it's velocity to the right.
            bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0)));
            bulletInstance.velocity = new Vector2(speed2, 0);
            bulletInstance.name = "Bullet";
        }

    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            transform.localScale += new Vector3(0.1f, 0.1f, 0);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            SetCountText ();
        }

    }

    //This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them.
    void SetCountText()
    {
        //Set the text property of our our countText object to "Count: " followed by the number stored in our count variable.
        countText.text = "Count: " + count.ToString ();

        //Check if we've collected all 12 pickups. If we have...
        if (count >= 12)
            //... then set the text property of our winText object to "You win!"
            winText.text = "You win!";
    }
}
</code>```

Hit code. All code in this class is made for the bullet.

```<code>using UnityEngine;
using System.Collections;

public class Hit : MonoBehaviour
{

    GameObject[] gameObjects;
    public static bool hit = false;

    void  Removal ()
    {

    gameObjects =  GameObject.FindGameObjectsWithTag("Bullet");

    for(var i= 0 ; i < gameObjects.Length ; i ++)
        Destroy(gameObjects[i]);
    }

    void  OnCollisionEnter2D ( Collision2D other  )
    {
        if(other.gameObject.name=="Bullet")
        {
            Removal();
            Destroy(gameObject);
            hit = true;

        }
    }
}
</code>```

答:
I see several issues with the code you wrote. as @Kyle Delaney suggested, I'd also highly recommend you check out the Unity Learn website, and go through several tutorials before moving through. I've highlighted a few issues below that may help solve your problem, but you could really benefit from changing your approach in the first place to avoid many of these issues. See below.

In your camera controller class, why not make the offset public so you can set it yourself in the inspector>

In Player controller class:

changed:

```<code>if (Input.GetKeyDown(KeyCode.Space)) //Shoot bullet
{
    // ... instantiate the bullet facing right and set it's velocity to the right.
    Rigidbody2D bulletRB = Instantiate(bullet, transform.position, transform.rotation);
    bulletRB.AddForce(new Vector2(speed2,0), ForceMode2D.Impulse);
}
</code>```

On a click, this instantiates the bullet prefab and sets its transform to copy the position and rotation of the player. It then adds a force to it to the right. You should avoid setting the velocity manually with rigidbodies, this can cause unwanted behaviour. Use the Addforce/addTorque methods instead. The ForceMode says to ignore its mass and set its velocity.

Then delete your Hit class, and replace with this Bullet class, which you drag onto the bullet prefab. Your player shouldn't be in charge of checking for bullet hits. that's the bullet's job. The player just launches the bullets and then the bullets do what bullets do. this just checks to see if the bullet hit anything, if so it destroys it. You can make this more complicated if you want. I would recommend using layers to determine which layers the bullet checks collisions with. You probably don't want bullets destroying your terrain. and you definitely don't want bullets destroying the player itself!

```<code>public class Bullet : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(collision.gameObject);
        Destroy(this.gameObject);
    }

}
</code>```

Also you shouldn't need to set the name of the bullet, since your prefab bullet should already be named "bullet".

I hope this gets you started in the right direction. But based on your code, I HIGHLY recommend you work through the tutorials before continuing with any projects. The unity staff that make them are super helpful and the tutorials start off really simple but get really complicated fast, so you actually come away learning a ton!

Body:
I am not new to programming, but I am new to C#. I am experienced in Python, Java, and HTML. My game is 2D I have a game where my character currently has to touch the enemy to kill it. Now I added code for shooting a bullet to kill the enemy. I also want the bullet to be shot if the spacebar is pressed. The character is supposed to a shoot bullet in either direction. I have taken my code from an example my professor gave me which was originally Javascript and I converted it to C#. Unity no longer supports Javascript. The example code he gave me was basically a rocket shooting as many bullets as I clicked (clicking the mouse shoots bullets) to eliminate an enemy, however the rocket in that example does not move. In my game, the character moves, so the bullet has to get the position of the character. What is the correct code for getting the character position and shooting a bullet correctly?

I tested my game with my current code. The bullet is being spit out of nowhere (from the bottom of my background wallpaper [smack in the middle of the bottom] to a little below the wallpaper). Not even from the character...
Also, I added the Hit class script to my Bullet category in Unity.

Complete Camera Controller (no issues here at all)

using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

    public GameObject player;       //Public variable to store a reference to the player game object

    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}

Complete Player Control Class (If you read the comments in the code that say the "BULLET CODE", that's new code I have placed in the game for the bullets.

using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class CompletePlayerController : MonoBehaviour
{

    public float speed;             //Floating point variable to store the player's movement speed.
    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    public Text winText;            //Store a reference to the UI Text component which will display the 'You win' message.

    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    private int count;              //Integer to store the number of pickups collected so far.
    Rigidbody2D bullet;
    float speed2 = 30f; //BULLET CODE

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        winText.text = "";

        //Call our SetCountText function which will update the text with the current value for count.
        SetCountText ();
    }

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis ("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis ("Vertical");

        Rigidbody2D bulletInstance; //BULLET CODE

        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

        //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
         rb2d.AddForce (movement * speed);

         if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE
        {
            // ... instantiate the bullet facing right and set it's velocity to the right.
            bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0)));
            bulletInstance.velocity = new Vector2(speed2, 0);
            bulletInstance.name = "Bullet";
        }

    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            transform.localScale += new Vector3(0.1f, 0.1f, 0);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            SetCountText ();
        }

    }

    //This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them.
    void SetCountText()
    {
        //Set the text property of our our countText object to "Count: " followed by the number stored in our count variable.
        countText.text = "Count: " + count.ToString ();

        //Check if we've collected all 12 pickups. If we have...
        if (count >= 12)
            //... then set the text property of our winText object to "You win!"
            winText.text = "You win!";
    }
}

Hit code. All code in this class is made for the bullet.

using UnityEngine;
using System.Collections;

public class Hit : MonoBehaviour
{

    GameObject[] gameObjects;
    public static bool hit = false;

    void  Removal ()
    {

    gameObjects =  GameObject.FindGameObjectsWithTag("Bullet");

    for(var i= 0 ; i < gameObjects.Length ; i ++)
        Destroy(gameObjects[i]);
    }

    void  OnCollisionEnter2D ( Collision2D other  )
    {
        if(other.gameObject.name=="Bullet")
        {
            Removal();
            Destroy(gameObject);
            hit = true;

        }
    }
}

Body:
I see several issues with the code you wrote. as @Kyle Delaney suggested, I'd also highly recommend you check out the Unity Learn website, and go through several tutorials before moving through. I've highlighted a few issues below that may help solve your problem, but you could really benefit from changing your approach in the first place to avoid many of these issues. See below.

In your camera controller class, why not make the offset public so you can set it yourself in the inspector>

In Player controller class:

changed:

if (Input.GetKeyDown(KeyCode.Space)) //Shoot bullet
{
    // ... instantiate the bullet facing right and set it's velocity to the right.
    Rigidbody2D bulletRB = Instantiate(bullet, transform.position, transform.rotation);
    bulletRB.AddForce(new Vector2(speed2,0), ForceMode2D.Impulse);
}

On a click, this instantiates the bullet prefab and sets its transform to copy the position and rotation of the player. It then adds a force to it to the right. You should avoid setting the velocity manually with rigidbodies, this can cause unwanted behaviour. Use the Addforce/addTorque methods instead. The ForceMode says to ignore its mass and set its velocity.

Then delete your Hit class, and replace with this Bullet class, which you drag onto the bullet prefab. Your player shouldn't be in charge of checking for bullet hits. that's the bullet's job. The player just launches the bullets and then the bullets do what bullets do. this just checks to see if the bullet hit anything, if so it destroys it. You can make this more complicated if you want. I would recommend using layers to determine which layers the bullet checks collisions with. You probably don't want bullets destroying your terrain. and you definitely don't want bullets destroying the player itself!

public class Bullet : MonoBehaviour
{

    private void OnCollisionEnter2D(Collision2D collision)
    {
        Destroy(collision.gameObject);
        Destroy(this.gameObject);
    }

}

Also you shouldn't need to set the name of the bullet, since your prefab bullet should already be named "bullet".

I hope this gets you started in the right direction. But based on your code, I HIGHLY recommend you work through the tutorials before continuing with any projects. The unity staff that make them are super helpful and the tutorials start off really simple but get really complicated fast, so you actually come away learning a ton!


问:
How to write to ORC files using BucketingSink in Apache Flink?
I'm working on a Flink streaming program that reads kafka messages and dump the messages to ORC files on AWS s3. I found there is no document about the integration of Flink's BucketingSink and ORC file writer. and there is no such an ORC file writer implementation can be used in BucketingSink.

I'm stuck here, any ideas?

答:
I agree, a BucketingSink writer for ORC files would be a great feature. However, it hasn't been contributed to Flink yet. You would have to implement such a writer yourself.

I'm sure the Flink community would help designing and reviewing the writer, if you would consider contributing it to Flink.


问:
How to use *ngFor in angular 2 bootstrap modal
I am trying to bind data to my modal using *ngFor in angular 2 but not able to view any data in modal when in my component data is available.

modal.component.html

```<code> <div class="modal modalscroll" tabindex="-1" role="dialog"  [ngStyle]="{'display':addSplitBilling}">
    <div class="modal-dialog splitBillingModal">
    <form>
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click) = "clearSplitBilling()">×</button>
          <h4 class="modal-title">Split Billing</h4>
        </div>
        <div class="container"></div>
        <div class="modal-body">
          <table>
                <tbody>
                    <tr *ngFor="let d of data.dupStmtAddresses; let i = index">
                          <td>{{d.addressee}}</td>
                          <td>{{d.splitPercent}}</td>
                      </tr>
                </tbody>
            </table>
        </div>
        <div class="modal-footer">
        </div>

      </div>
    </form>
    </div>
  </div>
</code>```

modal.component.ts

```<code>export class DupStatementsComponent implements OnInit {
    addSplitBilling = 'none';
    data: any;

    ngOnInit() {
        this.getData();
    }

    getData(){
        this.duplicateStatementsProvider.getDuplicateStatements()
        .subscribe(
            data => {
                this.data = JSON.parse(data['_body']);
            },
            error => {
            }
        );
    }

    splitBilling(){
        console.log(this.data.dupStmtAddresses);
        this.addSplitBilling = 'block';
    }
}
</code>```

In console I can see that data is available but in modal not able to view any data.

In data i am getting this response from web service -->

```<code>{"createdDate":"2017-12-04T17:04:00.174+05:30","id":1,"dupStmtAddresses":[{"createdDate":null,"id":1,"addressee":"a","address1":"a","address2":"a","address3":"a","address4":"a","email":"a","splitPercent":null,"new":false},{"createdDate":null,"id":2,"addressee":"b","address1":"b","address2":"b","address3":"b","address4":"b","email":"b","splitPercent":null,"new":false},{"createdDate":null,"id":3,"addressee":"c","address1":"c","address2":"c","address3":"c","address4":"c","email":"c","splitPercent":null,"new":false}],"enableSplitBilling":true,"new":false}
</code>```

I have no idea why it is not working.

答:
What I can conclude from your description and comments above is that, the service is yet to respond before the modal template is created. I am not sure if it will work but could you please try:

Instead of using data directly in modal, use a new variable modalContent initialised to null/empty string. On click of button to open modal, assign the data to modalContent variable and use this in ngFor loop.

```<code>export class DupStatementsComponent implements OnInit {
    modalContent: any = '';
    //... same as your logic

    splitBilling(){
        console.log(this.data.dupStmtAddresses);
        this.modalContent = this.data.dupStmtAddresses;
        this.addSplitBilling = 'block';
    }
}
</code>```

your ngFor loop:

```<code><tr *ngFor="let d of modalContent; let i = index">
</code>```

Kindly share if it works!

Body:
I am trying to bind data to my modal using *ngFor in angular 2 but not able to view any data in modal when in my component data is available.

modal.component.html

    <form>

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click) = "clearSplitBilling()">×</button>

Split Billing

                          {{d.addressee}}
                          {{d.splitPercent}}

    </form>

modal.component.ts

export class DupStatementsComponent implements OnInit {
    addSplitBilling = 'none';
    data: any;

    ngOnInit() {
        this.getData();
    }

    getData(){
        this.duplicateStatementsProvider.getDuplicateStatements()
        .subscribe(
            data => {
                this.data = JSON.parse(data['_body']);
            },
            error => {
            }
        );
    }

    splitBilling(){
        console.log(this.data.dupStmtAddresses);
        this.addSplitBilling = 'block';
    }
}

In console I can see that data is available but in modal not able to view any data.

In data i am getting this response from web service -->

{"createdDate":"2017-12-04T17:04:00.174+05:30","id":1,"dupStmtAddresses":[{"createdDate":null,"id":1,"addressee":"a","address1":"a","address2":"a","address3":"a","address4":"a","email":"a","splitPercent":null,"new":false},{"createdDate":null,"id":2,"addressee":"b","address1":"b","address2":"b","address3":"b","address4":"b","email":"b","splitPercent":null,"new":false},{"createdDate":null,"id":3,"addressee":"c","address1":"c","address2":"c","address3":"c","address4":"c","email":"c","splitPercent":null,"new":false}],"enableSplitBilling":true,"new":false}

I have no idea why it is not working.

Body:
What I can conclude from your description and comments above is that, the service is yet to respond before the modal template is created. I am not sure if it will work but could you please try:

Instead of using data directly in modal, use a new variable modalContent initialised to null/empty string. On click of button to open modal, assign the data to modalContent variable and use this in ngFor loop.

export class DupStatementsComponent implements OnInit {
    modalContent: any = '';
    //... same as your logic

    splitBilling(){
        console.log(this.data.dupStmtAddresses);
        this.modalContent = this.data.dupStmtAddresses;
        this.addSplitBilling = 'block';
    }
}

your ngFor loop:

<tr *ngFor="let d of modalContent; let i = index">

Kindly share if it works!


问:
Cakephp controller name
i m new to cakephp. i have stuck in one place the problem is

table name - india_tends

controller - tends

model name - india_tends

The problem is that cake php not allow tends to controller name its show that i have to use india_tends.. so any way to give tends to controller name?

答:
If your table name is india_tends, then your controller code should be in the file india_tends_controller.php, and the class name should be IndiaTendsController.

In your case I think you want the IndiaTendsController to be accessible through /tends/:actions so the best guess would be using routing.

Edit your config/routes.php to have the following code:

```<code>Router::connect('/tends/*', array('controller' => 'india_tends'));
</code>```

And you can have it accessible through /tends/*

ContentLicense: CC BY-SA 2.5

Title: Cakephp controller name

Body:
If your table name is india_tends, then your controller code should be in the file india_tends_controller.php, and the class name should be IndiaTendsController.

In your case I think you want the IndiaTendsController to be accessible through /tends/:actions so the best guess would be using routing.

Edit your config/routes.php to have the following code:

Router::connect('/tends/*', array('controller' => 'india_tends'));

And you can have it accessible through /tends/*


问:
Elasticache - Increase the nodes for replication
I was looking at elasticache as a replacement for our EC2 redis deployment.
However I have a hard requirement of 1 master and 11 replicas in our deployment, while elasticache allows only 5 replicas. Is there a way this restriction can be relaxed.</p>

答:
No, unfortunately 5 read replicas appears to be the upper limit - http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Replication.html

Is your replica requirement to spread out CPU load? If so, there are some very capable instances available these days. Check out the M4 family of machines.


问:
Angular in Plain JavaScript on IE11
I need to use Angular 4+ in plain JavaScript on IE11. My overall application is an OfficeJS add-in, that is using the Dialog API to open a new window (IE11) from my add-in. There are several constraints:

Must run on IE11.

Must use plain JavaScript (I cannot use TypeScript).

Runs in its own context. Reference

Must be as lightweight as possible (so I cannot have it reinitialize / bootstrap my entire Angular app again. Reference). Think of the dialog as its own mini-app.

I have tried following these great examples, but was unable to get Angular to boot up.

My plunker is here.

The errors I get on IE11 are:

Object doesn't support property or method 'Class' (app.component.js (7,3))
Object doesn't support property or method 'Class' (app.module.js (7,3))
No NgModule metadata found for 'undefined'. (compiler.umd.min.js (55,26076))
```

<p>On Chrome (when looking at the Plunker) I get these errors:</p>

<pre class="lang-none prettyprint-override"><code>app.component.js:11 Uncaught TypeError: Component(...).Class is not a function
    at window.app.window.app (VM524 app.component.js:11)
    at VM524 app.component.js:15
window.app.window.app @ app.component.js:11
(anonymous) @ app.component.js:15
app.module.js:13 Uncaught TypeError: NgModule(...).Class is not a function
    at window.app.window.app (VM525 app.module.js:13)
    at VM525 app.module.js:16
window.app.window.app @ app.module.js:13
(anonymous) @ app.module.js:16
compiler.umd.min.js:sourcemap:55 Uncaught Error: No NgModule metadata found for 'undefined'.
    at NgModuleResolver.resolve (VM475 compiler.umd.min.js:55)
    at CompileMetadataResolver.getNgModuleMetadata (VM475 compiler.umd.min.js:53)
    at JitCompiler._loadModules (VM475 compiler.umd.min.js:62)
    at JitCompiler._compileModuleAndComponents (VM475 compiler.umd.min.js:62)
    at JitCompiler.compileModuleAsync (VM475 compiler.umd.min.js:62)
    at CompilerImpl.compileModuleAsync (VM476 platform-browser-dynamic.umd.min.js:6)
    at PlatformRef.bootstrapModule (VM472 core.umd.min.js:113)
    at window.app.window.app ((index):42)
    at (index):44
NgModuleResolver.resolve @ compiler.umd.min.js:sourcemap:55
CompileMetadataResolver.getNgModuleMetadata @ compiler.umd.min.js:sourcemap:53
JitCompiler._loadModules @ compiler.umd.min.js:sourcemap:62
JitCompiler._compileModuleAndComponents @ compiler.umd.min.js:sourcemap:62
JitCompiler.compileModuleAsync @ compiler.umd.min.js:sourcemap:62
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.umd.min.js:sourcemap:6
PlatformRef.bootstrapModule @ core.umd.min.js:sourcemap:113
window.app.window.app @ (index):42
(anonymous) @ (index):44
</code>```

What am I doing wrong?

Bonus points if this can be solved using AOT (i.e. not paying the cost of JIT at runtime).

答:
In the console, it says ng.core.Class is not a function for the version you are using.

Change the scripts references in your index.html :

```<code><script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.6.21/dist/zone.min.js"></script>
<script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.min.js"></script>

<script src="https://unpkg.com/@angular/core@2.1.2/bundles/core.umd.js"></script>
<script src="https://unpkg.com/@angular/common@2.1.2/bundles/common.umd.js"></script>
<script src="https://unpkg.com/@angular/compiler@2.1.2/bundles/compiler.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser@2.1.2/bundles/platform-browser.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser-dynamic@2.1.2/bundles/platform-browser-dynamic.umd.js"></script>
<script src="https://unpkg.com/@angular/http@2.1.2/bundles/http.umd.js"></script>
</code>```

And here is the app.module.js

```<code>(function(app) {
  var NgModule = ng.core.NgModule;
  var BrowserModule = ng.platformBrowser.BrowserModule;
  var AppComponent = app.AppComponent;

  app.AppModule = NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    providers: [],
    bootstrap: [AppComponent]
  })
  .Class({
    constructor: function() { }
  });
})(window.app || (window.app = {}));
</code>```

Title: Angular in Plain JavaScript on IE11

Body:
I need to use Angular 4+ in plain JavaScript on IE11. My overall application is an OfficeJS add-in, that is using the Dialog API to open a new window (IE11) from my add-in. There are several constraints:

Must run on IE11.

Must use plain JavaScript (I cannot use TypeScript).

Runs in its own context. Reference

Must be as lightweight as possible (so I cannot have it reinitialize / bootstrap my entire Angular app again. Reference). Think of the dialog as its own mini-app.

I have tried following these great examples, but was unable to get Angular to boot up.

My plunker is here.

The errors I get on IE11 are:

Object doesn't support property or method 'Class' (app.component.js (7,3))
Object doesn't support property or method 'Class' (app.module.js (7,3))
No NgModule metadata found for 'undefined'. (compiler.umd.min.js (55,26076))

On Chrome (when looking at the Plunker) I get these errors:

app.component.js:11 Uncaught TypeError: Component(...).Class is not a function
    at window.app.window.app (VM524 app.component.js:11)
    at VM524 app.component.js:15
window.app.window.app @ app.component.js:11
(anonymous) @ app.component.js:15
app.module.js:13 Uncaught TypeError: NgModule(...).Class is not a function
    at window.app.window.app (VM525 app.module.js:13)
    at VM525 app.module.js:16
window.app.window.app @ app.module.js:13
(anonymous) @ app.module.js:16
compiler.umd.min.js:sourcemap:55 Uncaught Error: No NgModule metadata found for 'undefined'.
    at NgModuleResolver.resolve (VM475 compiler.umd.min.js:55)
    at CompileMetadataResolver.getNgModuleMetadata (VM475 compiler.umd.min.js:53)
    at JitCompiler._loadModules (VM475 compiler.umd.min.js:62)
    at JitCompiler._compileModuleAndComponents (VM475 compiler.umd.min.js:62)
    at JitCompiler.compileModuleAsync (VM475 compiler.umd.min.js:62)
    at CompilerImpl.compileModuleAsync (VM476 platform-browser-dynamic.umd.min.js:6)
    at PlatformRef.bootstrapModule (VM472 core.umd.min.js:113)
    at window.app.window.app ((index):42)
    at (index):44
NgModuleResolver.resolve @ compiler.umd.min.js:sourcemap:55
CompileMetadataResolver.getNgModuleMetadata @ compiler.umd.min.js:sourcemap:53
JitCompiler._loadModules @ compiler.umd.min.js:sourcemap:62
JitCompiler._compileModuleAndComponents @ compiler.umd.min.js:sourcemap:62
JitCompiler.compileModuleAsync @ compiler.umd.min.js:sourcemap:62
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.umd.min.js:sourcemap:6
PlatformRef.bootstrapModule @ core.umd.min.js:sourcemap:113
window.app.window.app @ (index):42
(anonymous) @ (index):44

What am I doing wrong?

Bonus points if this can be solved using AOT (i.e. not paying the cost of JIT at runtime).

Body:
In the console, it says ng.core.Class is not a function for the version you are using.

Change the scripts references in your index.html :

<script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.6.21/dist/zone.min.js"></script>
<script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.min.js"></script>

<script src="https://unpkg.com/@angular/core@2.1.2/bundles/core.umd.js"></script>
<script src="https://unpkg.com/@angular/common@2.1.2/bundles/common.umd.js"></script>
<script src="https://unpkg.com/@angular/compiler@2.1.2/bundles/compiler.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser@2.1.2/bundles/platform-browser.umd.js"></script>
<script src="https://unpkg.com/@angular/platform-browser-dynamic@2.1.2/bundles/platform-browser-dynamic.umd.js"></script>
<script src="https://unpkg.com/@angular/http@2.1.2/bundles/http.umd.js"></script>

And here is the app.module.js

(function(app) {
  var NgModule = ng.core.NgModule;
  var BrowserModule = ng.platformBrowser.BrowserModule;
  var AppComponent = app.AppComponent;

  app.AppModule = NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    providers: [],
    bootstrap: [AppComponent]
  })
  .Class({
    constructor: function() { }
  });
})(window.app || (window.app = {}));


问:
does php have any special character classes like [:alnum:] for regex expressions?
Does php have or support any special character classes like [:alnum:] for regex expressions?</p>

答: All the character classes are listed in the doc.</p>


问:
What is causing an assertion error in my c++ code?
I am validating a cstring to check if it has an uppercase character and a digit and if it does the loops end. The validatePassword function of my code causes an assertion error. Username is the character array. Fail is a boolean array which is changed to 1 if the cstring does need meet the input validation requirement. The cstrings are being read in from a text file. U_SIZE is the size of the cstring.

The assertion error says:
Expression: c > -1 && c < 255

```<code>int main()
{
run();
return 0;
}

void run()
{
fstream inFile;

const int U_SIZE = 20;
const int P_SIZE = 20;

const int F_SIZE = 9;

int x = 0;

char user[20];
user[19] = NULL;

char username[U_SIZE];
username[19] = NULL;

char password1[P_SIZE];
password1[19] = NULL;

char password2[P_SIZE];
password2[19] = NULL;

bool fail[F_SIZE] = { 0,  //fail[0]
                      0,  //fail[1]
                      0,  //fail[2]
                      0,  //fail[3]
                      0,  //fail[4]
                      0,  //fail[5]
                      0,  //fail[6]
                      0,  //fail[7]
                      0}; //fail[8]

inFile.open("user_data.txt", ios::in);
inFile >> x;
inFile.ignore();

for (int i = 0; i < x; i++)
 {
    loadData(user, username, password1, password2, inFile);
    validateUsername(username, U_SIZE, fail, F_SIZE);
    cout << " " << endl;
 }
}

void loadData(char user[], char username[], char password1[], char
password2[], fstream &inFile)
{
inFile.getline(user, 20); //read user
inFile.getline(username, 20); //read username
inFile.getline(password1, 20);// read password 1
inFile.getline(password2, 20); // read password 2
}

void validateUsername(char username[], const int U_SIZE, bool fail[], int
F_SIZE)
{
char c;
char cTwo;
if (strlen(username) >= 10)
{
    fail[0] = 0;
}
else
{
    fail[0] = 1;
}

for (int i = 0; i < U_SIZE; i++)
{
    c = username[i];
    if (isupper(c) != 0)
    {
        fail[1] = 0;
        i = U_SIZE;
    }
    else
    {
        fail[1] = 1;
    }
}

for (int i = 0; i < U_SIZE; i++)
{
    cTwo = username[i];
    if (isdigit(cTwo) != 0)
    {
        fail[2] = 0;
        i = U_SIZE;
    }
    else
    {
        fail[2] = 1;
    }
 }
}
</code>```

答:
The problem is that you go outside of your strings, you don't check for the terminator or the end of the strings in your loops:

```<code>for (int i = 0; i < U_SIZE; i++)
{
    c = username[i];
    ...
</code>```

The length of the string in username is strlen(username). Outside of that the contents of the array might not be initialized properly, and its contents is indeterminate. And using indeterminate values, even just reading them, is undefined behavior in C++.

Use

```<code>for (int i = 0; i < strlen(username); i++)
{
    c = username[i];
    ...
</code>```

instead.

Body:
I am validating a cstring to check if it has an uppercase character and a digit and if it does the loops end. The validatePassword function of my code causes an assertion error. Username is the character array. Fail is a boolean array which is changed to 1 if the cstring does need meet the input validation requirement. The cstrings are being read in from a text file. U_SIZE is the size of the cstring.

The assertion error says:
Expression: c > -1 && c < 255

int main()
{
run();
return 0;
}

void run()
{
fstream inFile;

const int U_SIZE = 20;
const int P_SIZE = 20;

const int F_SIZE = 9;

int x = 0;

char user[20];
user[19] = NULL;

char username[U_SIZE];
username[19] = NULL;

char password1[P_SIZE];
password1[19] = NULL;

char password2[P_SIZE];
password2[19] = NULL;

bool fail[F_SIZE] = { 0,  //fail[0]
                      0,  //fail[1]
                      0,  //fail[2]
                      0,  //fail[3]
                      0,  //fail[4]
                      0,  //fail[5]
                      0,  //fail[6]
                      0,  //fail[7]
                      0}; //fail[8]

inFile.open("user_data.txt", ios::in);
inFile >> x;
inFile.ignore();

for (int i = 0; i < x; i++)
 {
    loadData(user, username, password1, password2, inFile);
    validateUsername(username, U_SIZE, fail, F_SIZE);
    cout << " " << endl;
 }
}

void loadData(char user[], char username[], char password1[], char
password2[], fstream &inFile)
{
inFile.getline(user, 20); //read user
inFile.getline(username, 20); //read username
inFile.getline(password1, 20);// read password 1
inFile.getline(password2, 20); // read password 2
}

void validateUsername(char username[], const int U_SIZE, bool fail[], int
F_SIZE)
{
char c;
char cTwo;
if (strlen(username) >= 10)
{
    fail[0] = 0;
}
else
{
    fail[0] = 1;
}

for (int i = 0; i < U_SIZE; i++)
{
    c = username[i];
    if (isupper(c) != 0)
    {
        fail[1] = 0;
        i = U_SIZE;
    }
    else
    {
        fail[1] = 1;
    }
}

for (int i = 0; i < U_SIZE; i++)
{
    cTwo = username[i];
    if (isdigit(cTwo) != 0)
    {
        fail[2] = 0;
        i = U_SIZE;
    }
    else
    {
        fail[2] = 1;
    }
 }
}

Body:
The problem is that you go outside of your strings, you don't check for the terminator or the end of the strings in your loops:

for (int i = 0; i < U_SIZE; i++)
{
    c = username[i];
    ...

The length of the string in username is strlen(username). Outside of that the contents of the array might not be initialized properly, and its contents is indeterminate. And using indeterminate values, even just reading them, is undefined behavior in C++.

Use

for (int i = 0; i < strlen(username); i++)
{
    c = username[i];
    ...

instead.


问:
how to convert HH:MM representation to minutes in oracle sql
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

```<code>HH:MM    Minutes
08:00    480
08:45    525
07:57    477
</code>```

答:
If you can convert your input to a real date first, the task becomes much easier. Here, I have shamelessly appended the time to a fake date to create a date such as 2017-01-01 00:30. To find out the number of minutes since midnight, you simply subtract the date for "midnight". It will return the difference in days, so you need to multiply by number of minutes per day to get what you want.

```<code>select time
      ,(to_date('2017-01-01 ' || time, 'yyyy-mm-dd hh24:mi') - date '2017-01-01') * 24 * 60 as minutes
  from (select '00:30' as time from dual union all
        select '08:00' as time from dual union all
        select '08:30' as time from dual union all
        select '12:00' as time from dual union all
        select '23:59' as time from dual
       );
</code>```

Here is some sample input and output

```<code>time  minutes
====  =======
00:30      30
08:00     480
08:30     510
12:00     720
23:59   1 439
</code>```

Body:
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

HH:MM    Minutes
08:00    480
08:45    525
07:57    477

Body:
If you can convert your input to a real date first, the task becomes much easier. Here, I have shamelessly appended the time to a fake date to create a date such as 2017-01-01 00:30. To find out the number of minutes since midnight, you simply subtract the date for "midnight". It will return the difference in days, so you need to multiply by number of minutes per day to get what you want.

select time
      ,(to_date('2017-01-01 ' || time, 'yyyy-mm-dd hh24:mi') - date '2017-01-01') * 24 * 60 as minutes
  from (select '00:30' as time from dual union all
        select '08:00' as time from dual union all
        select '08:30' as time from dual union all
        select '12:00' as time from dual union all
        select '23:59' as time from dual
       );

Here is some sample input and output

time  minutes
====  =======
00:30      30
08:00     480
08:30     510
12:00     720
23:59   1 439


问:
Loop json variable in javascript
I have a variable in which I get json value. The value comes from 4 tables. I want to loop each table while assigning values. Below is my code

```<code>var dataResponse = JSON.parse(response);
</code>```

I get values from table as

dataResponse.Table[0] , dataResponse.Table[1] ....

how to loop it in javascript. Please help

My json value

```<code>{
  "Table": [{
    "JOB_PROGRESS_ID": 4.0,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU",
    "LINK_ID": "12345678",
    "SPAN_TYPE": "INTERCITY",
    "NE_SPAN_LENGTH": 200.0,
    "HOTO_OFFERED_LENGTH": 26.0,
    "LIT_OFFERED_LENGTH": 30.0,
    "HOTO_ACTUAL_LENGTH": 20.0,
    "LIT_ACTUAL_LENGTH": 15.0,
    "HOTO_OFFERED_DATE": null,
    "HOTO_ACCEPTENCE_DATE": null,
    "LIT_ACCEPTENCE_DATE": null,
    "APPROV_REJECT_REMARK": null,
    "ISABDMISSING": 1.0,
    "JOB_ID": 1.0,
    "MAINTENANCEZONECODE": "INMUKLYN01"
  }],
  "Table1": [{
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.09,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": null,
    "ASBUILT_LENGTH": 0.33,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 12.41,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.01,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.46,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 8,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.02,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 6,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.33,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "CLAMP",
    "ASBUILT_LENGTH": 0.48,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 5,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.14,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 8,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 5.45,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": null,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.23,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }],
  "Table2": [],
  "Table3": [{
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }]
}
</code>```

UPDATE

```<code>var dataResponse = JSON.parse(response);

for (var i = 0; i < dataResponse.Table.length; i++) {
  if (dataResponse.Table[i] != "" || dataResponse.Table[i] != null) {
    $("#spnLinkId").text(dataResponse.Table[i].LINK_ID);
    $("#spnSpanLength").text(dataResponse.Table[i].NE_SPAN_LENGTH);
    $("#txtFiberActlength").val(dataResponse.Table[i].HOTO_ACTUAL_LENGTH);
    $("#txtLITActlength").val(dataResponse.Table[i].LIT_ACTUAL_LENGTH);
  }
  if (dataResponse.Table[i].ISABDMISSING != "" || dataResponse.Table[i].ISABDMISSING != null) {

    if (dataResponse.Table[i].ISABDMISSING == 1) {
      $("#FEmissingAsBuiltYes").prop("checked", true);
    } else {
      $("#FEmissingAsBuiltNo").prop("checked", true);
    }
  }
}
</code>```

答:
The response is an object not an array.
For iterating over an object, we use for-in loop and
for iterating over an array, we use for loop.
In your case, you use for-in loop.

```<code>for(var item in dataResponse){
//logic
}
</code>```

Title: Loop json variable in javascript

Body:
I have a variable in which I get json value. The value comes from 4 tables. I want to loop each table while assigning values. Below is my code

var dataResponse = JSON.parse(response);

I get values from table as

dataResponse.Table[0] , dataResponse.Table[1] ....

how to loop it in javascript. Please help

My json value

{
  "Table": [{
    "JOB_PROGRESS_ID": 4.0,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU",
    "LINK_ID": "12345678",
    "SPAN_TYPE": "INTERCITY",
    "NE_SPAN_LENGTH": 200.0,
    "HOTO_OFFERED_LENGTH": 26.0,
    "LIT_OFFERED_LENGTH": 30.0,
    "HOTO_ACTUAL_LENGTH": 20.0,
    "LIT_ACTUAL_LENGTH": 15.0,
    "HOTO_OFFERED_DATE": null,
    "HOTO_ACCEPTENCE_DATE": null,
    "LIT_ACCEPTENCE_DATE": null,
    "APPROV_REJECT_REMARK": null,
    "ISABDMISSING": 1.0,
    "JOB_ID": 1.0,
    "MAINTENANCEZONECODE": "INMUKLYN01"
  }],
  "Table1": [{
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.09,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": null,
    "ASBUILT_LENGTH": 0.33,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 12.41,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 3,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.01,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.46,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 8,
    "ROUTETYPE": "HDD",
    "ASBUILT_LENGTH": 0.02,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 6,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.33,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 7,
    "ROUTETYPE": "CLAMP",
    "ASBUILT_LENGTH": 0.48,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 5,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.14,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": 8,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 5.45,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }, {
    "NUMBEROFDUCTS": null,
    "ROUTETYPE": "OT",
    "ASBUILT_LENGTH": 0.23,
    "SPAN_ID": "MUMUMBMUKLYNSPN001_BU"
  }],
  "Table2": [],
  "Table3": [{
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }, {
    "UMS_GROUP_ASS_BY_NAME": "Construction_Eng",
    "MODIFIED_BY": "HARDIK1.SHAH",
    "MODIFIED_DATE": "2017-11-27T12:07:39",
    "APPROVED_DATE": null,
    "REJECTED_DATE": null
  }]
}

UPDATE

var dataResponse = JSON.parse(response);

for (var i = 0; i < dataResponse.Table.length; i++) {
  if (dataResponse.Table[i] != "" || dataResponse.Table[i] != null) {
    $("#spnLinkId").text(dataResponse.Table[i].LINK_ID);
    $("#spnSpanLength").text(dataResponse.Table[i].NE_SPAN_LENGTH);
    $("#txtFiberActlength").val(dataResponse.Table[i].HOTO_ACTUAL_LENGTH);
    $("#txtLITActlength").val(dataResponse.Table[i].LIT_ACTUAL_LENGTH);
  }
  if (dataResponse.Table[i].ISABDMISSING != "" || dataResponse.Table[i].ISABDMISSING != null) {

    if (dataResponse.Table[i].ISABDMISSING == 1) {
      $("#FEmissingAsBuiltYes").prop("checked", true);
    } else {
      $("#FEmissingAsBuiltNo").prop("checked", true);
    }
  }
}

Body:
The response is an object not an array.
For iterating over an object, we use for-in loop and
for iterating over an array, we use for loop.
In your case, you use for-in loop.

for(var item in dataResponse){
//logic
}


问:
Access token gives only id, all other params are empty or null
I'm new here and I tried to get started with some videos in youtube. I did all exactly like in the video, but netbeans got only my id. Graph api explorer gives me other params too, netbeans doesn't. Some arrays are empty and all other params are null.

Here are vids.

https://youtu.be/m14hYs1T3FA
https://youtu.be/GwbO_PdwK_4

Thanks for your help!

答:
You have to provide the parameter you like to receive in your call.

```<code>User user = facebookClient.fetchObject("me", User.class,
        Parameter.with("fields", "id,name,email")); // this is the important part
</code>```

Here you can see, how this is done with more explanation and deeper insights: http://restfb.com/documentation/#advanced-usage-selecting-fields

BTW these videos are highly outdated as you see on the really old RestFB version. Currently 1.49.0 is the latest version and they use something with 1.18.0! So you can take them as a hint how to start but you have to read the Facebook and the RestFB documentation.

Body:
You have to provide the parameter you like to receive in your call.

User user = facebookClient.fetchObject("me", User.class,
        Parameter.with("fields", "id,name,email")); // this is the important part

Here you can see, how this is done with more explanation and deeper insights: http://restfb.com/documentation/#advanced-usage-selecting-fields

BTW these videos are highly outdated as you see on the really old RestFB version. Currently 1.49.0 is the latest version and they use something with 1.18.0! So you can take them as a hint how to start but you have to read the Facebook and the RestFB documentation.


问:
input type date only for mobile
I am trying to make time and date picker for my project. I want to time and date picker I will use one plugins, but that's only for desktop browsers and when it will browse on mobile it will trigger mobile native time/date picker. I was looking that type plugins, but I don't get it yet. If you guys know then please let me know. I tried to do something add/remove class Depending on Screen Size. It adds and remove class, but plugins not fired.

bellow is my code

https://codepen.io/pagol/pen/MOzVMP

html

```<code><div class="datepicker test">
<input type="date" class="change" id="myinput">
</div>
</code>```

js

```<code>jQuery(document).ready(function(){

  TinyDatePicker('.test input');

});

$(function(){

$(window).bind("resize",function(){
    console.log($(this).width())
    if($(this).width() <500){
    $('.datepicker').removeClass('test').addClass('red')
    }
    else{
    $('div').removeClass('red').addClass('test')
    }
})
})
</code>```

答:
You could use a custom build of Modernizr:

(You only need to include the input type fields).

```<code>if (!Modernizr.inputtypes.date) {
  jQuery(document).ready(function(){
    TinyDatePicker('.test input');
  });
}
</code>```

This will check if the browser has native support for input type="date". If not then it will use your custom datepicker.

Title: input type date only for mobile

Body:
I am trying to make time and date picker for my project. I want to time and date picker I will use one plugins, but that's only for desktop browsers and when it will browse on mobile it will trigger mobile native time/date picker. I was looking that type plugins, but I don't get it yet. If you guys know then please let me know. I tried to do something add/remove class Depending on Screen Size. It adds and remove class, but plugins not fired.

bellow is my code

https://codepen.io/pagol/pen/MOzVMP

html

<input type="date" class="change" id="myinput">

js

jQuery(document).ready(function(){

  TinyDatePicker('.test input');

});

$(function(){

$(window).bind("resize",function(){
    console.log($(this).width())
    if($(this).width() <500){
    $('.datepicker').removeClass('test').addClass('red')
    }
    else{
    $('div').removeClass('red').addClass('test')
    }
})
})

Body:
You could use a custom build of Modernizr:

(You only need to include the input type fields).

if (!Modernizr.inputtypes.date) {
  jQuery(document).ready(function(){
    TinyDatePicker('.test input');
  });
}

This will check if the browser has native support for input type="date". If not then it will use your custom datepicker.


问:
animate.css bounceindown not working in safari
The animation is not working in safari.</p>

```<code>@media screen and (min-color-index:0) and (-webkit-min-device-pixel-ratio:0) {
  @media {
    img.img-responsive.padd-bottom.desktop {
      display: none;
    }
    .col-md-10.col-sm-10.ftr.clearfix.animated.animated-delay-15s.bounceInDown.safari_only {
      animation-duration: 5s !important;
      animation-delay: 15s !important;
      z-index: 9999;
      margin-top: -46%;
      margin-left: 290px;
      width: 60%;
      -webkit-animation-duration: 5s !important;
      -moz-animation-duration: 5s !important;
      -o-animation-duration: 5s !important;
      animation-duration: 5s !important;
      display: none;
    }
  }
}
</code>```

答:
```<code><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>    @-moz-keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -moz-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -moz-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -moz-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    @-webkit-keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -webkit-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -webkit-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -webkit-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    @keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -moz-transform: translateY(0);
        -ms-transform: translateY(0);
        -webkit-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -moz-transform: translateY(-30px);
        -ms-transform: translateY(-30px);
        -webkit-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -moz-transform: translateY(-15px);
        -ms-transform: translateY(-15px);
        -webkit-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    body {
      background: black;
    }

    .arrow {
      position: fixed;
      bottom: 0;
      left: 50%;
      margin-left: -20px;
      width: 40px;
      height: 40px;
      background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB3aWR0aD0iNTEycHgiIGhlaWdodD0iNTEycHgiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA1MTIgNTEyIiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIGZpbGw9IiNGRkZGRkYiIGQ9Ik0yOTMuNzUxLDQ1NS44NjhjLTIwLjE4MSwyMC4xNzktNTMuMTY1LDE5LjkxMy03My42NzMtMC41OTVsMCwwYy0yMC41MDgtMjAuNTA4LTIwLjc3My01My40OTMtMC41OTQtNzMuNjcyICBsMTg5Ljk5OS0xOTBjMjAuMTc4LTIwLjE3OCw1My4xNjQtMTkuOTEzLDczLjY3MiwwLjU5NWwwLDBjMjAuNTA4LDIwLjUwOSwyMC43NzIsNTMuNDkyLDAuNTk1LDczLjY3MUwyOTMuNzUxLDQ1NS44Njh6Ii8+DQo8cGF0aCBmaWxsPSIjRkZGRkZGIiBkPSJNMjIwLjI0OSw0NTUuODY4YzIwLjE4LDIwLjE3OSw1My4xNjQsMTkuOTEzLDczLjY3Mi0wLjU5NWwwLDBjMjAuNTA5LTIwLjUwOCwyMC43NzQtNTMuNDkzLDAuNTk2LTczLjY3MiAgbC0xOTAtMTkwYy0yMC4xNzgtMjAuMTc4LTUzLjE2NC0xOS45MTMtNzMuNjcxLDAuNTk1bDAsMGMtMjAuNTA4LDIwLjUwOS0yMC43NzIsNTMuNDkyLTAuNTk1LDczLjY3MUwyMjAuMjQ5LDQ1NS44Njh6Ii8+DQo8L3N2Zz4=);
      background-size: contain;
    }

    .bounce {
      -moz-animation: bounce 2s 1;
      -webkit-animation: bounce 2s 1;
      animation: bounce 2s 1;
    }</code>```

```
</div>
</div>

</code>```

Body:
The animation is not working in safari.

@media screen and (min-color-index:0) and (-webkit-min-device-pixel-ratio:0) {
  @media {
    img.img-responsive.padd-bottom.desktop {
      display: none;
    }
    .col-md-10.col-sm-10.ftr.clearfix.animated.animated-delay-15s.bounceInDown.safari_only {
      animation-duration: 5s !important;
      animation-delay: 15s !important;
      z-index: 9999;
      margin-top: -46%;
      margin-left: 290px;
      width: 60%;
      -webkit-animation-duration: 5s !important;
      -moz-animation-duration: 5s !important;
      -o-animation-duration: 5s !important;
      animation-duration: 5s !important;
      display: none;
    }
  }
}

Body:
    @-moz-keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -moz-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -moz-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -moz-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    @-webkit-keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -webkit-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -webkit-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -webkit-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    @keyframes bounce {
      0%, 20%, 50%, 80%, 100% {
        -moz-transform: translateY(0);
        -ms-transform: translateY(0);
        -webkit-transform: translateY(0);
        transform: translateY(0);
      }
      40% {
        -moz-transform: translateY(-30px);
        -ms-transform: translateY(-30px);
        -webkit-transform: translateY(-30px);
        transform: translateY(-30px);
      }
      60% {
        -moz-transform: translateY(-15px);
        -ms-transform: translateY(-15px);
        -webkit-transform: translateY(-15px);
        transform: translateY(-15px);
      }
    }
    body {
      background: black;
    }

    .arrow {
      position: fixed;
      bottom: 0;
      left: 50%;
      margin-left: -20px;
      width: 40px;
      height: 40px;
      background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB3aWR0aD0iNTEycHgiIGhlaWdodD0iNTEycHgiIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCA1MTIgNTEyIiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxwYXRoIGZpbGw9IiNGRkZGRkYiIGQ9Ik0yOTMuNzUxLDQ1NS44NjhjLTIwLjE4MSwyMC4xNzktNTMuMTY1LDE5LjkxMy03My42NzMtMC41OTVsMCwwYy0yMC41MDgtMjAuNTA4LTIwLjc3My01My40OTMtMC41OTQtNzMuNjcyICBsMTg5Ljk5OS0xOTBjMjAuMTc4LTIwLjE3OCw1My4xNjQtMTkuOTEzLDczLjY3MiwwLjU5NWwwLDBjMjAuNTA4LDIwLjUwOSwyMC43NzIsNTMuNDkyLDAuNTk1LDczLjY3MUwyOTMuNzUxLDQ1NS44Njh6Ii8+DQo8cGF0aCBmaWxsPSIjRkZGRkZGIiBkPSJNMjIwLjI0OSw0NTUuODY4YzIwLjE4LDIwLjE3OSw1My4xNjQsMTkuOTEzLDczLjY3Mi0wLjU5NWwwLDBjMjAuNTA5LTIwLjUwOCwyMC43NzQtNTMuNDkzLDAuNTk2LTczLjY3MiAgbC0xOTAtMTkwYy0yMC4xNzgtMjAuMTc4LTUzLjE2NC0xOS45MTMtNzMuNjcxLDAuNTk1bDAsMGMtMjAuNTA4LDIwLjUwOS0yMC43NzIsNTMuNDkyLTAuNTk1LDczLjY3MUwyMjAuMjQ5LDQ1NS44Njh6Ii8+DQo8L3N2Zz4=);
      background-size: contain;
    }

    .bounce {
      -moz-animation: bounce 2s 1;
      -webkit-animation: bounce 2s 1;
      animation: bounce 2s 1;
    }

    <div class="arrow bounce"></div>


问:
Round of experiance in years months
I am saving employees work experiance for example as 5.14 n all when I display it, it should show me as 6.2yrs of experiance;

How can I calculate it in PHP or laravel framework?

答:
Considering you 5.14 as string i have created simple function for you </p>

```<code><?php
function totalEexperience($experience)
{
     $experience = '5.14';
     $array = explode(".",$experience);
     $resultArray[] = $array[0] + round($array[1]/12);
     $resultArray[] = $array[1] % 12;
     $totalExperience = implode(".", $resultArray);
     return $totalExperience;
}
?>
</code>```

Title: Round of experiance in years months

Body:
Considering you 5.14 as string i have created simple function for you

<?php
function totalEexperience($experience)
{
     $experience = '5.14';
     $array = explode(".",$experience);
     $resultArray[] = $array[0] + round($array[1]/12);
     $resultArray[] = $array[1] % 12;
     $totalExperience = implode(".", $resultArray);
     return $totalExperience;
}
?>


问:
How can I pass multiple source files to the TypeScript compiler?
TypeScript is designed for large-scale JavaScripty projects which typically consist of multiple internally produced files along with externally produced libraries. How does the TypeScript compiler (tsc) expect you to provide it with the complete set of files that make up a project?</p>

答:
If someone needs multiple files pretranspiled before the actual project compiling, use a separate tsconfig with the --project compiler option.

Compile a project given a valid configuration file. The argument can
  be a file path to a valid JSON configuration file, or a directory path
  to a directory containing a tsconfig.json file. See tsconfig.json
  documentation for more details.

One use case would be the need of the resulting JS files used afterwards  in command line arguments for ionic app scripts.


问:
Clear PHP session on tab close?
I'm trying to logout each time the user closes it's tab. I've saw all similar questions, but I still haven't found anything that works.

Here's what I've done:

```<code><script type="text/javascript">
    $(document).ready(function() {
        $(window).bind("beforeunload", function() {
            confirm("Do you really want to logout?") && $.ajax({
                type: "GET",
                url: "/admin/account/logout"
            })
        })
    });
</script>
</code>```

I've tried without the confirm, but it still doesn't work. I'm absolutely sure that it can be done, since my bank's website has the same functionality.

EDIT:
Without the confirm it does fire the logout ajax, but even when I browse trough the pages. Which reminds me, that my bank's website uses something like AngularJS, which is not exactly a true link-browsing system, right? Maybe that's why it works there?

答:
The issue with your code is that the request is executed asyncronously and gets terminated with the closing of the window.
If you set the async paramenter to false the ajax request will get executed before the tab/window is closed.

Unfortunately this won't solve your problem since this event is fired every time you're about to leave the page. If you are just trying to hack a solution you can use the approach mentioned here: https://stackoverflow.com/a/44057659/5173095 - trigger a timeout on the server side and logout the user if he doesn't make another request after the timeout has passed.

Title: Clear PHP session on tab close?

Body:
I'm trying to logout each time the user closes it's tab. I've saw all similar questions, but I still haven't found anything that works.

Here's what I've done:

I've tried without the confirm, but it still doesn't work. I'm absolutely sure that it can be done, since my bank's website has the same functionality.

EDIT:
Without the confirm it does fire the logout ajax, but even when I browse trough the pages. Which reminds me, that my bank's website uses something like AngularJS, which is not exactly a true link-browsing system, right? Maybe that's why it works there?


问:
How can I rewrite a code for php server to a code for Apache?
Is it possible that a code written for php server could be rewritten for apache server? Is it even a legal question in the first place? I have very little experience on server-side technologies.
THanks</p>

答: Apache has the ability to serve PHP - read more at the wiki. </p>


问:
Replacing null values in object
I have array of objects like

```<code>{
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4",
  ...
}
</code>```

How can I replace all null values to '-' string (maybe with es6 for shorter code)?

答:
You can iterate over all keys of an object as follows:

```<code>var obj = {a: 1, b:2};
Object.keys(obj).forEach(someFunction);
</code>```

Now, to replace null-values, you can just test for null and set it to '-'.

```<code>var obj = {
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4"
};

Object.keys(obj).forEach(function(key) {
    if(obj[key] === null) {
        obj[key] = '-';
    }
})
</code>```

Title: Replacing null values in object

Body:
I have array of objects like

{
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4",
  ...
}

How can I replace all null values to '-' string (maybe with es6 for shorter code)?

Body:
You can iterate over all keys of an object as follows:

var obj = {a: 1, b:2};
Object.keys(obj).forEach(someFunction);

Now, to replace null-values, you can just test for null and set it to '-'.

var obj = {
  key1: "value1",
  key2: "value2",
  key3: null,
  key4: "value4"
};

Object.keys(obj).forEach(function(key) {
    if(obj[key] === null) {
        obj[key] = '-';
    }
})


问:
DB2 Comma Separated Output by Groups
Is there a built in function for comma separated column values in DB2 SQL?

Example: If there are columns with an ID and it has 3 rows with the same ID but have three different roles, the data should be concatenated with a comma.

```<code>ID   | Role
------------
4555 | 2
4555 | 3
4555 | 4
</code>```

The output should look like the following, per row:

4555 2,3,4

答:
Since DB2 9.7.5 there is a function for that:

LISTAGG(colname, separator)

check this for more information: Using LISTAGG to Turn Rows of Data into a Comma Separated List

Title: DB2 Comma Separated Output by Groups

Body:
Is there a built in function for comma separated column values in DB2 SQL?

Example: If there are columns with an ID and it has 3 rows with the same ID but have three different roles, the data should be concatenated with a comma.

ID   | Role
------------
4555 | 2
4555 | 3
4555 | 4

The output should look like the following, per row:

4555 2,3,4


问:
Drag and Drop the images on canvas using jqueryui

I have completed the dragging and dropping  of buttons and nav bar and it is draggable after drop also and working properly,

But now  problem is now i want to drag and drop the image.i have tried many different things but unable to do this.

```<code>I am adding my fiddle please check
</code>```

http://jsfiddle.net/Yousuf_007/d6gowym5/

Thanx

答:
I'm now working on a project similar to yours, but in the left div I have a list and every draggable element is a list item. This function works perfect for me, maybe it will be useful for you:

```<code>        $('#streams li').draggable({
            helper: 'clone',
            revert: 'invalid'
        });
        //Function for setting drag and drop settings
        function foo(){
            $('.foo').each(function() {
                //Making dropped elements draggable again
                $('.foo').draggable({
                    containment: $(this).parent(),
                    stack: '.foo',
                    snap: '.foo',
                    drop: function (event, ui) {
                        var pos = ui.draggable.offset(), dPos = $(this).offset();
                        alert("nodeid: " + ui.draggable.data("noteid") +
                            ", Top: " + (pos.top - dPos.top) +
                            ", Left: " + (pos.left - dPos.left));
                    },
                    drag: function(){
                        var draggedItemId = $(this).attr('id');
                        $(this).css({'z-index': '11'});
                        $(".class"+draggedItemId).css({'z-index':'15'});
                    },
                    stop: function(){
                        var draggedItemId = $(this).attr('id');
                        $(this).css({'z-index': '0'});
                        $(".class"+draggedItemId).css({'z-index':'10'});
                    }
                });
            });
        }
        var fooCount = $('.foo').length;
        //Generating new table after drop
        $('#mainDiv').droppable({
            drop: function(event, ui) {
                //Getting position where new item was dropped
                var pos = ui.draggable.offset(), dPos = $(this).offset();
                var droppedTop = ui.position.top - $(this).offset().top;
                var droppedLeft = ui.position.left - $(this).offset().left;
                //Generating new table if the item is dropped first time
                if (!ui.draggable.hasClass('foo')) {
                    var Class = ui.draggable.attr("class");
                    var title = ui.draggable.text().trim();
                    var item = $('<table class="foo small elementTable ' + Class + '" name="' + title + '" id="'+(fooCount+1)+'" style="left: '+droppedLeft+'px; top: '+droppedTop+'px;"><tr class="tableHeader"><th class="thClass"><span class="header">' + title + '</span><span class="settings"><img src="Icons/pignon.png" width="17px" height="17px" alt="Settings" title="Settings" /></span></th></tr><tr><td class="add"><span class="addList">Add new link</span></td></tr></table>');
                    $(this).append(item);
                    fooCount += 1;
                    foo();
                }
            }
        });
</code>```

Try to rewrite your function and give it similar look. Also change your DOM structure from separate elements to list, that will help you to easily implement drag and drop. Here is the fiddle: https://jsfiddle.net/vaxobasilidze/7gvon7h1/

EDIT: Here is your fiddle. I have initialized drag and drop. The rest, styling and what you do to your content while dropping is up to you: http://jsfiddle.net/vaxobasilidze/rhz6ovyz/

Body:
I have completed the dragging and dropping  of buttons and nav bar and it is draggable after drop also and working properly,

But now  problem is now i want to drag and drop the image.i have tried many different things but unable to do this.

I am adding my fiddle please check

http://jsfiddle.net/Yousuf_007/d6gowym5/

Thanx

Body:
I'm now working on a project similar to yours, but in the left div I have a list and every draggable element is a list item. This function works perfect for me, maybe it will be useful for you:

        $('#streams li').draggable({
            helper: 'clone',
            revert: 'invalid'
        });
        //Function for setting drag and drop settings
        function foo(){
            $('.foo').each(function() {
                //Making dropped elements draggable again
                $('.foo').draggable({
                    containment: $(this).parent(),
                    stack: '.foo',
                    snap: '.foo',
                    drop: function (event, ui) {
                        var pos = ui.draggable.offset(), dPos = $(this).offset();
                        alert("nodeid: " + ui.draggable.data("noteid") +
                            ", Top: " + (pos.top - dPos.top) +
                            ", Left: " + (pos.left - dPos.left));
                    },
                    drag: function(){
                        var draggedItemId = $(this).attr('id');
                        $(this).css({'z-index': '11'});
                        $(".class"+draggedItemId).css({'z-index':'15'});
                    },
                    stop: function(){
                        var draggedItemId = $(this).attr('id');
                        $(this).css({'z-index': '0'});
                        $(".class"+draggedItemId).css({'z-index':'10'});
                    }
                });
            });
        }
        var fooCount = $('.foo').length;
        //Generating new table after drop
        $('#mainDiv').droppable({
            drop: function(event, ui) {
                //Getting position where new item was dropped
                var pos = ui.draggable.offset(), dPos = $(this).offset();
                var droppedTop = ui.position.top - $(this).offset().top;
                var droppedLeft = ui.position.left - $(this).offset().left;
                //Generating new table if the item is dropped first time
                if (!ui.draggable.hasClass('foo')) {
                    var Class = ui.draggable.attr("class");
                    var title = ui.draggable.text().trim();
                    var item = $('<table class="foo small elementTable ' + Class + '" name="' + title + '" id="'+(fooCount+1)+'" style="left: '+droppedLeft+'px; top: '+droppedTop+'px;"><tr class="tableHeader"><th class="thClass"><span class="header">' + title + '</span><span class="settings"><img src="Icons/pignon.png" width="17px" height="17px" alt="Settings" title="Settings" /></span></th></tr><tr><td class="add"><span class="addList">Add new link</span></td></tr></table>');
                    $(this).append(item);
                    fooCount += 1;
                    foo();
                }
            }
        });

Try to rewrite your function and give it similar look. Also change your DOM structure from separate elements to list, that will help you to easily implement drag and drop. Here is the fiddle: https://jsfiddle.net/vaxobasilidze/7gvon7h1/

EDIT: Here is your fiddle. I have initialized drag and drop. The rest, styling and what you do to your content while dropping is up to you: http://jsfiddle.net/vaxobasilidze/rhz6ovyz/


问:
Probabilistic Early Expiration with Guava Cache
I have a Guava cache created with expireAfterWrite(20, TimeUnit.MINUTES). The cache is also initialized with dozens of entries when created. When values expire, client is supposed to call an external service and refresh the cache.

Problem is - all the initialized values would expire simultaneously and after 20 minutes, and the client would call the service dozens of times almost at the same instance.

I don't want this to happen. To avoid this - one idea is to probabilistically expire the entries a little earlier than the TTL so that the service won't get hit a lot at the same time.

Unfortunately, I don't see an option of doing this with Guava cache - at least nothing popped up from the Wiki or Javadoc. Is there any other library available? I am trying to avoid writing my own implementation of a cache for this purpose.

答:
Cache warming is a fairly involved topic, so there are a lot of reasonable approaches but not necessarily a single "correct" one. An easy option would be to simply trigger additional writes at staggered times in the future in order to reset the expiry times:

```<code>public static <K, V> void staggerCacheExpiration(
    Cache<K, V> cache, long maxExpiration, TimeUnit unit, ScheduledExecutorService scheduler) {
  for (Entry<K, V> e : cache.asMap().entrySet()) {
    long delay = ThreadLocalRandom.current().nextLong(0, maxExpiration);
    scheduler.schedule(() -> cache.put(e.getKey(), e.getValue()), delay, unit);
  }
}
</code>```

A critical problem with any approach that relies on Cache itself is you'll end up trigger a (potentially expensive) refresh only when a caller needs the value. It may be better not to use expireAfterWrite() or refreshAfterWrite() and instead run a dedicated thread that's responsible for updating each key in sequence. By having a single thread updating all keys you'll naturally avoid any hotspots where multiple keys are being refreshed simultaneously, and also avoid blocking any threads relying on values from the cache.

As Ben Manes suggests you might prefer to encapsulate your Cache in your own type so whatever behavior you choose isn't exposed to your callers.

Body:
Cache warming is a fairly involved topic, so there are a lot of reasonable approaches but not necessarily a single "correct" one. An easy option would be to simply trigger additional writes at staggered times in the future in order to reset the expiry times:

public static <K, V> void staggerCacheExpiration(
    Cache<K, V> cache, long maxExpiration, TimeUnit unit, ScheduledExecutorService scheduler) {
  for (Entry<K, V> e : cache.asMap().entrySet()) {
    long delay = ThreadLocalRandom.current().nextLong(0, maxExpiration);
    scheduler.schedule(() -> cache.put(e.getKey(), e.getValue()), delay, unit);
  }
}

A critical problem with any approach that relies on Cache itself is you'll end up trigger a (potentially expensive) refresh only when a caller needs the value. It may be better not to use expireAfterWrite() or refreshAfterWrite() and instead run a dedicated thread that's responsible for updating each key in sequence. By having a single thread updating all keys you'll naturally avoid any hotspots where multiple keys are being refreshed simultaneously, and also avoid blocking any threads relying on values from the cache.

As Ben Manes suggests you might prefer to encapsulate your Cache in your own type so whatever behavior you choose isn't exposed to your callers.


问:
How to get the distinct id using the same column twice in SQL

I have the following issue. I have a user_id column and an attribute_idcolumn and I want to get the users id that has the attribute_id 1 and 4.

In this case, the result would be one single column with the user_id 1 and 35, once they both have the attribute id 1 and 4.

答:
Really depends on your data, but if you have only 1s and 4s, you can do it like this:

```<code>with users as
(
select '62' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '1' as userid,  1 as attributeid union
select '35' as userid,  1 as attributeid union
select '35' as userid,  4 as attributeid union
select '1' as userid,  4 as attributeid
)
select userid from users group by userid having sum(distinct attributeid) = 5;
</code>```

If you can also have 2 and 3 as attributeid (so you get also 5), you can use this:

```<code>with users as
(
select '62' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '1' as userid,  1 as attributeid union
select '35' as userid,  1 as attributeid union
select '35' as userid,  4 as attributeid union
select '1' as userid,  4 as attributeid
)
select u1.userid from users u1
    inner join users u4 on u1.userid = u4.userid
                        and u1.attributeid = 1
                        and u4.attributeid = 4;
</code>```

Body:
Really depends on your data, but if you have only 1s and 4s, you can do it like this:

with users as
(
select '62' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '1' as userid,  1 as attributeid union
select '35' as userid,  1 as attributeid union
select '35' as userid,  4 as attributeid union
select '1' as userid,  4 as attributeid
)
select userid from users group by userid having sum(distinct attributeid) = 5;

If you can also have 2 and 3 as attributeid (so you get also 5), you can use this:

with users as
(
select '62' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '63' as userid,  1 as attributeid union
select '1' as userid,  1 as attributeid union
select '35' as userid,  1 as attributeid union
select '35' as userid,  4 as attributeid union
select '1' as userid,  4 as attributeid
)
select u1.userid from users u1
    inner join users u4 on u1.userid = u4.userid
                        and u1.attributeid = 1
                        and u4.attributeid = 4;


答:
You have to fire TinyDatePicker (that i do not know about) after adding the class. Here you are just adding classes without attaching TinyDatePicker :</p>

```<code>var dp = null;
attachDatePicker = function(){
    if(dp === null || typeof dp === 'undefined')
        dp = TinyDatePicker('.test input');
}

$(function(){
    $(window).bind("resize",function(){
        console.log($(this).width())
        if($(this).width() <500){
            $('.datepicker').removeClass('test').addClass('red');
            //you should alsa remove TinyDatePicker here
            if(dp !== null){
                dp.destroy();
                dp = null;
            }
        }
        else{
            $('div').removeClass('red').addClass('test');
            attachDatePicker();
        }
    });
});

jQuery(document).ready(function(){
  attachDatePicker();
});
</code>```

Title: input type date only for mobile

Body:
You have to fire TinyDatePicker (that i do not know about) after adding the class. Here you are just adding classes without attaching TinyDatePicker :

var dp = null;
attachDatePicker = function(){
    if(dp === null || typeof dp === 'undefined')
        dp = TinyDatePicker('.test input');
}

$(function(){
    $(window).bind("resize",function(){
        console.log($(this).width())
        if($(this).width() <500){
            $('.datepicker').removeClass('test').addClass('red');
            //you should alsa remove TinyDatePicker here
            if(dp !== null){
                dp.destroy();
                dp = null;
            }
        }
        else{
            $('div').removeClass('red').addClass('test');
            attachDatePicker();
        }
    });
});

jQuery(document).ready(function(){
  attachDatePicker();
});


问:
multiple image upload to different column php mysql
good day , here i have a page that store data with some images in it , 3 images to be exact,

    <?php
    $brg            = $_POST['id'];
    $nama           = $_POST['nm'];
    $img            = $_FILES['img']['name'];
    $tmp            = $_FILES['img']['tmp_name'];
    $img1           = $_FILES['img1']['name'];
    $tmp1           = $_FILES['img1']['tmp_name'];
    $img2           = $_FILES['img2']['name'];
    $tmp2           = $_FILES['img2']['tmp_name'];

    $temp           = explode(".", $img);
    $temp1          = explode(".", $img1);
    $temp2          = explode(".", $img2);
    $new            = round(microtime(true)) . '.' . end($temp);
    $new1           = round(microtime(true)) . '.' . end($temp1);
    $new2           = round(microtime(true)) . '.' . end($temp2);
    $path           = "img/photo/".$new;
    $path1          = "img/photo/".$new1;
    $path2          = "img/photo/".$new2;
    move_uploaded_file($tmp, $path);
    move_uploaded_file($tmp1, $path1);
    move_uploaded_file($tmp2, $path2);

$c  = "insert into imgstuff values('$brg','$nama','$new','$new1','$new2');";

$ins=mysqli_query($con,$c);

if($ins){
header('location: test.php?success='.base64_encode('success'));
} else {
header('location: test.php?error='.base64_encode('failed'));
}
?>
```

code above works perfectly but as you can see it ends up horribly ugly and it produce same file name for three picture ,
 my question, is there any ways to made my code cleaner and easy to maintain and whats wrong with my naming files method ?

答:
Maybe

```<code>round(microtime(true)) . '.' . end($temp);
</code>```

return the same things because it's done almost at the same time. Can you try something like uuid or even a simple function such as

```<code>function getUniqFileName($end) {
    $token = md5(sha1(rand()));

    return sprintf($token%s, $end);
}
</code>```

and then in your code

```<code>$new = getUniqFileName(end($temp));
</code>```

That will give you a bit more uniq name very quickly ?

(Edit : removed the round which is quite useless in this case)

Body:
good day , here i have a page that store data with some images in it , 3 images to be exact,

    <?php
    $brg            = $_POST['id'];
    $nama           = $_POST['nm'];
    $img            = $_FILES['img']['name'];
    $tmp            = $_FILES['img']['tmp_name'];
    $img1           = $_FILES['img1']['name'];
    $tmp1           = $_FILES['img1']['tmp_name'];
    $img2           = $_FILES['img2']['name'];
    $tmp2           = $_FILES['img2']['tmp_name'];

    $temp           = explode(".", $img);
    $temp1          = explode(".", $img1);
    $temp2          = explode(".", $img2);
    $new            = round(microtime(true)) . '.' . end($temp);
    $new1           = round(microtime(true)) . '.' . end($temp1);
    $new2           = round(microtime(true)) . '.' . end($temp2);
    $path           = "img/photo/".$new;
    $path1          = "img/photo/".$new1;
    $path2          = "img/photo/".$new2;
    move_uploaded_file($tmp, $path);
    move_uploaded_file($tmp1, $path1);
    move_uploaded_file($tmp2, $path2);

$c  = "insert into imgstuff values('$brg','$nama','$new','$new1','$new2');";

$ins=mysqli_query($con,$c);

if($ins){
header('location: test.php?success='.base64_encode('success'));
} else {
header('location: test.php?error='.base64_encode('failed'));
}
?>

code above works perfectly but as you can see it ends up horribly ugly and it produce same file name for three picture ,
 my question, is there any ways to made my code cleaner and easy to maintain and whats wrong with my naming files method ?

Body:
Maybe

round(microtime(true)) . '.' . end($temp);

return the same things because it's done almost at the same time. Can you try something like uuid or even a simple function such as

function getUniqFileName($end) {
    $token = md5(sha1(rand()));

    return sprintf($token%s, $end);
}

and then in your code

$new = getUniqFileName(end($temp));

That will give you a bit more uniq name very quickly ?

(Edit : removed the round which is quite useless in this case)


问:
How to know android.os.TransactionTooLarge or not
I am trying to pass data more than 1Mb here, data it may be possible bitmap or string so, android.os.TransactionTooLarge exception thrown by an application but below 24 API level it was a simple warning but >=24 API level it will create application crash so, how can I know this transaction is valid or not else have any API available which represents this transaction is valid or not?. Can I prior know the transaction is valid or not?

for example,

```<code>Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is too long string data...");
startActivity(sendIntent);
</code>```

答:
If you really need to measure the size of the String or Bitmap you can get its byte array and count as per this link.

In your case you probably should not pass these objects in bundles between activities. Instead you can put it in a Singleton object, put it in an LRU cache or persist it.

If you need to keep your object intact even if the app's process dies, than your only option is persisting it.

Body:
I am trying to pass data more than 1Mb here, data it may be possible bitmap or string so, android.os.TransactionTooLarge exception thrown by an application but below 24 API level it was a simple warning but >=24 API level it will create application crash so, how can I know this transaction is valid or not else have any API available which represents this transaction is valid or not?. Can I prior know the transaction is valid or not?

for example,

Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is too long string data...");
startActivity(sendIntent);