问:
Bots are picking up and dropping weapons in weird way
I am making a TDS so it's time to make a mechanism to be able to pick up and drop weapons. I made it for the player and a new script for bots was based on player's one. So the problem is: I created an enemy prefab to be able to make as much of them as needed and if it is only one enemy while game is running then everything is fine: enemy passes through waypoins, picks up a weapon, then meets a better one and picks it up aswell dropping a worse one. But when I add a couple of new enemies things become weird as enemies don't pick up weapons (basically, a picked-up weapon doesn't become active) but just ignore them. At the same time the weapons on ground which are used to disappear when picked actually disappear so it doesn't make any sense. Here's the code of my realization. I hope we'll find a solution to this problem.
Thanks for you attention and sorry for my disgusting english!

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

public class EnemyDrop : MonoBehaviour
{
//Current amount of ammo
public int currentAmmo;
private Vector3 offset;
//Weapons which are active in inventory.
//LABEL0
public GameObject _activeMelee;
public static GameObject activeMelee;
public GameObject _activeBottle;
public static GameObject activeBottle;
public GameObject _activeGun;
public static GameObject activeGun;
public GameObject _activePistol;
public static GameObject activePistol;
[HideInInspector]
//ID of weapon which was active last time.
public int activeId;
//ID of weapon which is ready to be picked up.
private int activeQuestion;
//Weapon that is equipped before function ChangeWeapon().
private GameObject currentChange;
//Weapon that is ready to be picked up in function ChangeWeapon().
private GameObject groundWeapon;
public Transform enemy;
[HideInInspector]
private bool ifThereIsSmthInHand;
[HideInInspector]
//Can we move to next step? This becomes true when enemy's trigger works.
public bool mightDoNextTurn;
[HideInInspector]
private string nameOfActive;
private string nameOfWeapon;
public GameObject[] arrayOfObjects;
public int[] arrayOfIds;
public int[] arrayOfAmmo;
[HideInInspector]
public bool isFlying;
[HideInInspector]
public float speed;
private float timeWhileFlying;
[HideInInspector]
public float timing;
public int[] arrayOfValues;
private bool pickedAnEmptyWeapon;
public string nameactive;
public string nameWeapon;
public int question;

public static string getActiveWeapon () //LABEL1
{
    if (activeGun.activeSelf) {
        return "Gun";
    }
    if (activeMelee.activeSelf) {
        return "Melee";
    }
    if (activeBottle.activeSelf) {
        return "Bottle";
    }
    if (activePistol.activeSelf) {
        return "Pistol";
    }
    return "empty";
}

public static bool ifThereIsSomethingInHand ()//LABEL2
{
    if (activeMelee.activeSelf || activeGun.activeSelf || activeBottle.activeSelf || activePistol.activeSelf)
        return true;
    else
        return false;
}
void Start ()
{ //LABEL3
    activeMelee = _activeMelee;
    activeGun = _activeGun;
    activeBottle = _activeBottle;
    activePistol = _activePistol;
    activeBottle.SetActive (false);
    activeMelee.SetActive (false);
    activeGun.SetActive (false);
    activePistol.SetActive (false);
    offset = new Vector3 (0f, 0.9f, -0.5f);
    mightDoNextTurn = false;
    speed = 2;
    timeWhileFlying = 2;
    activeId = 26;
}

void Update ()
{
    ifThereIsSmthInHand = ifThereIsSomethingInHand ();
    nameOfActive = getActiveWeapon ();
    if (ifThereIsSmthInHand) {
        if (mightDoNextTurn)
            ChangeWeapon ();
        else
            actionDrop ();
    } else if (mightDoNextTurn)
        actionPick ();
    nameactive = nameOfActive;
    nameWeapon = nameOfWeapon;
    question = activeQuestion;
}

private void actionDrop () //LABEL4
{
    if (currentAmmo == 0 && nameOfActive == "Gun") {
        activeGun.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        arrayOfValues [activeId] = 0;
        DropPos ();
        activeId = 26;
    }
    if (currentAmmo == 0 && nameOfActive == "Pistol") {
        activePistol.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        arrayOfValues [activeId] = 0;
        DropPos ();
        activeId = 26;
    }
}

public void deathDrop ()
{
    arrayOfObjects [activeId].SetActive (true);
    DropPos ();
}

private void actionPick ()//LABEL5
{
    switch (nameOfWeapon) {
    case "FireWeapon":
        activeGun.SetActive (true);
        break;
    case "MeleeWeapon":
        activeMelee.SetActive (true);
        break;
    case "BottleWeapon":
        activeBottle.SetActive (true);
        break;
    case "PistolWeapon":
        activePistol.SetActive (true);
        break;
    default:
        break;
    }
    arrayOfObjects [activeQuestion].SetActive (false);
    activeId = activeQuestion;
    mightDoNextTurn = false;
}

private void DropPos ()
{
    arrayOfObjects [activeId].transform.position = enemy.transform.position - offset;
    arrayOfObjects [activeId].transform.rotation = enemy.transform.rotation;
}

private void ChangeWeapon ()//LABEL6
{
    if (arrayOfValues [activeQuestion] > arrayOfValues [activeId]) {
        if (activeMelee.activeSelf)
            currentChange = activeMelee;
        if (activeGun.activeSelf)
            currentChange = activeGun;
        if (activeBottle.activeSelf)
            currentChange = activeBottle;
        if (activePistol.activeSelf)
            currentChange = activePistol;
        currentChange.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        DropPos ();
        activeId = 26;
        arrayOfObjects [activeQuestion].SetActive (false);
        activeId = activeQuestion;
        mightDoNextTurn = false;
        if (nameOfWeapon == "BottleWeapon") {
            activeBottle.SetActive (true);
        }
        if (nameOfWeapon == "MeleeWeapon") {
            activeMelee.SetActive (true);
        }
        if (nameOfWeapon == "FireWeapon") {
            activeGun.SetActive (true);
        }
        if (nameOfWeapon == "PistolWeapon") {
            activePistol.SetActive (true);
        }
    }
}

void OnTriggerEnter (Collider other)//LABEL7
{
    if (other.gameObject.tag == "Weapon") {
        groundWeapon = other.gameObject;
        activeQuestion = other.gameObject.GetComponent<IdOfWeapon> ().localId;
        if (arrayOfValues [activeQuestion] == 0)
            activeQuestion = 26;
        if (activeQuestion >= 0 && activeQuestion <= 1000 && activeQuestion != 26) {
            if (activeQuestion < 31) {
                nameOfWeapon = "MeleeWeapon";
            }
            if (activeQuestion < 61 && activeQuestion >= 31) {
                nameOfWeapon = "BottleWeapon";
            }
            if (activeQuestion >= 61 && activeQuestion < 91) {
                nameOfWeapon = "FireWeapon";
            }
            if (activeQuestion >= 121 && activeQuestion < 151) {
                nameOfWeapon = "PistolWeapon";
            }
        }
        mightDoNextTurn = true;
    }
}

void OnTriggerStay (Collider other)//LABEL8
{
    if (other.gameObject.tag == "Weapon") {
        groundWeapon = other.gameObject;
        activeQuestion = other.gameObject.GetComponent<IdOfWeapon> ().localId;
        if (arrayOfValues [activeQuestion] == 0)
            activeQuestion = 26;
        if (activeQuestion >= 0 && activeQuestion <= 1000 && activeQuestion != 26) {
            if (activeQuestion < 31) {
                nameOfWeapon = "MeleeWeapon";
            }
            if (activeQuestion < 61 && activeQuestion >= 31) {
                nameOfWeapon = "BottleWeapon";
            }
            if (activeQuestion >= 61 && activeQuestion < 91) {
                nameOfWeapon = "FireWeapon";
            }
            if (activeQuestion >= 121 && activeQuestion < 151) {
                nameOfWeapon = "PistolWeapon";
            }
        }
        mightDoNextTurn = true;
    }
}
void OnTriggerExit (Collider other)
{
    if (other.gameObject.tag == "Weapon") {
        mightDoNextTurn = false;
        nameOfWeapon = "";
    }
    activeQuestion = 26;
    }
}
</code>```

Note: enemy is allowed to drop a weapon for only two reasons: currentAmmo is equal to 0 or if he meets a better one (based on value).

答: the keyword static will mean this variable is shared with all instances of the script. This is what is causing you problems. – Catwood 1 hour ago - that's the solution</p>

Body:
I am making a TDS so it's time to make a mechanism to be able to pick up and drop weapons. I made it for the player and a new script for bots was based on player's one. So the problem is: I created an enemy prefab to be able to make as much of them as needed and if it is only one enemy while game is running then everything is fine: enemy passes through waypoins, picks up a weapon, then meets a better one and picks it up aswell dropping a worse one. But when I add a couple of new enemies things become weird as enemies don't pick up weapons (basically, a picked-up weapon doesn't become active) but just ignore them. At the same time the weapons on ground which are used to disappear when picked actually disappear so it doesn't make any sense. Here's the code of my realization. I hope we'll find a solution to this problem.
Thanks for you attention and sorry for my disgusting english!

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class EnemyDrop : MonoBehaviour
{
//Current amount of ammo
public int currentAmmo;
private Vector3 offset;
//Weapons which are active in inventory.
//LABEL0
public GameObject _activeMelee;
public static GameObject activeMelee;
public GameObject _activeBottle;
public static GameObject activeBottle;
public GameObject _activeGun;
public static GameObject activeGun;
public GameObject _activePistol;
public static GameObject activePistol;
[HideInInspector]
//ID of weapon which was active last time.
public int activeId;
//ID of weapon which is ready to be picked up.
private int activeQuestion;
//Weapon that is equipped before function ChangeWeapon().
private GameObject currentChange;
//Weapon that is ready to be picked up in function ChangeWeapon().
private GameObject groundWeapon;
public Transform enemy;
[HideInInspector]
private bool ifThereIsSmthInHand;
[HideInInspector]
//Can we move to next step? This becomes true when enemy's trigger works.
public bool mightDoNextTurn;
[HideInInspector]
private string nameOfActive;
private string nameOfWeapon;
public GameObject[] arrayOfObjects;
public int[] arrayOfIds;
public int[] arrayOfAmmo;
[HideInInspector]
public bool isFlying;
[HideInInspector]
public float speed;
private float timeWhileFlying;
[HideInInspector]
public float timing;
public int[] arrayOfValues;
private bool pickedAnEmptyWeapon;
public string nameactive;
public string nameWeapon;
public int question;

public static string getActiveWeapon () //LABEL1
{
    if (activeGun.activeSelf) {
        return "Gun";
    }
    if (activeMelee.activeSelf) {
        return "Melee";
    }
    if (activeBottle.activeSelf) {
        return "Bottle";
    }
    if (activePistol.activeSelf) {
        return "Pistol";
    }
    return "empty";
}

public static bool ifThereIsSomethingInHand ()//LABEL2
{
    if (activeMelee.activeSelf || activeGun.activeSelf || activeBottle.activeSelf || activePistol.activeSelf)
        return true;
    else
        return false;
}
void Start ()
{ //LABEL3
    activeMelee = _activeMelee;
    activeGun = _activeGun;
    activeBottle = _activeBottle;
    activePistol = _activePistol;
    activeBottle.SetActive (false);
    activeMelee.SetActive (false);
    activeGun.SetActive (false);
    activePistol.SetActive (false);
    offset = new Vector3 (0f, 0.9f, -0.5f);
    mightDoNextTurn = false;
    speed = 2;
    timeWhileFlying = 2;
    activeId = 26;
}

void Update ()
{
    ifThereIsSmthInHand = ifThereIsSomethingInHand ();
    nameOfActive = getActiveWeapon ();
    if (ifThereIsSmthInHand) {
        if (mightDoNextTurn)
            ChangeWeapon ();
        else
            actionDrop ();
    } else if (mightDoNextTurn)
        actionPick ();
    nameactive = nameOfActive;
    nameWeapon = nameOfWeapon;
    question = activeQuestion;
}

private void actionDrop () //LABEL4
{
    if (currentAmmo == 0 && nameOfActive == "Gun") {
        activeGun.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        arrayOfValues [activeId] = 0;
        DropPos ();
        activeId = 26;
    }
    if (currentAmmo == 0 && nameOfActive == "Pistol") {
        activePistol.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        arrayOfValues [activeId] = 0;
        DropPos ();
        activeId = 26;
    }
}

public void deathDrop ()
{
    arrayOfObjects [activeId].SetActive (true);
    DropPos ();
}

private void actionPick ()//LABEL5
{
    switch (nameOfWeapon) {
    case "FireWeapon":
        activeGun.SetActive (true);
        break;
    case "MeleeWeapon":
        activeMelee.SetActive (true);
        break;
    case "BottleWeapon":
        activeBottle.SetActive (true);
        break;
    case "PistolWeapon":
        activePistol.SetActive (true);
        break;
    default:
        break;
    }
    arrayOfObjects [activeQuestion].SetActive (false);
    activeId = activeQuestion;
    mightDoNextTurn = false;
}

private void DropPos ()
{
    arrayOfObjects [activeId].transform.position = enemy.transform.position - offset;
    arrayOfObjects [activeId].transform.rotation = enemy.transform.rotation;
}

private void ChangeWeapon ()//LABEL6
{
    if (arrayOfValues [activeQuestion] > arrayOfValues [activeId]) {
        if (activeMelee.activeSelf)
            currentChange = activeMelee;
        if (activeGun.activeSelf)
            currentChange = activeGun;
        if (activeBottle.activeSelf)
            currentChange = activeBottle;
        if (activePistol.activeSelf)
            currentChange = activePistol;
        currentChange.SetActive (false);
        arrayOfObjects [activeId].SetActive (true);
        DropPos ();
        activeId = 26;
        arrayOfObjects [activeQuestion].SetActive (false);
        activeId = activeQuestion;
        mightDoNextTurn = false;
        if (nameOfWeapon == "BottleWeapon") {
            activeBottle.SetActive (true);
        }
        if (nameOfWeapon == "MeleeWeapon") {
            activeMelee.SetActive (true);
        }
        if (nameOfWeapon == "FireWeapon") {
            activeGun.SetActive (true);
        }
        if (nameOfWeapon == "PistolWeapon") {
            activePistol.SetActive (true);
        }
    }
}

void OnTriggerEnter (Collider other)//LABEL7
{
    if (other.gameObject.tag == "Weapon") {
        groundWeapon = other.gameObject;
        activeQuestion = other.gameObject.GetComponent<IdOfWeapon> ().localId;
        if (arrayOfValues [activeQuestion] == 0)
            activeQuestion = 26;
        if (activeQuestion >= 0 && activeQuestion <= 1000 && activeQuestion != 26) {
            if (activeQuestion < 31) {
                nameOfWeapon = "MeleeWeapon";
            }
            if (activeQuestion < 61 && activeQuestion >= 31) {
                nameOfWeapon = "BottleWeapon";
            }
            if (activeQuestion >= 61 && activeQuestion < 91) {
                nameOfWeapon = "FireWeapon";
            }
            if (activeQuestion >= 121 && activeQuestion < 151) {
                nameOfWeapon = "PistolWeapon";
            }
        }
        mightDoNextTurn = true;
    }
}

void OnTriggerStay (Collider other)//LABEL8
{
    if (other.gameObject.tag == "Weapon") {
        groundWeapon = other.gameObject;
        activeQuestion = other.gameObject.GetComponent<IdOfWeapon> ().localId;
        if (arrayOfValues [activeQuestion] == 0)
            activeQuestion = 26;
        if (activeQuestion >= 0 && activeQuestion <= 1000 && activeQuestion != 26) {
            if (activeQuestion < 31) {
                nameOfWeapon = "MeleeWeapon";
            }
            if (activeQuestion < 61 && activeQuestion >= 31) {
                nameOfWeapon = "BottleWeapon";
            }
            if (activeQuestion >= 61 && activeQuestion < 91) {
                nameOfWeapon = "FireWeapon";
            }
            if (activeQuestion >= 121 && activeQuestion < 151) {
                nameOfWeapon = "PistolWeapon";
            }
        }
        mightDoNextTurn = true;
    }
}
void OnTriggerExit (Collider other)
{
    if (other.gameObject.tag == "Weapon") {
        mightDoNextTurn = false;
        nameOfWeapon = "";
    }
    activeQuestion = 26;
    }
}

Note: enemy is allowed to drop a weapon for only two reasons: currentAmmo is equal to 0 or if he meets a better one (based on value).


来源: stackexchange

问:
How to create chat functionality same as linkedIn using signalR
I need to create chat functionality (same as linkedIn messaging) in DNN. How to do that in DNN(C#)?</p>

答:
There is a blog post here. http://www.dnnsoftware.com/community-blog/cid/151246/using-signalr-with-dotnetnuke-modules

Older article but still should be relevant.

ContentLicense: CC BY-SA 3.0


问:
simple flexbox grid overflow fit to row height
I have a very simple grid using flexbox where I want to display multi-line data in a scrollable box. I might be missing a trivial property but the row height doesn't appear to adjust itself properly to the height of it's content.

An example: https://plnkr.co/edit/rCXfvd4Vsh8RgoFja89A?p=preview

.grid {
  display: flex;
  flex-flow: column;
  max-height: 400px;
  overflow-y: auto;
}

.grid .header {
  font-weight: 700;
  margin-bottom: 6px;
  border-bottom: 3px solid black;
}

.grid .row {
  flex: 1;
  display: flex;
  flex-flow: row;
}

.grid .row:nth-child(even) {
  background: #CCC;
}

.grid .col-1 {
  flex: 0 0 60px;
}

.grid .col-2 {
  flex: 1 0 200px;
  white-space: pre;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Flexbox grid</h1>

<h3>Overflow example</h3>

<div class="grid">
  <div class="row header">
    <div class="col-1">Col 1</div>
    <div class="col-2">Col 2</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">One Line</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">One Line</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
</div>

<h3>No overflow example</h3>

<div class="grid">
  <div class="row header">
    <div class="col-1">Col 1</div>
    <div class="col-2">Col 2</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
</div></code>```

To keep everything simple I my columns are fixed size and all the data I want to display is loaded into the grid (instead of using a virtual grid). Is there a way to fix my example so that the rows adjust itself to the content?

EDIT: SOLVED!

As user @bhv pointed out I should have disabled shrink on .row by applying flex: 1 0 auto instead of flex+:1 (1 auto).

.grid {
  display: flex;
  flex-flow: column;
  max-height: 400px;
  overflow-y: auto;
}

.grid .header {
  font-weight: 700;
  margin-bottom: 6px;
  border-bottom: 3px solid black;
}

.grid .row {
  flex: 1;
  display: flex;
  flex-flow: row;
  flex-shrink: 0;
}

.grid .row:nth-child(even) {
  background: #CCC;
}

.grid .col-1 {
  flex: 0 0 60px;
}

.grid .col-2 {
  flex: 1 0 200px;
  white-space: pre;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Flexbox grid</h1>

<h3>Overflow example</h3>

<div class="grid">
  <div class="row header">
    <div class="col-1">Col 1</div>
    <div class="col-2">Col 2</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">One Line</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">One Line</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
</div>

<h3>No overflow example</h3>

<div class="grid">
  <div class="row header">
    <div class="col-1">Col 1</div>
    <div class="col-2">Col 2</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
  <div class="row body">
    <div class="col-1">DATA</div>
    <div class="col-2">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled</div>
  </div>
</div></code>```

https://plnkr.co/edit/jIoaME?p=preview

答:
Since the total height of your items is higher than their parents max-height, and since the flex-shrink defaults to 1, they will shrink as much as possible to fit.

So by simply change flex-shrink to 0 will prevent that.

Also the flex: 1 cause another change of the defaults, where the flex-basis is set to 0, which will make the items share the space left equally, instead of the default auto, which takes their content into account before the remaining space is calculated.

In your case though, where the parent has no height (and flex-direction: column), flex: 1 has no effect and can be deleted.

Body:
I have a very simple grid using flexbox where I want to display multi-line data in a scrollable box. I might be missing a trivial property but the row height doesn't appear to adjust itself properly to the height of it's content.

An example: https://plnkr.co/edit/rCXfvd4Vsh8RgoFja89A?p=preview

.grid {
  display: flex;
  flex-flow: column;
  max-height: 400px;
  overflow-y: auto;
}

.grid .header {
  font-weight: 700;
  margin-bottom: 6px;
  border-bottom: 3px solid black;
}

.grid .row {
  flex: 1;
  display: flex;
  flex-flow: row;
}

.grid .row:nth-child(even) {
  background: #CCC;
}

.grid .col-1 {
  flex: 0 0 60px;
}

.grid .col-2 {
  flex: 1 0 200px;
  white-space: pre;
}

Flexbox grid

Overflow example

Col 1

Col 2

DATA

One Line

DATA

One Line

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

No overflow example

Col 1

Col 2

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

To keep everything simple I my columns are fixed size and all the data I want to display is loaded into the grid (instead of using a virtual grid). Is there a way to fix my example so that the rows adjust itself to the content?

EDIT: SOLVED!

As user @bhv pointed out I should have disabled shrink on .row by applying flex: 1 0 auto instead of flex+:1 (1 auto).

.grid {
  display: flex;
  flex-flow: column;
  max-height: 400px;
  overflow-y: auto;
}

.grid .header {
  font-weight: 700;
  margin-bottom: 6px;
  border-bottom: 3px solid black;
}

.grid .row {
  flex: 1;
  display: flex;
  flex-flow: row;
  flex-shrink: 0;
}

.grid .row:nth-child(even) {
  background: #CCC;
}

.grid .col-1 {
  flex: 0 0 60px;
}

.grid .col-2 {
  flex: 1 0 200px;
  white-space: pre;
}

Flexbox grid

Overflow example

Col 1

Col 2

DATA

One Line

DATA

One Line

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

No overflow example

Col 1

Col 2

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

DATA

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled

https://plnkr.co/edit/jIoaME?p=preview


问:
How to prevent default sorting in key value array Javascript
I have this array:

recentPageArray = {
  "e49f8a67-3075-433a-bacd-30379008fdb2": {
    "id": "e49f8a67-3075-433a-bacd-30379008fdb2",
    "name": "afolder",
    "type": "indexfolder"
  },
  "3a1ca419-5467-4662-9f7a-f3e9246a1d49": {
    "id": "3a1ca419-5467-4662-9f7a-f3e9246a1d49",
    "name": "folder1",
    "type": "indexfolder"
  },
  "832f9d4e-297e-40e9-9189-75ce3b86341a": {
    "id": "832f9d4e-297e-40e9-9189-75ce3b86341a",
    "name": "afolder",
    "type": "documentfolder"
  },
  "86fee1ce-21cd-4948-bf9d-a6c81b897a0e": {
    "id": "86fee1ce-21cd-4948-bf9d-a6c81b897a0e",
    "name": "afolder",
    "type": "documentfolder"
  }
}
```

Whenever I push new array in the this array. Key sort automatically. I dont want to sort array in the key base. I need new pushed key item in top of the array.

答:
I suggest you to mantain 2 references:
1 Array (list)
1 Object (key, value)

The Object (key->val) cannot mantain the elements' insert order (and if an utopic new browser implementation want to order in descending order(for any cause) your code will be sensible to it).

So, while populating the object,also push the element key in the Array.
When you want to iterate use the Array to iterate in order (and it is also faster)

```<code>myObject = {};
myArray = [];
/** POPULATING **/
for (var x in myData){
   myObject[myData[x].key] = myData[x].value;
   myArray.push(myData[x].key);

}
/** ITERATING **/
for (var y =0; y < myArray.length; y++){
   var readingKey = myArray[y];
   var storedData = myObject[readingKey];
   //your code here
}
</code>```

Regards

Body:
I have this array:

recentPageArray = {
  "e49f8a67-3075-433a-bacd-30379008fdb2": {
    "id": "e49f8a67-3075-433a-bacd-30379008fdb2",
    "name": "afolder",
    "type": "indexfolder"
  },
  "3a1ca419-5467-4662-9f7a-f3e9246a1d49": {
    "id": "3a1ca419-5467-4662-9f7a-f3e9246a1d49",
    "name": "folder1",
    "type": "indexfolder"
  },
  "832f9d4e-297e-40e9-9189-75ce3b86341a": {
    "id": "832f9d4e-297e-40e9-9189-75ce3b86341a",
    "name": "afolder",
    "type": "documentfolder"
  },
  "86fee1ce-21cd-4948-bf9d-a6c81b897a0e": {
    "id": "86fee1ce-21cd-4948-bf9d-a6c81b897a0e",
    "name": "afolder",
    "type": "documentfolder"
  }
}

Whenever I push new array in the this array. Key sort automatically. I dont want to sort array in the key base. I need new pushed key item in top of the array.

Body:
I suggest you to mantain 2 references:
1 Array (list)
1 Object (key, value)

The Object (key->val) cannot mantain the elements' insert order (and if an utopic new browser implementation want to order in descending order(for any cause) your code will be sensible to it).

So, while populating the object,also push the element key in the Array.
When you want to iterate use the Array to iterate in order (and it is also faster)

myObject = {};
myArray = [];
/** POPULATING **/
for (var x in myData){
   myObject[myData[x].key] = myData[x].value;
   myArray.push(myData[x].key);

}
/** ITERATING **/
for (var y =0; y < myArray.length; y++){
   var readingKey = myArray[y];
   var storedData = myObject[readingKey];
   //your code here
}

Regards


问:
HTML as a server-side programming language
I was reading a Wikipedia article when I came accross this page.

Can anyone explain to me the meaning of HTML used as a server-side programming language?

答:
Looks like the information was incorrectly taken from This blog post (it's the reference on the wiki page you linked)

The image on the blog that relates to server-side programming languages is this: http://blog.stoneriverelearning.com/wp-content/uploads/2015/11/blog3.jpg

Looks like whoever transcribed the information confused "Ruby and others" with "HTML" somehow.

All in all this is a good demonstration of why wikipedia isn't a flawless resource.


问:
Overflow in div tag
I have a div tag with fixed width. Now i want that if there is a condition of overflow then text should go to next line automatically. I used overflow:auto but its giving a horizontal scroll bar. There should not be any scroll bar, text should go to next line.

Any idea how to do it with css???

答:
If you want a scrollbar to appear for when text fills more than the height of a div, you can try:

overflow-y:auto

You might also need word-wrap or white-space css attributes?

ContentLicense: CC BY-SA 2.5

Title: Overflow in div tag


问:
Issue loading-data-from-multiple-db-to-another-server-using-ssis
I am facing issue in loading-data-from-multiple-db-to-another-server-using-ssis
I have referred the below link
Loading data from multiple db to another server using SSIS

SSIS Package FLow :

Unfortunately i am getting the error in "Execute SQL Task" as below:

[Execute SQL Task] Error: There is an invalid number of result
  bindings returned for the ResultSetType: "ResultSetType_Rowset".

Appreciate if you could help me with the solutions.
Thanks

答:
You have 2 Execute SQL Tasks

1, First Execute SQL Task, get list of tables and schema, it expects a Full Result set and map it to a object type variable.

2, Foreach loop container,  ADO Enumerator, ADO source is the object type variable. Variable Mappings to 2 string type variables, 1 is for table name and 1 is for schema name.

Second Execute SQL Task, it has no Full Result set, no parameter mapping. Because table name/schema name changes are taken care of by Foreach loop container.


问:
How to extract the elements of an Array[String] in Scala?
Suppose we have an Array:

```<code>val arr = Array("Id:1; Apple; Red; 2; Out",
                "Id:2; Banana; Yellow; 5",
                "Id:3; Peach; Red; 3",
                "Id:4; Grape; Green; 5; Out")
</code>```

I want to apply a function on each element of the array, which extracts the fruit type and the number and returns a Map. The output in this case would be:

```<code>(Apple, 2)
(Banana, 5)
(Peach, 3)
(Grape, 5)
</code>```

I tried:

```<code>val pairMap = arr.foreach(r => r.split(";")(1) zip r.split(";")(3))
</code>```

but I always obtain Unit

答:
You actually have two errors in your code.

First as pointed out already you are using foreach (which returns Unit) instead of map (which returns an Object).

Second, you are using zip in your foreach function, which combines two collections pair wise, like this:

```<code>val arr1 = Seq("Apple", "Peach", "Banana")
val arr2 = Seq("Red", "Red", "Yellow")

val arr3 = arr1 zip arr2 // = Seq(("Apple", "Red"), ("Peach", "Red"), ("Banana", "Yellow"))
</code>```

Your code should look like this:

```<code>val arr = Array("Id:1; Apple; Red; 2; Out",
  "Id:2; Banana; Yellow; 5",
  "Id:3; Peach; Red; 3",
  "Id:4; Grape; Green; 5; Out")

arr.map(r => (r.split(";")(1), r.split(";")(3)))
</code>```

Or to be a tiny bit more efficient, by splitting only once:

```<code>arr.map { r =>
  val t = r.split(";")
  (t(1), t(2))
}
</code>```

And you probably don't want the white spaces, so:

```<code>arr.map { r =>
  val t = r.split(";")
  (t(1).trim(), t(2).trim())
}
</code>```

Just adding this because I think regex is also a good option for string processing and a neat feature together with scala's pattern match:

```<code>val regEx = "[^;]+; ([^;]+); [^;]+; ([^;]+).*".r

arr collect {
  case regEx(fruit, number) => (fruit, number)
}
</code>```

Also leads to the desired output, but might be a bit overkill for this simple use case.

Body:
Suppose we have an Array:

val arr = Array("Id:1; Apple; Red; 2; Out",
                "Id:2; Banana; Yellow; 5",
                "Id:3; Peach; Red; 3",
                "Id:4; Grape; Green; 5; Out")

I want to apply a function on each element of the array, which extracts the fruit type and the number and returns a Map. The output in this case would be:

(Apple, 2)
(Banana, 5)
(Peach, 3)
(Grape, 5)

I tried:

val pairMap = arr.foreach(r => r.split(";")(1) zip r.split(";")(3))

but I always obtain Unit

Body:
You actually have two errors in your code.

First as pointed out already you are using foreach (which returns Unit) instead of map (which returns an Object).

Second, you are using zip in your foreach function, which combines two collections pair wise, like this:

val arr1 = Seq("Apple", "Peach", "Banana")
val arr2 = Seq("Red", "Red", "Yellow")

val arr3 = arr1 zip arr2 // = Seq(("Apple", "Red"), ("Peach", "Red"), ("Banana", "Yellow"))

Your code should look like this:

val arr = Array("Id:1; Apple; Red; 2; Out",
  "Id:2; Banana; Yellow; 5",
  "Id:3; Peach; Red; 3",
  "Id:4; Grape; Green; 5; Out")

arr.map(r => (r.split(";")(1), r.split(";")(3)))

Or to be a tiny bit more efficient, by splitting only once:

arr.map { r =>
  val t = r.split(";")
  (t(1), t(2))
}

And you probably don't want the white spaces, so:

arr.map { r =>
  val t = r.split(";")
  (t(1).trim(), t(2).trim())
}

Just adding this because I think regex is also a good option for string processing and a neat feature together with scala's pattern match:

val regEx = "[^;]+; ([^;]+); [^;]+; ([^;]+).*".r

arr collect {
  case regEx(fruit, number) => (fruit, number)
}

Also leads to the desired output, but might be a bit overkill for this simple use case.


问:
Approach to make a one line script into a one line command?
Below is my "one liner" in a script.

```<code>#!/usr/bin/ruby

puts ARGF.read.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx, yy|
  Regexp.last_match[0].gsub(/([^\\])#/,'\1\\#') }
</code>```

If I just insert in ruby -pe '' I get

```<code>-e:1: syntax error, unexpected $undefined, expecting ')'
...ast_match[0].gsub(/([^\\])#/,1\#) }
...                               ^
</code>```

With double quotes I get

```<code>-e:1: premature end of char-class: /([^\])#/
</code>```

Question

So the question is what is the approach to make it work in ruby -pe ''?

答:
Use %q|| instead of single quotes in your one-liner, it’s effectively the same but it won’t mess up with command line single quotes:

```<code>puts ARGF.read.gsub(RE1) { Regexp.last_match[0].gsub(/([^\\])#/,%q|\1\\#|) }
</code>```

Body:
Below is my "one liner" in a script.

#!/usr/bin/ruby

puts ARGF.read.gsub(/\\caption\{((?:[^{}]+|\{\g<1>\})+)\}/m) { |xx, yy|
  Regexp.last_match[0].gsub(/([^\\])#/,'\1\\#') }

If I just insert in ruby -pe '' I get

-e:1: syntax error, unexpected $undefined, expecting ')'
...ast_match[0].gsub(/([^\\])#/,1\#) }
...                               ^

With double quotes I get

-e:1: premature end of char-class: /([^\])#/

Question

So the question is what is the approach to make it work in ruby -pe ''?

Body:
Use %q|| instead of single quotes in your one-liner, it’s effectively the same but it won’t mess up with command line single quotes:

puts ARGF.read.gsub(RE1) { Regexp.last_match[0].gsub(/([^\\])#/,%q|\1\\#|) }


问:
sidebar appearing under content of wordpress
Every time I add a new page either through wordpress and or the new woocommerce pages I have due to installing the woocommerce plugin are all pushing the sidebar to the bottom of the page under the content.

I have no idea why this is happening. Please check attached photo

This is what the code looks like in my themes sidebar in the CSS

```<code>/* Sidebar
---------------------------------------- */
#sidebar {
    float: Left;
}

    .widget {
        background: url(images/box-tail.gif) repeat-x 50% 0%;
        position: relative;
        margin: 0 0 30px 0;
        border: 1px solid #f0f0f0;
        border-top: none;
        border-radius: 4px;
        -moz-border-radius: 4px;
        -webkit-border-radius: 4px;
    }

        ul.children {
            margin: 0 0 0 20px;
        }

    .widget-indent {
        padding: 0 20px 19px 20px;
    }

.primary_content_wrap .widget {
    padding: 0 19px 19px 19px;
}

.primary_content_wrap h3 {
    padding: 0 0 21px 0;
}

.primary_content_wrap .widget #searchform {
    width: 100%;
}

    .primary_content_wrap .widget #searchform input[type="text"] {
        width: 123px;
    }
</code>```

This is my sidebar.php

```<code><aside id="sidebar" class="grid_6 omega">
    <?php if ( ! dynamic_sidebar( 'Sidebar' )) : ?>

        <div id="sidebar-search" class="widget">
            <h3>Search</h3>
            <?php get_search_form(); ?> <!-- outputs the default Wordpress search form-->
        </div>

        <div id="sidebar-nav" class="widget menu">
            <h3>Navigation</h3>
            <?php wp_nav_menu( array('menu' => 'Sidebar Menu' )); ?> <!-- editable within the Wordpress backend -->
        </div>

        <div id="sidebar-archives" class="widget">
            <h3>Archives</h3>
            <ul>
                <?php wp_get_archives( 'type=monthly' ); ?>
            </ul>
        </div>

        <div id="sidebar-meta" class="widget">
            <h3>Meta</h3>
            <ul>
                <?php wp_register(); ?>
                <li><?php wp_loginout(); ?></li>
                <?php wp_meta(); ?>
            </ul>
        </div>

    <?php endif; ?>
</aside><!--sidebar-->
</code>```

And then this is how I call the sidebar in each of my pages

```<code><?php get_sidebar(); ?>
</code>```

any help would be greatly appreciated.

UPDATE
Appearance>widgets

答: When the main content and sidebar have sizes assigned to them that don’t fit next to one another or too much margin or padding, the sidebar will automatically move to the bottom of the screen. this may cause problem </p>

Body:
Every time I add a new page either through wordpress and or the new woocommerce pages I have due to installing the woocommerce plugin are all pushing the sidebar to the bottom of the page under the content.

I have no idea why this is happening. Please check attached photo

This is what the code looks like in my themes sidebar in the CSS

/* Sidebar
---------------------------------------- */
#sidebar {
    float: Left;
}

    .widget {
        background: url(images/box-tail.gif) repeat-x 50% 0%;
        position: relative;
        margin: 0 0 30px 0;
        border: 1px solid #f0f0f0;
        border-top: none;
        border-radius: 4px;
        -moz-border-radius: 4px;
        -webkit-border-radius: 4px;
    }

        ul.children {
            margin: 0 0 0 20px;
        }

    .widget-indent {
        padding: 0 20px 19px 20px;
    }

.primary_content_wrap .widget {
    padding: 0 19px 19px 19px;
}

.primary_content_wrap h3 {
    padding: 0 0 21px 0;
}

.primary_content_wrap .widget #searchform {
    width: 100%;
}

    .primary_content_wrap .widget #searchform input[type="text"] {
        width: 123px;
    }

This is my sidebar.php

    <?php if ( ! dynamic_sidebar( 'Sidebar' )) : ?>

Search

            <?php get_search_form(); ?>

Navigation

            <?php wp_nav_menu( array('menu' => 'Sidebar Menu' )); ?>

Archives

                <?php wp_get_archives( 'type=monthly' ); ?>

Meta

                <?php wp_register(); ?>

<?php wp_loginout(); ?>

                <?php wp_meta(); ?>

    <?php endif; ?>

And then this is how I call the sidebar in each of my pages

<?php get_sidebar(); ?>

any help would be greatly appreciated.

UPDATE
Appearance>widgets


问:
JQuery create a form and add elements to it programmatically
Hi I need to create a form and add elements to it programatically.

```<code>$form = $("<form></form>");
$form.append("<input type=button value=button");
</code>```

this doesn't seem to work right.

答:
The 2nd line should be written as:</p>

```<code>$form.append('<input type="button" value="button">');
</code>```

Body:
Hi I need to create a form and add elements to it programatically.

$form = $("<form></form>");
$form.append("<input type=button value=button");

this doesn't seem to work right.

Body:
The 2nd line should be written as:

$form.append('<input type="button" value="button">');


问:
How to center ImageView in a toolbar?
Been trying to center a logo inside my toolbar. When i navigate to the next activity, the "up affordance" icon is present, and it will push my logo slightly to the right. How can I keep my logo at the center of the toolbar, without removing the up affordance icon?

This is my toolbar tag

```<code><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/CustomToolBarTheme">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_android_logo"
    android:layout_gravity="center"
    android:paddingBottom="3dp"/>
 </android.support.v7.widget.Toolbar>
</code>```

答:
I am bit late to answer this , but have wonderful solution

```<code> <android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:contentInsetStart="0dp"
        app:contentInsetEnd="0dp"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <RelativeLayout
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="?attr/actionBarSize"
            android:contentDescription="@string/app_name"
            android:id="@+id/logoImageView"
            android:layout_centerInParent="true"
            android:adjustViewBounds="true"
            android:src="@drawable/toolbar_background" />
    </RelativeLayout>
</FrameLayout>

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

and here is my toolbar_background.xml drawable

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/colorPrimary" />
    </shape>
</item>
<item>
    <bitmap
        android:src="@drawable/splash" android:gravity="center"
        />
</item>
</code>```

Title: How to center ImageView in a toolbar?

Body:
Been trying to center a logo inside my toolbar. When i navigate to the next activity, the "up affordance" icon is present, and it will push my logo slightly to the right. How can I keep my logo at the center of the toolbar, without removing the up affordance icon?

This is my toolbar tag

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/CustomToolBarTheme">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_android_logo"
    android:layout_gravity="center"
    android:paddingBottom="3dp"/>
 </android.support.v7.widget.Toolbar>

Body:
I am bit late to answer this , but have wonderful solution

 <android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:contentInsetStart="0dp"
        app:contentInsetEnd="0dp"
        app:popupTheme="@style/AppTheme.PopupOverlay">

    </android.support.v7.widget.Toolbar>
    <RelativeLayout
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="?attr/actionBarSize"
            android:contentDescription="@string/app_name"
            android:id="@+id/logoImageView"
            android:layout_centerInParent="true"
            android:adjustViewBounds="true"
            android:src="@drawable/toolbar_background" />
    </RelativeLayout>
</FrameLayout>

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

and here is my toolbar_background.xml drawable

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@color/colorPrimary" />
    </shape>
</item>
<item>
    <bitmap
        android:src="@drawable/splash" android:gravity="center"
        />
</item>


问:
Why jQuery mobile style not applied when table created dynamically
I use jQuery mobile 1.4.5 in my project.

I create dynamically table with buttons by click. When table created the JQM style isn't apply.

Here is my HTML code:

```<code><div data-role="page" id="page1">
    <div data-role="header">
         <h1>My page</h1>
    </div>
    <div data-role="content" class="ui-content">
    <button onclick="CretaeTable()">Cretate table</button>
     <div id="vectorLayerslist"></div>
</div>
</code>```

Here is JavaScript code:

```<code>function CretaeTable(){
    var vectorLayersList = $('#vectorLayerslist');
    var arr  = [{id:'124',Title:'qqq'},
               {id:'589',Title:'www'},
               {id:'45',Title:'eee'},
               {id:'567',Title:'rrr'}]

    var table = layersListTable(arr);
     vectorLayersList.append(table);
}

function layersListTable(layers) {
    // build the table
    var frame = '<fieldset style="border: solid 1px #6b6b6b;">';
    var smallHeader = '<legend>title</legend>';
    var content = frame + smallHeader + '<table data-role="table" id="layersListEditable" data-mode="columntoggle:none" class="ui-responsive"><thead><tr></tr></thead>';
    $.each($(layers), function () {
        // we'll store the ID in HTML5 data-attribute for later
        content += '<tr>';
        // give classes to your buttons for later
        content += '<td><button data-mini="true" data-inline="true" data-icon="edit" data-theme="b" type="button" class="edit">Edit</button></td>';
        content += '<td><button data-mini="true" data-inline="true" data-icon="delete" data-theme="b" type="button" class="delete">Delete</button></td>';
        content += '<td style="vertical-align: inherit;">' + this.Title + '</td>';
        content += '</tr>';
    });
    content += '</table>';
    content += '</fieldset>'

    return content;
}
</code>```

Here is JSFIDDLE.

Why JQM style isn't apply?

答:
You jist only need to rebuild the table, and then maybe update the layout of the whole page content:

```<code> ... your dynamic table creation
 vectorLayersList.append(table);
 // add this:
 $("#layersListEditable").table().table("rebuild");
 $(".ui-content").trigger("updatelayout");
</code>```

Please, note:  you may also adjust the button markup, something like this:

```<code>content += '<td><button class="ui-btn ui-mini ui-btn-inline ui-btn-icon-left ui-icon-edit">Edit</button></td>';
content += '<td><button class="ui-btn ui-mini ui-btn-inline ui-btn-icon-left ui-icon-delete">Delete</button></td>';
</code>```

Here is your updated Fiddle: http://jsfiddle.net/aJUy8/105/

Body:
I use jQuery mobile 1.4.5 in my project.

I create dynamically table with buttons by click. When table created the JQM style isn't apply.

Here is my HTML code:

My page

    <button onclick="CretaeTable()">Cretate table</button>

Here is JavaScript code:

function CretaeTable(){
    var vectorLayersList = $('#vectorLayerslist');
    var arr  = [{id:'124',Title:'qqq'},
               {id:'589',Title:'www'},
               {id:'45',Title:'eee'},
               {id:'567',Title:'rrr'}]

    var table = layersListTable(arr);
     vectorLayersList.append(table);
}

function layersListTable(layers) {
    // build the table
    var frame = '<fieldset style="border: solid 1px #6b6b6b;">';
    var smallHeader = '<legend>title</legend>';
    var content = frame + smallHeader + '

';
    $.each($(layers), function () {
        // we'll store the ID in HTML5 data-attribute for later
        content += '
';
        // give classes to your buttons for later
        content += '<button data-mini="true" data-inline="true" data-icon="edit" data-theme="b" type="button" class="edit">Edit</button>	';
        content += '<button data-mini="true" data-inline="true" data-icon="delete" data-theme="b" type="button" class="delete">Delete</button>	';
        content += '' + this.Title + '	';
        content += '
';
    });
    content += '
';
    content += '</fieldset>'

    return content;
}

Here is JSFIDDLE.

Why JQM style isn't apply?

Body:
You jist only need to rebuild the table, and then maybe update the layout of the whole page content:

 ... your dynamic table creation
 vectorLayersList.append(table);
 // add this:
 $("#layersListEditable").table().table("rebuild");
 $(".ui-content").trigger("updatelayout");

Please, note:  you may also adjust the button markup, something like this:

content += '<td><button class="ui-btn ui-mini ui-btn-inline ui-btn-icon-left ui-icon-edit">Edit</button></td>';
content += '<td><button class="ui-btn ui-mini ui-btn-inline ui-btn-icon-left ui-icon-delete">Delete</button></td>';

Here is your updated Fiddle: http://jsfiddle.net/aJUy8/105/


问:
Retrieve Node-Red flows
I had my Node-Red running as windows service with the help of daemon tool. Unfortunately it stopped working. Not sure why. I have created some flows which I wish to retrieve from the node-red so that, I can re-install node-red again from scratch and use the flows that i have created already. Could anyone help me where the flows are actually stored and the configurations, packages installed details?
Any help on this is highly appreciated.</p>

答:
The flows will be stored in the .node-red in the profile directory of the user running node-red.

The default directory is c:\Users\[username]\.node-red

The flow will be made up of 2 files:

flows_[hostname].json

flows_[hostname]_creds.json

The first is the actual flow, the second is where any username/passwords used by the flow is kept. This second file is normally encrypted with a key generated the first time node-red is run. The key is stored in the .config.json in the same directory.

Title: Retrieve Node-Red flows


问:
Getting another element through a method thats related to the current operation
Sorry for the bad title, simple couldn't figure out how to explain my problem.

Let's say i have 4 of these fields, and not just one. I want to increment or decrement each input field. Each input field has a "+" and "-" that does incremental and decremental tasks.

I have setup a method that register the v-on click even to a method. But how do i get what input field it was incremented on, cause 'this' would return the buttons of +/-

normally i would just use jquery with .parent().find('.input-number'); but i feel like this is dirty, and excessive for such a small thing. most be a better approach?

This is my markup

```<code>      <div class="form-group">
        <span class="input-number-decrement" v-on:click="decrement()">–</span>
        <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
        <span class="input-number-increment" v-on:click="increment()">+</span>
      </div>
</code>```

and looks like this
example of the field

any help would great, since i'm stuck at this part :)

答:
I have created one javascript function for increment and decrement value by 1.

HTML

```<code><div class="form-group">
    <span class="input-number-decrement" v-on:click="inc_dec('dec')">-</span>
    <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
    <span class="input-number-increment" v-on:click="inc_dec('inc')">+</span>
</div>
</code>```

Javascript

```<code><script type="text/javascript">
    function inc_dec(flag){
        var pack1 = document.getElementById('pack1');
        var inc_dec_by = 1;
        if(flag=='inc'){
            pack1.value = parseInt(pack1.value)+inc_dec_by;
        }
        if(flag=='dec'){
            pack1.value = parseInt(pack1.value)-inc_dec_by;
        }
    }
</script>
</code>```

Body:
Sorry for the bad title, simple couldn't figure out how to explain my problem.

Let's say i have 4 of these fields, and not just one. I want to increment or decrement each input field. Each input field has a "+" and "-" that does incremental and decremental tasks.

I have setup a method that register the v-on click even to a method. But how do i get what input field it was incremented on, cause 'this' would return the buttons of +/-

normally i would just use jquery with .parent().find('.input-number'); but i feel like this is dirty, and excessive for such a small thing. most be a better approach?

This is my markup

        –
        <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
        +

and looks like this
example of the field

any help would great, since i'm stuck at this part :)

Body:
I have created one javascript function for increment and decrement value by 1.

HTML

<div class="form-group">
    <span class="input-number-decrement" v-on:click="inc_dec('dec')">-</span>
    <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
    <span class="input-number-increment" v-on:click="inc_dec('inc')">+</span>
</div>

Javascript

<script type="text/javascript">
    function inc_dec(flag){
        var pack1 = document.getElementById('pack1');
        var inc_dec_by = 1;
        if(flag=='inc'){
            pack1.value = parseInt(pack1.value)+inc_dec_by;
        }
        if(flag=='dec'){
            pack1.value = parseInt(pack1.value)-inc_dec_by;
        }
    }
</script>


问:
Multiple port scans using external tool, subprocess.Popen and threads
I am using a port scanner to scan my subnet. The port scanner unfortunately can scan one port of only one host at a time. Also the scanner has a 1 sec timeout for unreachable hosts. The scanner(being an outside program) has to be run from subprocess.Popen() and to speed it up - so that I may send multiple probes while some previous ones are waiting for replies- I use threads. The problem comes up for a complete /24 subnet scan with large number of threads. SOme of the actually open ports are displayed as closed. I suspect somehow the output gets garbled. Note that this does not occur if I scan fewer hosts or one host at a time

The following code is my attempt to create a pool of threads which take an IP address and run 'sequential' port scan for defined port. Once all specified ports are scanned, it picks up next IP from the list.

```<code>        while True:
            if not thread_queue.empty():
                try:
                    hst = ip_iter.next()
                except StopIteration:
                    break
                m=thread_queue.get()
                l=ThreadWork(self,hst,m)
                l.start()
        while open_threads != 0:
            pass
</code>```

Where this fragment sets up thread queue

```<code>        thread_list = [x for x in range(num_threads)]
        for t in thread_list:
            thread_queue.put(str(t))
        ip_iter=iter(self.final_target)
</code>```

In the ThreadWork function I keep a tab of open threads(since thread_queue.empty proved to be unreliable, I had to use this crude way)

```<code>class ThreadWork(threading.Thread):
    def __init__(self,i,hst,thread_no):
        global open_threads
        threading.Thread.__init__(self)
        self.host = hst
        self.ptr = i
        self.t = thread_no
        lock.acquire()
        open_threads = open_threads + 1
        lock.release()

    def run(self):
        global thread_queue
        global open_threads
        global lock
        user_log.info("Executing sinfp for IP Address : %s"%self.host)
        self.ptr.result.append(SinFpRes(self.host,self.ptr.init_ports,self.ptr.all_ports,self.ptr.options,self.ptr.cf))
        lock.acquire()
        open_threads = open_threads - 1
        lock.release()
        thread_queue.put(self.t)
</code>```

The call to SinFpRes creates a result object for one IP and initiate sequential scanning of ports for that IP only.
The actual scan per port is as shown

```<code>        com_string = '/usr/local/sinfp/bin/sinfp.pl '+self.options+' -ai '+str(self.ip)+' -p '+str(p)
        args = shlex.split(com_string)
        self.result=subprocess.Popen(args,stdout=subprocess.PIPE).communicate()[0]
        self.parse(p)
</code>```

The parse function then utilises result  stored in self.result to store output for that PORT. An aggregate of all the ports is what constitues a scan result for an IP.

Calling this code using 10 threads gives accurate o/p (when compared to nmap output). On giving 15 threads an occasional open port is missed. On giving 20 threads, more open ports are missed. On giving 50 threads many ports are missed.

P.S. - As a first timer, this code is very convoluted. Apologies to the puritans.

P.P.S. - Even a threaded port scan takes 15 minutes for an entire class C subnet with hardly 20 ports scanned. I was wondering if I should move this code to another language and use Python to only parse the results. Could somebody suggest me a language?
Note -I am exploring Shell option as shown by S.Lott but manual processing is required before dumping it into file.

答: Use Perl instead of Python. The program (SinFP) is written in Perl, you can modify the code to suite your needs.</p>

Body:
I am using a port scanner to scan my subnet. The port scanner unfortunately can scan one port of only one host at a time. Also the scanner has a 1 sec timeout for unreachable hosts. The scanner(being an outside program) has to be run from subprocess.Popen() and to speed it up - so that I may send multiple probes while some previous ones are waiting for replies- I use threads. The problem comes up for a complete /24 subnet scan with large number of threads. SOme of the actually open ports are displayed as closed. I suspect somehow the output gets garbled. Note that this does not occur if I scan fewer hosts or one host at a time

The following code is my attempt to create a pool of threads which take an IP address and run 'sequential' port scan for defined port. Once all specified ports are scanned, it picks up next IP from the list.

        while True:
            if not thread_queue.empty():
                try:
                    hst = ip_iter.next()
                except StopIteration:
                    break
                m=thread_queue.get()
                l=ThreadWork(self,hst,m)
                l.start()
        while open_threads != 0:
            pass

Where this fragment sets up thread queue

        thread_list = [x for x in range(num_threads)]
        for t in thread_list:
            thread_queue.put(str(t))
        ip_iter=iter(self.final_target)

In the ThreadWork function I keep a tab of open threads(since thread_queue.empty proved to be unreliable, I had to use this crude way)

class ThreadWork(threading.Thread):
    def __init__(self,i,hst,thread_no):
        global open_threads
        threading.Thread.__init__(self)
        self.host = hst
        self.ptr = i
        self.t = thread_no
        lock.acquire()
        open_threads = open_threads + 1
        lock.release()

    def run(self):
        global thread_queue
        global open_threads
        global lock
        user_log.info("Executing sinfp for IP Address : %s"%self.host)
        self.ptr.result.append(SinFpRes(self.host,self.ptr.init_ports,self.ptr.all_ports,self.ptr.options,self.ptr.cf))
        lock.acquire()
        open_threads = open_threads - 1
        lock.release()
        thread_queue.put(self.t)

The call to SinFpRes creates a result object for one IP and initiate sequential scanning of ports for that IP only.
The actual scan per port is as shown

        com_string = '/usr/local/sinfp/bin/sinfp.pl '+self.options+' -ai '+str(self.ip)+' -p '+str(p)
        args = shlex.split(com_string)
        self.result=subprocess.Popen(args,stdout=subprocess.PIPE).communicate()[0]
        self.parse(p)

The parse function then utilises result  stored in self.result to store output for that PORT. An aggregate of all the ports is what constitues a scan result for an IP.

Calling this code using 10 threads gives accurate o/p (when compared to nmap output). On giving 15 threads an occasional open port is missed. On giving 20 threads, more open ports are missed. On giving 50 threads many ports are missed.

P.S. - As a first timer, this code is very convoluted. Apologies to the puritans.

P.P.S. - Even a threaded port scan takes 15 minutes for an entire class C subnet with hardly 20 ports scanned. I was wondering if I should move this code to another language and use Python to only parse the results. Could somebody suggest me a language?
Note -I am exploring Shell option as shown by S.Lott but manual processing is required before dumping it into file.


问:
Duplicate edges with same properties neo4j
I have two nodes between which, same edge with same property is being created over and over again. How can I avoid this? If the edges have different properties, its ok and it needs to be kept but if the properties are same, there should be one edge only.

EDIT: I'm using rails and I want to do this through application and not Cypher query.

EDIT: Sharing some code for relevance:

```<code>dis = Disease.where(disease: params[:disease]).first
fac = Factor.where(factor: params[:factor])
dis.factors.create(fac, prop: "p1")
</code>```

So, what I want is if I input same disease and factor, it not duplicate the edge (which it is currently doing) as property being set is also same. However, if in future, this p1 changes to p2, then the edge should be added.

Refer post Neo4j inconsistent behaviour of model classes for model classes (Disease and factor).

答:
You have two options.  You could use the unique option on your association(s):

http://neo4jrb.readthedocs.io/en/8.1.x/ActiveNode.html#creating-unique-relationships

This allows you to specify anything from there being only one of that relationship type between two nodes (regardless of properties), to only creating unique nodes if all properties are exactly the same.  If you create an ActiveRel model, you can also do the same thing with the creates_unique declaration:

http://neo4jrb.readthedocs.io/en/8.1.x/ActiveRel.html#creating-unique-relationships

Body:
I have two nodes between which, same edge with same property is being created over and over again. How can I avoid this? If the edges have different properties, its ok and it needs to be kept but if the properties are same, there should be one edge only.

EDIT: I'm using rails and I want to do this through application and not Cypher query.

EDIT: Sharing some code for relevance:

dis = Disease.where(disease: params[:disease]).first
fac = Factor.where(factor: params[:factor])
dis.factors.create(fac, prop: "p1")

So, what I want is if I input same disease and factor, it not duplicate the edge (which it is currently doing) as property being set is also same. However, if in future, this p1 changes to p2, then the edge should be added.

Refer post Neo4j inconsistent behaviour of model classes for model classes (Disease and factor).


问:
Can I select a previous sibling in CSS?
I want to select #btnsrchicon parent's child #txtSearch. I tried in the below format, but not works

HTML

```<code><div id="topSearch">

<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
<button id="btnsrchicon" class="submit" onClick="search_another();"></button>

</div>
</code>```

and CSS

```<code><style>
 #txtSearch{display:none;}
#btnsrchicon:hover < #topSearch+#txtSearch
{
 display: block;
 border:2px solid red;
}
</style>
</code>```

答:
CSS doesn't offer this solution.

What you can do is a javascript solution when user hover elem:

```<code>$('#btnsrchicon').prev('#txtSearch').addClass('yourClass')
</code>```

Something like that:

$('#btnsrchicon').hover(function(){
  $(this).prev('#txtSearch').addClass('show');
}, function(){
  $(this).prev('#txtSearch').removeClass('show');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#txtSearch{
  display:none;
}

#txtSearch.show {
 display: block;
 border:2px solid red;
}</code>```

  <input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
  <button id="btnsrchicon" class="submit" onClick="search_another();">Button</button>

```
</div>
</div>
</p>

<p>Edit: Another solution</p>

<p><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>#txtSearch{
  display:none;
}

#btnsrchicon:hover + #txtSearch
{
 display: block;
 border:2px solid red;
}</code>```

<button id="btnsrchicon" class="submit" onClick="search_another();">Button</button>
<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>

 ```

... and you adjust the position with CSS.

Title: Can I select a previous sibling in CSS?

Body:
I want to select #btnsrchicon parent's child #txtSearch. I tried in the below format, but not works

HTML

<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
<button id="btnsrchicon" class="submit" onClick="search_another();"></button>

and CSS

Body:
CSS doesn't offer this solution.

What you can do is a javascript solution when user hover elem:

$('#btnsrchicon').prev('#txtSearch').addClass('yourClass')

Something like that:

$('#btnsrchicon').hover(function(){
  $(this).prev('#txtSearch').addClass('show');
}, function(){
  $(this).prev('#txtSearch').removeClass('show');
});

#txtSearch{
  display:none;
}

#txtSearch.show {
 display: block;
 border:2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="topSearch">
  <input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
  <button id="btnsrchicon" class="submit" onClick="search_another();">Button</button>
</div>

Edit: Another solution

#txtSearch{
  display:none;
}

#btnsrchicon:hover + #txtSearch
{
 display: block;
 border:2px solid red;
}

<div id="topSearch">

<button id="btnsrchicon" class="submit" onClick="search_another();">Button</button>
<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>

</div>

... and you adjust the position with CSS.


问:
Hbs IF statement basics
I want to do basic thing in hbs, but I'm stacked.
How to write if value greater than 0

{{#if value > 0}} {{/if}}

And if somebody can recommend some good tutorial for Hbs, and isn't PUG simpler to use?

答:
You can use handlebars helpers library

Or create own helper:

Handlebars.registerHelper('greater', function(conditional, value, options) {
 if (conditional > value) {
  return options.fn(this);
 } else {
  return options.inverse(this);
 }
});```
</div>
</div>
</p>

<p>and use it:</p>

```{{#greater value 0}} {{/greater}}
```

Title: Hbs IF statement basics

Body:
You can use handlebars helpers library

Or create own helper:

Handlebars.registerHelper('greater', function(conditional, value, options) {
 if (conditional > value) {
  return options.fn(this);
 } else {
  return options.inverse(this);
 }
});

and use it:

{{#greater value 0}} {{/greater}}


问:
Unit-testing of private method and possible refactoring
I am currently testing private method this way (using nunit):

```<code>class Foo
{
    private int Identity(int n) => n;
}

[TestFixture]
class MyTests
{
    [Test]
    public void TestFoo()
    {
        var myFoo = new Foo();
        var identityMethod = myFoo.GetType().GetMethod("Identity", BindingFlags.NonPublic | BindingFlags.Instance);
        Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
    }
}
</code>```

My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.

I tried to replace the name with nameof, but:

Foo.Indentity(int) is inaccessible due to its protection level

(By the way, this is strange in my opinion that such an operator respects the privacy protections).

So, can I test private methods without sacrificing possible refactoring?

I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.

Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.

答:
There´s no way to ensure your code won´t break because of a private member being renamed. Even nameof won´t help as you already mentioned because it can´t access private members. That´s one of the reasons you shouldn´t test private members - at least not directly but instead through your public API.

The only thing you could do is make your member internal and mark your assembly as InternalsVisibleTo combined with the name of your test-assembly. This way all internals are visible to your test-project. Be aware that doing so on a signed assembly will make indicate the fully qualified name of the friend-assembly.

Body:
I am currently testing private method this way (using nunit):

class Foo
{
    private int Identity(int n) => n;
}

[TestFixture]
class MyTests
{
    [Test]
    public void TestFoo()
    {
        var myFoo = new Foo();
        var identityMethod = myFoo.GetType().GetMethod("Identity", BindingFlags.NonPublic | BindingFlags.Instance);
        Assert.That(identityMethod.Invoke(myFoo, new []{ (object)42 }), Is.EqualTo(42));
    }
}

My team does not like this, because put the method name as a string prevent this method to be renamed, if we want to do refactoring through automatic tools.

I tried to replace the name with nameof, but:

Foo.Indentity(int) is inaccessible due to its protection level

(By the way, this is strange in my opinion that such an operator respects the privacy protections).

So, can I test private methods without sacrificing possible refactoring?

I was proposed to make the private methods protected and inherit the class with the class test, but this does not satisfy me.

Disclaimer: I know that some people think that private method should not be tested, but this is not the point here. Please do not transform this question into a debate about this.


问:
My json object becomes null when it reaches my controller function
I know this question has been asked many times, but this is different.

I have kendo grdi which i get selected and not selected type, the user have free role to make changes and that works. I did tried exmples like this Example1 ,Example2 and many others.

Now the problem is my json object that am trying to pass to the controller became null, I this is what i have tried below.

Can you please correct me if there's something wrong am doing ?

Javascript

JsonObj : This is what i get when i deselect from grid checkbox

```<code>[ { mailID: '10' , roleID: '5' , isMailSelected: 'false' } , {
  mailID: '11' , roleID: '5' , isMailSelected: 'false' } , {
 mailID: '19' , roleID: '9' , isMailSelected: 'false' } ]

function goToControllerSave() {
    var jsonObj = displayFilterResults();
    $.ajax({

        url: '@Url.Action("Save", "Account")',
        type: "POST",
        dataType: "json",
        traditional: true,
        data: { myobj: jsonObj },
        success: function (data) {

        },
        error: function (data) {

        }
    })

}

$(function () {
    $('#Grid1').on('click', '.chkbx', function () {
        var checked = $(this).is(':checked');
        var grid = $('#Grid1').data().kendoGrid;
        var dataItem = grid.dataItem($(this).closest('tr'));
        dataItem.set('isSelected', checked);
    })
})

//My json obj: this returns results on Alert

function displayFilterResults() {
    var items = "[";
    var dataSource = $("#Grid1").data("kendoGrid").dataSource;
    var filters = dataSource.filter();
    var allData = dataSource.data();
    var query = new kendo.data.Query(allData);
    var filteredData = query.filter(filters).data;

  items = items + " { mailID: '" + item.mailID + "' , roleID: '" +
  item.roleID + "' , isSelected: '" + item.isSelected + "' } ,";

    });
    if (items.charAt(items.length - 1) == ',') {
        items = items.substr(0, items.length - 1);
    }
    items = items + "]";

    alert(items)
    return items;
}
</code>```

My conntroller

```<code>   public class myItems
    {

        public string mailID { set; get; }
        public string roleID { set; get; }
        public string isSelected { set; get; }
    }

    [HttpPost]
    public ActionResult Save(List<myItems> myobj)
    {
       --------------
       --------------
    }
</code>```

答:
In the examples you mention, json object is an actual object, not the string representation. Then JSON.stringify() is used to get string formatted using double quotation marks, removing spare spaces, etc. Unfortunately MVC application has trouble parsing json that doesn't look like this.

Since you create a string directly, you need to produce similar json format.

```<code>var json = '{"myobj":[';
json +='{mailID:"10",roleID:"5",isMailSelected:"false"},';
json+='{mailID:"11",roleID:"5",isMailSelected:"false"},';
json +='{mailID:"19",roleID:"9",isMailSelected:"false"}'
json +=']}';
$.ajax({
    url: '@Url.Action("Save", "Account")',
    type: "POST",
    contentType: "application/json",
    dataType: 'html',
    data: json,
    success: function (data) {

    },
    error: function (data) {
    }
})
</code>```

In the class I have updated the name of member isSelected, cause I saw it didn't match json and I assume you changed it to isMailSelected.

```<code>public class myItems
{
    public string mailID { set; get; }
    public string roleID { set; get; }
    public string isMailSelected { set; get; }
}
</code>```

In my controller I have the same you posted

```<code>[HttpPost]
public ActionResult Save(List<myItems> myobj)
{
    return View();
}
</code>```

Body:
I know this question has been asked many times, but this is different.

I have kendo grdi which i get selected and not selected type, the user have free role to make changes and that works. I did tried exmples like this Example1 ,Example2 and many others.

Now the problem is my json object that am trying to pass to the controller became null, I this is what i have tried below.

Can you please correct me if there's something wrong am doing ?

Javascript

JsonObj : This is what i get when i deselect from grid checkbox

[ { mailID: '10' , roleID: '5' , isMailSelected: 'false' } , {
  mailID: '11' , roleID: '5' , isMailSelected: 'false' } , {
 mailID: '19' , roleID: '9' , isMailSelected: 'false' } ]

function goToControllerSave() {
    var jsonObj = displayFilterResults();
    $.ajax({

        url: '@Url.Action("Save", "Account")',
        type: "POST",
        dataType: "json",
        traditional: true,
        data: { myobj: jsonObj },
        success: function (data) {

        },
        error: function (data) {

        }
    })

}

$(function () {
    $('#Grid1').on('click', '.chkbx', function () {
        var checked = $(this).is(':checked');
        var grid = $('#Grid1').data().kendoGrid;
        var dataItem = grid.dataItem($(this).closest('tr'));
        dataItem.set('isSelected', checked);
    })
})

//My json obj: this returns results on Alert

function displayFilterResults() {
    var items = "[";
    var dataSource = $("#Grid1").data("kendoGrid").dataSource;
    var filters = dataSource.filter();
    var allData = dataSource.data();
    var query = new kendo.data.Query(allData);
    var filteredData = query.filter(filters).data;

  items = items + " { mailID: '" + item.mailID + "' , roleID: '" +
  item.roleID + "' , isSelected: '" + item.isSelected + "' } ,";

    });
    if (items.charAt(items.length - 1) == ',') {
        items = items.substr(0, items.length - 1);
    }
    items = items + "]";

    alert(items)
    return items;
}

My conntroller

   public class myItems
    {

        public string mailID { set; get; }
        public string roleID { set; get; }
        public string isSelected { set; get; }
    }

    [HttpPost]
    public ActionResult Save(List<myItems> myobj)
    {
       --------------
       --------------
    }

Body:
In the examples you mention, json object is an actual object, not the string representation. Then JSON.stringify() is used to get string formatted using double quotation marks, removing spare spaces, etc. Unfortunately MVC application has trouble parsing json that doesn't look like this.

Since you create a string directly, you need to produce similar json format.

var json = '{"myobj":[';
json +='{mailID:"10",roleID:"5",isMailSelected:"false"},';
json+='{mailID:"11",roleID:"5",isMailSelected:"false"},';
json +='{mailID:"19",roleID:"9",isMailSelected:"false"}'
json +=']}';
$.ajax({
    url: '@Url.Action("Save", "Account")',
    type: "POST",
    contentType: "application/json",
    dataType: 'html',
    data: json,
    success: function (data) {

    },
    error: function (data) {
    }
})

In the class I have updated the name of member isSelected, cause I saw it didn't match json and I assume you changed it to isMailSelected.

public class myItems
{
    public string mailID { set; get; }
    public string roleID { set; get; }
    public string isMailSelected { set; get; }
}

In my controller I have the same you posted

[HttpPost]
public ActionResult Save(List<myItems> myobj)
{
    return View();
}


问:
Elisp: Asking yes-or-no in interactive commands
I'm new to Emacs and am trying to write a few Emacs Lisp functions.

I'd like to write a function that takes two parameters and can handle being interactive. However, one of the parameters is a boolean — it'd be perfect if I could use (y-or-no-p), but (interactive) doesn't seem to have a character code for that.

Any ideas?

Update: I'm using GNU Emacs 23.

Also, here's what my function looks like so far:

```<code>(defun foo (str bool)
  (interactive "sSome text: \nsDo the thing?")
  (some-func str)
  (if bool (some-other-func str)))
</code>```

答:
Ah, found it.</p>

```<code>(defun foo (str bool)
  (interactive
    (list (read-string "Some text: ")
          (y-or-n-p "Do the thing? ")))
  (some-func str)
  (if bool (some-other-func str)))
</code>```

Body:
I'm new to Emacs and am trying to write a few Emacs Lisp functions.

I'd like to write a function that takes two parameters and can handle being interactive. However, one of the parameters is a boolean — it'd be perfect if I could use (y-or-no-p), but (interactive) doesn't seem to have a character code for that.

Any ideas?

Update: I'm using GNU Emacs 23.

Also, here's what my function looks like so far:

(defun foo (str bool)
  (interactive "sSome text: \nsDo the thing?")
  (some-func str)
  (if bool (some-other-func str)))

Body:
Ah, found it.

(defun foo (str bool)
  (interactive
    (list (read-string "Some text: ")
          (y-or-n-p "Do the thing? ")))
  (some-func str)
  (if bool (some-other-func str)))


问:
Android MediaPlayer unknown error
I am creating a MediaPlayer instance in MainActivity's onCreate() method like this

```<code> MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
</code>```

It is created successfully but I get this error:

```<code>07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
</code>```

Also tried this but the same error on logcat:

```<code>MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.prepareAsync();
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
</code>```

I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?

答:
Try using a FileInputStream to start your MediaPlayer with a FileDescriptor instead:</p>

```<code>String yourFilePath = "/wherever/your/file/is.wav";

MediaPlayer mPlayer = new MediaPlayer();

try{
    FileInputStream inputStream = new FileInputStream(yourFilePath);
    mPlayer.setDataSource(inputStream.getFD());
    inputStream.close();

    mPlayer.prepare();
    mPlayer.start();

}catch (IOException e){
    Log.e("IOException", e.getMessage());
}
</code>```

Title: Android MediaPlayer unknown error

Body:
I am creating a MediaPlayer instance in MainActivity's onCreate() method like this

 MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));

It is created successfully but I get this error:

07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0

Also tried this but the same error on logcat:

MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.prepareAsync();
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });

I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?

Body:
Try using a FileInputStream to start your MediaPlayer with a FileDescriptor instead:

String yourFilePath = "/wherever/your/file/is.wav";

MediaPlayer mPlayer = new MediaPlayer();

try{
    FileInputStream inputStream = new FileInputStream(yourFilePath);
    mPlayer.setDataSource(inputStream.getFD());
    inputStream.close();

    mPlayer.prepare();
    mPlayer.start();

}catch (IOException e){
    Log.e("IOException", e.getMessage());
}


问:
PUT with null attribute
Occasionally my API receives PUT requests where one of the boolean attributes is set to null. Something like this:

```<code>{
  "name": "John Doe",
  "email": "john.doe@company.com",
  "active": null
}
</code>```

If this would be a PATCH, I would simply ignore the attribute, but in case of PUT, what should I do? My intuition says: set active to false. But I'm not convinced that would be the right REST behavior.

What do you think?

答:
As per RFC7231:

6.5.1.  400 Bad Request

The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).

I would say you should reject processing of client's request which doesn't pass data validation with a 400 Bad Request response.

Also note that:

4.3.4.  PUT

The PUT method requests that the state of the target resource be
created or replaced with the state defined by the representation
enclosed in the request message payload.

so, you shouldn't just ignore invalid field values.

However, if you skip data validation and just accept the new resource state as sent by the client, then representation will be is inconsistent with the target resource, and you can try rewriting the request, or failing with 409 Conflict (RFC7231):

An origin server SHOULD verify that the PUT representation is
consistent with any constraints the server has for the target
resource that cannot or will not be changed by the PUT.  This is
particularly important when the origin server uses internal
configuration information related to the URI in order to set the
values for representation metadata on GET responses.  When a PUT
representation is inconsistent with the target resource, the origin
server SHOULD either make them consistent, by transforming the
representation or changing the resource configuration, or respond
with an appropriate error message containing sufficient information
to explain why the representation is unsuitable.  The 409 (Conflict)
or 415 (Unsupported Media Type) status codes are suggested, with the
latter being specific to constraints on Content-Type values.

Title: PUT with null attribute

Body:
Occasionally my API receives PUT requests where one of the boolean attributes is set to null. Something like this:

{
  "name": "John Doe",
  "email": "john.doe@company.com",
  "active": null
}

If this would be a PATCH, I would simply ignore the attribute, but in case of PUT, what should I do? My intuition says: set active to false. But I'm not convinced that would be the right REST behavior.

What do you think?