问:
Where to put constants in python
I'm very new to python and would like to understand what is the pythonic way to define some contants. I have the following class:

```<code>class ConfigBuilder:

   def add_param(self, key, value):
       #...
   def build():
       #...
</code>```

Now I want to use this in another module as follows:

```<code>some_val = #...
config_builder builder = ConfigBuilder()
builder.add_param('PROJECT_RELATED_KEY', some_val)
</code>```

Where to put this 'PROJECT_RELATED_KEY'? In another module and then import it? Or put it as a global variable?

答:
Agreed that there is no absolute convention for where settings should be stored. There's a lot of flexibility when it comes to project placement. Below are a few possibilities I might consider when deciding where to put my own settings.

If your project might contains some sensitive parameters that you wouldn't want in version control, you could put them into your environment and then access them with environment variables.

```<code>import os
print os.environ['HOME']
</code>```

If they're not sensitive at all, one possible route would be to do what Django does and create a settings.py file. Something like this

```<code># myproject/settings.py
SOME_VALUE = 'SomeConfigurableValue'
FOO = 'bar'
PROJECT_RELATED_KEY = 'bestkeyever'

# myproject/builder.py
from myproject.settings import SOME_VALUE
print(SOME_VALUE)
</code>```

You could even set up the project as a package and then do

```<code>from . import settings
print(settings.SOME_VALUE)
</code>```

For more info on setting up a project as a package, see:
How to fix "Attempted relative import in non-package" even with __init__.py

Title: Where to put constants in python

Body:
I'm very new to python and would like to understand what is the pythonic way to define some contants. I have the following class:

class ConfigBuilder:

   def add_param(self, key, value):
       #...
   def build():
       #...

Now I want to use this in another module as follows:

some_val = #...
config_builder builder = ConfigBuilder()
builder.add_param('PROJECT_RELATED_KEY', some_val)

Where to put this 'PROJECT_RELATED_KEY'? In another module and then import it? Or put it as a global variable?

Body:
Agreed that there is no absolute convention for where settings should be stored. There's a lot of flexibility when it comes to project placement. Below are a few possibilities I might consider when deciding where to put my own settings.

If your project might contains some sensitive parameters that you wouldn't want in version control, you could put them into your environment and then access them with environment variables.

import os
print os.environ['HOME']

If they're not sensitive at all, one possible route would be to do what Django does and create a settings.py file. Something like this

# myproject/settings.py
SOME_VALUE = 'SomeConfigurableValue'
FOO = 'bar'
PROJECT_RELATED_KEY = 'bestkeyever'

# myproject/builder.py
from myproject.settings import SOME_VALUE
print(SOME_VALUE)

You could even set up the project as a package and then do

from . import settings
print(settings.SOME_VALUE)

For more info on setting up a project as a package, see:
How to fix "Attempted relative import in non-package" even with __init__.py


来源: stackexchange

问:
A-Frame using teleport-controls with shake.js events
I want to use fernandojsg's teleport controls on my A-Frame project, but the way I want to use them is with shake.js, one shake to make the teleport line appear and another one to actually teleport where you selected.

I've seen the documentations and came across the startEvents and endEvent properties, and I want to map them into the shake event... for me it sounds like I have to create a custom component to do this, but I wanted to seek help first, to see if this is possible without doing it.

So far I've made this (glitch.com/ link) but it doesn't work so far (please note that I've got some other libraries there that make use of shake, mousedown, and similar events... my plan is to activate or deactivate them depending on how the user wants to move)

```<code>    <a-entity id="player" wasd-controls tap-to-walk>
     <a-camera id="eyes" position="-.5 1.5 0" camera="" look-controls="" mouse-cursor="">
      <a-entity id="cursor" cursor="fuse: false;"
        position="0 0 -1"
        geometry="primitive: ring; radiusInner: 0.015; radiusOuter: 0.019"
        material="color: white; shader: flat"
        raycaster="far: 5; interval: 1000; objects: .clickable">
      </a-entity>
      <a-entity id="texto" text="value:Hola;align:center" position="0 -.3 -0.5"></a-entity>
      <a-plane position="0 .7 -1" material="transparent: true;  opacity: 0.5; color: #ffec04; shader:flat;"  scale="1 0.2 1"></a-plane>
    </a-camera>
    <a-entity
    teleport-controls="cameraRig: #player; teleport-origins: #eyes; startEvents:['shake','mousedown']">        </a-entity>
    <a-entity id="step" sound="src: #step1"></a-entity>
  </a-entity>
</code>```

Thanks...

答:
Yes you will need a some JS or a custom component to get shake.js and teleport controls to work together for two reasons:

shake.js emits its events outside the A-Frame scene on window where teleport-controls is not listening

shake.js only emits one event type, and you need to differentiate for startEvents and endEvents

But it doesn't need to be very complicated:

```<code>AFRAME.registerComponent('shake-listener', {
  init: function () {
    var targetEl = this.el
    var count = 0
    // you could also initialize the shake instance here
    window.addEventListener('shake', function () {
      if (++count % 2) {
        targetEl.emit('shakestart')
      } else {
        targetEl.emit('shakeend')
      }
    })
  }
})
</code>```

Then add shake-listener to the same entity as teleport-controls="startEvents: shakestart; endEvents: shakeend"

ContentLicense: CC BY-SA 3.0

Body:
I want to use fernandojsg's teleport controls on my A-Frame project, but the way I want to use them is with shake.js, one shake to make the teleport line appear and another one to actually teleport where you selected.

I've seen the documentations and came across the startEvents and endEvent properties, and I want to map them into the shake event... for me it sounds like I have to create a custom component to do this, but I wanted to seek help first, to see if this is possible without doing it.

So far I've made this (glitch.com/ link) but it doesn't work so far (please note that I've got some other libraries there that make use of shake, mousedown, and similar events... my plan is to activate or deactivate them depending on how the user wants to move)

Thanks...

Body:
Yes you will need a some JS or a custom component to get shake.js and teleport controls to work together for two reasons:

shake.js emits its events outside the A-Frame scene on window where teleport-controls is not listening

shake.js only emits one event type, and you need to differentiate for startEvents and endEvents

But it doesn't need to be very complicated:

AFRAME.registerComponent('shake-listener', {
  init: function () {
    var targetEl = this.el
    var count = 0
    // you could also initialize the shake instance here
    window.addEventListener('shake', function () {
      if (++count % 2) {
        targetEl.emit('shakestart')
      } else {
        targetEl.emit('shakeend')
      }
    })
  }
})

Then add shake-listener to the same entity as teleport-controls="startEvents: shakestart; endEvents: shakeend"


问:
*ngFor next element
I am using Angular Cli. So, my html is:

```<code><div *ngFor="let Item of Items" (click)="add("*next Item should be here*")"></div>
</code>```

I need to send to function add() not Item but the next element. How I can call;it?
And I should stop when the arrow is end in order not to go out of the array

答:
If Items is an array or indexed collection you can use the special index variable and pass that to your function:

```<code><div *ngFor="let item of items; let i = index" (click)="add( i )">
</code>```

Then inside your add function you would check the index:

```<code>add(index: number): void {

    let nextIndex = index + 1;
    if( nextIndex < this.items.length ) {
        // do stuff
    }
    else {
        // error: there is no next-item
    }
}
</code>```

This is documented here: https://angular.io/api/common/NgForOf

index: number - The index of the current item in the iterable.

first: boolean - True when the item is the first item in the iterable.

last: boolean - True when the item is the last item in the iterable.

even: boolean - True when the item has an even index in the iterable.

odd: boolean - True when the item has an odd index in the iterable.

Title: *ngFor next element

Body:
I am using Angular Cli. So, my html is:

I need to send to function add() not Item but the next element. How I can call;it?
And I should stop when the arrow is end in order not to go out of the array

Body:
If Items is an array or indexed collection you can use the special index variable and pass that to your function:

<div *ngFor="let item of items; let i = index" (click)="add( i )">

Then inside your add function you would check the index:

add(index: number): void {

    let nextIndex = index + 1;
    if( nextIndex < this.items.length ) {
        // do stuff
    }
    else {
        // error: there is no next-item
    }
}

This is documented here: https://angular.io/api/common/NgForOf

index: number - The index of the current item in the iterable.

first: boolean - True when the item is the first item in the iterable.

last: boolean - True when the item is the last item in the iterable.

even: boolean - True when the item has an even index in the iterable.

odd: boolean - True when the item has an odd index in the iterable.


问:
Firebase access denied?
So I have this little code snippet that is responsible for uploading a picture to the firebase storage. For some odd reason, my access keeps getting denied. There seems to be a problem with storageRef because it goes into the if statement that prints out the  error.

```<code>  // will handle the  sign up of a user
    @objc func handleSignUp(){
        // first we cant to take sure that all of the fields are filled
        var profilePic: String = ""

        // will take the user selected image and load it to firebase
        let imageName = NSUUID().uuidString
 let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).PNG")
        if let userImage = selectedImageFromPicker,let uploadData = UIImageJPEGRepresentation(userImage, 0.1){

            storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil{
                    print(error ?? "")
                    return
                }
                 profilePic = (metadata?.downloadURL()!.absoluteString)!
                guard let username = self.nameTextField.text,
                    let confirmPassword = self.confirmPasswordTextField.text,
                    let email = self.emailTextField.text,
                    let password = self.passwordTextField.text,
                    !username.isEmpty,
                    !email.isEmpty,
                    !password.isEmpty,
                    !confirmPassword.isEmpty
                    else {

                        print("Required fields are not all filled!")
                        return
                }
                if self.validateEmail(enteredEmail:email) != true{
                    let alertController = UIAlertController(title: "Error", message: "Please Enter A Valid Email", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)
                    self.present(alertController, animated: true, completion: nil)
                }

                // will make sure user is validated before it even tries to create user

                // will make sure the password and confirm password textfields have the same value if so it will print an error
                if self.passwordTextField.text != self.confirmPasswordTextField.text {
                    let alertController = UIAlertController(title: "Error", message: "Passwords Don't Match", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)
                    self.present(alertController, animated: true, completion: nil)
                }

                // will authenticate a user into the authentication services with an email and passowrd
                AuthService.createUser(controller: self, email: email, password: password) { (authUser) in
                    guard let firUser = authUser else {
                        return
                    }
                    //will add user to the database
                    print(profilePic)
                    print(username)
                    UserService.create(firUser, username: username , profilePic: profilePic,location: self.userLocation!) { (user) in
                        guard let user = user else {
                            print("User successfully loaded into firebase db")
                            return
                        }
                        // will set the current user for userdefaults to work
                        print(user.profilePic)
                        print(user.username)

                        User.setCurrent(user, writeToUserDefaults: true)
                        // self.delegate?.finishSigningUp()

                        self.finishSigningUp()

                    }
                }

        })
        }
    }
</code>```

The error is

```<code>Error Domain=FIRStorageErrorDomain Code=-13021 "User does not have permission to access gs://eventful-3d558.appspot.com/profile_images/C0BC898A-6A6F-490F-954B-51D705CD2B23.PNG." UserInfo={object=profile_images/C0BC898A-6A6F-490F-954B-51D705CD2B23.PNG, bucket=eventful-3d558.appspot.com, ResponseBody={
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
  }
</code>```

If anyone knows what it is I would appreciate your help. It is preventing me from signing up users.

答: this is a perfect firebase presentation that will help with this problem: https://firebase.google.com/docs/database/security/</p>

Title: Firebase access denied?

Body:
So I have this little code snippet that is responsible for uploading a picture to the firebase storage. For some odd reason, my access keeps getting denied. There seems to be a problem with storageRef because it goes into the if statement that prints out the  error.

  // will handle the  sign up of a user
    @objc func handleSignUp(){
        // first we cant to take sure that all of the fields are filled
        var profilePic: String = ""

        // will take the user selected image and load it to firebase
        let imageName = NSUUID().uuidString
 let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).PNG")
        if let userImage = selectedImageFromPicker,let uploadData = UIImageJPEGRepresentation(userImage, 0.1){

            storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil{
                    print(error ?? "")
                    return
                }
                 profilePic = (metadata?.downloadURL()!.absoluteString)!
                guard let username = self.nameTextField.text,
                    let confirmPassword = self.confirmPasswordTextField.text,
                    let email = self.emailTextField.text,
                    let password = self.passwordTextField.text,
                    !username.isEmpty,
                    !email.isEmpty,
                    !password.isEmpty,
                    !confirmPassword.isEmpty
                    else {

                        print("Required fields are not all filled!")
                        return
                }
                if self.validateEmail(enteredEmail:email) != true{
                    let alertController = UIAlertController(title: "Error", message: "Please Enter A Valid Email", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)
                    self.present(alertController, animated: true, completion: nil)
                }

                // will make sure user is validated before it even tries to create user

                // will make sure the password and confirm password textfields have the same value if so it will print an error
                if self.passwordTextField.text != self.confirmPasswordTextField.text {
                    let alertController = UIAlertController(title: "Error", message: "Passwords Don't Match", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)
                    self.present(alertController, animated: true, completion: nil)
                }

                // will authenticate a user into the authentication services with an email and passowrd
                AuthService.createUser(controller: self, email: email, password: password) { (authUser) in
                    guard let firUser = authUser else {
                        return
                    }
                    //will add user to the database
                    print(profilePic)
                    print(username)
                    UserService.create(firUser, username: username , profilePic: profilePic,location: self.userLocation!) { (user) in
                        guard let user = user else {
                            print("User successfully loaded into firebase db")
                            return
                        }
                        // will set the current user for userdefaults to work
                        print(user.profilePic)
                        print(user.username)

                        User.setCurrent(user, writeToUserDefaults: true)
                        // self.delegate?.finishSigningUp()

                        self.finishSigningUp()

                    }
                }

        })
        }
    }

The error is

Error Domain=FIRStorageErrorDomain Code=-13021 "User does not have permission to access gs://eventful-3d558.appspot.com/profile_images/C0BC898A-6A6F-490F-954B-51D705CD2B23.PNG." UserInfo={object=profile_images/C0BC898A-6A6F-490F-954B-51D705CD2B23.PNG, bucket=eventful-3d558.appspot.com, ResponseBody={
  "error": {
    "code": 403,
    "message": "Permission denied. Could not perform this operation"
  }

If anyone knows what it is I would appreciate your help. It is preventing me from signing up users.


问:
Unity inventory System stack system
I have created an inventory system in Unity using C#. I currently have a simple stack system in my inventory where if an item is greater than the stack it stops adding it to the current inventory slot. But I was wondering how can I set it so it will add an instance of the same item to a different slot once the other slot is full?

Here's my code if you guys need me to share anymore classes let me know, any help would be greatly appreciated.

```<code>/**
 * Controller class used to handle the logic and functionality of the
inventory system
 **/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventoryController : MonoBehaviour
{

Inventory inv;
ItemDatabase database;
public int maxSize = 3;

private void Awake()
{
    database = GetComponent<ItemDatabase>();
    inv = GetComponent<Inventory>();

    inv.slotAmount = 25;
    inv.background = GameObject.Find("SlotBackgroundPanel");
    inv.slotPanel = inv.background.transform.Find("SlotPanel").gameObject;
    for (int i = 0; i < inv.slotAmount; i++)
    {
        inv.items.Add(new InventoryModel());
        inv.slots.Add(Instantiate(inv.inventorySlot));
        inv.slots[i].GetComponent<ItemSlot>().id = i;
        inv.slots[i].transform.SetParent(inv.slotPanel.transform);
    }
}

public void AddItem(int id)
{
    InventoryModel itemToAdd = database.FetchItemByID(id);
    if (itemToAdd.Stackable && CheckItemInInventory(itemToAdd))
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].ID == id)
            {

                ItemData data = inv.slots[i].transform.GetChild(0).GetComponent<ItemData>();
                data.amount++;
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                break;
            }
        }
    }

    else
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].ID == -1)
            {
                inv.items[i] = itemToAdd;
                GameObject itemObj = Instantiate(inv.inventoryItem);
                itemObj.GetComponent<ItemData>().inventoryModel = itemToAdd;
                itemObj.GetComponent<ItemData>().amount = 1;
                itemObj.GetComponent<ItemData>().slot = i;
                itemObj.transform.SetParent(inv.slots[i].transform);
                itemObj.transform.position = Vector2.zero;
                itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
                itemObj.name = itemToAdd.Title;
                break;
            }
        }
    }
}

public void RemoveItem(int id)
{
    InventoryModel itemToRemove = database.FetchItemByID(id);
    if (itemToRemove.Stackable && CheckItemInInventory(itemToRemove))
    {

        for (int j = 0; j < inv.items.Count; j++)
        {
            if (inv.items[j].ID == id)
            {
                ItemData data = inv.slots[j].transform.GetChild(0).GetComponent<ItemData>();
                data.amount--;
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                if (data.amount == 0)
                {
                    Destroy(inv.slots[j].transform.GetChild(0).gameObject);
                    inv.items[j] = new InventoryModel();
                    break;
                }
                if (data.amount == 1)
                {
                    inv.slots[j].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = "";
                    break;
                }
                break;
            }
        }
    }
    else
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].Title == null && inv.items[i].ID == id)
            {
                Destroy(inv.slots[i].transform.GetChild(0).gameObject); inv.items[i] = new InventoryModel();
                break;
            }
        }

    }
}

public void FullItem(int id)
{
    InventoryModel itemIsFull = database.FetchItemByID(id);
    if (itemIsFull.Stackable && CheckItemInInventory(itemIsFull))
    {
        for (int y = 0; y < inv.items.Count; y++)
        {
            if (inv.items[y].ID == id)
            {
                ItemData data = inv.slots[y].transform.GetChild(0).GetComponent<ItemData>();
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();

                if (data.amount >= maxSize)
                {
                    inv.slots[y].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = "3";
                    data.amount = 3;
                    Debug.Log(data.amount);
                    break;
                }
            }
        }
    }
}

public bool CheckItemInInventory(InventoryModel inventoryModel)
{
    for (int i = 0; i < inv.items.Count; i++)
        if (inv.items[i].Title == inventoryModel.Title)
            return true;
    return false;
}
}
</code>```

Class used for View

```<code>using System.Collections;
/**
 * View class, used to handle the User Interface
 **/

using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class Inventory : MonoBehaviour
{

public GameObject background;
public GameObject slotPanel;
InventoryController inventoryController;
public GameObject inventorySlot;
public GameObject inventoryItem;
public int slotAmount;

public enum type { diamond = 0, iron = 1, gold = 2, fuel = 3 };

public List<InventoryModel> items = new List<InventoryModel>();
public List<GameObject> slots = new List<GameObject>();

private void Start()
{

    inventoryController = GetComponent<InventoryController>();

    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);

    inventoryController.AddItem((int)type.gold);
    inventoryController.AddItem((int)type.fuel);

   inventoryController.FullItem((int)type.diamond);
}
}
</code>```

Class used for Model

```<code>    /**
 * Model class used to handle and store variables
 **/

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

public class InventoryModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool Stackable { get; set; }
public string Slug { get; set; }
public Sprite Sprite { get; set; }

public InventoryModel(int id, string title, string description,
    bool stackable, string slug)
{
    this.ID = id;
    this.Title = title;
    this.Description = description;
    this.Stackable = stackable;
    this.Slug = slug;

    this.Sprite = Resources.Load<Sprite>("Sprites/Items/" + slug);
}

public InventoryModel()
{
    this.ID = -1;
}
}
</code>```

Json File

```<code>[
{
"id" : 0,
"title" : "Diamond",
"value" : 5,
"stats":{
    "defence": 9,
    "power" : 8,
    "weight" : 5
    },
"description": "Mined Diamond is stronger than metal",
"stackable" : true,
"rarity" : 10,
"slug": "Diamond"
},

{
"id" : 1,
"title" : "Iron",
"value" : 2,
"stats":{
    "defence" : 5,
    "power" : 6,
    "weight" : 7
},
"description" : "Mined Iron is stronger than bronze",
"stackable" : false,
"rarity" : 6,
"slug" : "Metal"
},

{
"id" : 2,
"title" : "Gold",
"value" : 2,
"stats":{
    "defence" : 0,
    "power" : 0,
    "weight" : 0
},
"description" : "Gold is valuable",
"stackable" : false,
"rarity" : 10,
"slug" : "Gold"
},

{
"id" : 3,
"title" : "Fuel2",
"value" : 2,
"stats":{
    "defence" : 0,
    "power" : 0,
    "weight" : 0
    },
"description" : "Fuel is needed for ship engines",
"stackable" : true,
"rarity" : 2,
"slug" : "Fuel2"
}

]
</code>```

答:
Ah, I remember this problem when I was making my inventory system. I made a similar one to Minecraft, slot based, drag and drop.. etc. Anywho lost the source code wah.

I was really, really bored so I decided to copy your code and add a function to check if the item's amount is less than a maximum stack size. Take a look:

```<code>InventoryModel itemToAdd = database.FetchItemByID(id);

    // First check if the item is in the inventory
    // This check can be discarded. See below...
    // You might be able to use this check in some form of anti-cheat system, so I've left it there.

    if (CheckItemInInventory(itemToAdd))
    {
        // Iterate through the inventory and check items against their ID/Name
        for (int i = 0; i < inv.items.Count; i++)
        {
            // If the item in the slot has the same ID as the item we want to add...

            if (inv.items[i].ID == id)
            {
                // Check if the item is actually stackable and the slot is not full
                // I.E the stack size (amount) is less than the max stack size.

                // You'll need to add a new variable to your InventoryModel class
                // int maxStackSize

                if (inv.items[i].amount < inv.items[i].maxStackSize && itemToAdd.Stackable)
                {
                    ItemData data = inv.slots[i].transform.GetChild(0).GetComponent<ItemData>();
                    data.amount++;
                    data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                    break;
                }
                // If not, then we skip adding a new item because this slot is already occupied and it's stack size is full
            }
            else if (inv.items[i].id == -1)
            {
                // If we encounter an empty slot, add a new item.
                inv.items[i] = itemToAdd;
                GameObject itemObj = Instantiate(inv.inventoryItem);
                itemObj.GetComponent<ItemData>().inventoryModel = itemToAdd;
                itemObj.GetComponent<ItemData>().amount = 1;
                itemObj.GetComponent<ItemData>().slot = i;
                itemObj.transform.SetParent(inv.slots[i].transform);
                itemObj.transform.position = Vector2.zero;
                itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
                itemObj.name = itemToAdd.Title;
            }
        }
        // If the code's execution reaches this point, then we are essentially skipping action on the slot.
        // This means that we were not able to find an item that matched the ID OR the stack size was full...
        // So we keep scanning the other slots next in line...
    }
    else
    {
        // do something if the player tried to add an item but it does not exist in their inventory
        // or something doesn't quite add up... Good for anti-cheat systems.
    }
</code>```

As you can see, I've made some adjustments and some optimizations to your code, including removing some redundant checks. You were checking the player's inventory twice. Once to verify if they had the item, and then again to add the item to the inventory. You can do both operations in one swoop.

I should also mention that I wrote the code in visual studio, so it should be good for copy-paste. Enjoy!

Title: Unity inventory System stack system

Body:
I have created an inventory system in Unity using C#. I currently have a simple stack system in my inventory where if an item is greater than the stack it stops adding it to the current inventory slot. But I was wondering how can I set it so it will add an instance of the same item to a different slot once the other slot is full?

Here's my code if you guys need me to share anymore classes let me know, any help would be greatly appreciated.

/**
 * Controller class used to handle the logic and functionality of the
inventory system
 **/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventoryController : MonoBehaviour
{

Inventory inv;
ItemDatabase database;
public int maxSize = 3;

private void Awake()
{
    database = GetComponent<ItemDatabase>();
    inv = GetComponent<Inventory>();

    inv.slotAmount = 25;
    inv.background = GameObject.Find("SlotBackgroundPanel");
    inv.slotPanel = inv.background.transform.Find("SlotPanel").gameObject;
    for (int i = 0; i < inv.slotAmount; i++)
    {
        inv.items.Add(new InventoryModel());
        inv.slots.Add(Instantiate(inv.inventorySlot));
        inv.slots[i].GetComponent<ItemSlot>().id = i;
        inv.slots[i].transform.SetParent(inv.slotPanel.transform);
    }
}

public void AddItem(int id)
{
    InventoryModel itemToAdd = database.FetchItemByID(id);
    if (itemToAdd.Stackable && CheckItemInInventory(itemToAdd))
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].ID == id)
            {

                ItemData data = inv.slots[i].transform.GetChild(0).GetComponent<ItemData>();
                data.amount++;
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                break;
            }
        }
    }

    else
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].ID == -1)
            {
                inv.items[i] = itemToAdd;
                GameObject itemObj = Instantiate(inv.inventoryItem);
                itemObj.GetComponent<ItemData>().inventoryModel = itemToAdd;
                itemObj.GetComponent<ItemData>().amount = 1;
                itemObj.GetComponent<ItemData>().slot = i;
                itemObj.transform.SetParent(inv.slots[i].transform);
                itemObj.transform.position = Vector2.zero;
                itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
                itemObj.name = itemToAdd.Title;
                break;
            }
        }
    }
}

public void RemoveItem(int id)
{
    InventoryModel itemToRemove = database.FetchItemByID(id);
    if (itemToRemove.Stackable && CheckItemInInventory(itemToRemove))
    {

        for (int j = 0; j < inv.items.Count; j++)
        {
            if (inv.items[j].ID == id)
            {
                ItemData data = inv.slots[j].transform.GetChild(0).GetComponent<ItemData>();
                data.amount--;
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                if (data.amount == 0)
                {
                    Destroy(inv.slots[j].transform.GetChild(0).gameObject);
                    inv.items[j] = new InventoryModel();
                    break;
                }
                if (data.amount == 1)
                {
                    inv.slots[j].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = "";
                    break;
                }
                break;
            }
        }
    }
    else
    {
        for (int i = 0; i < inv.items.Count; i++)
        {
            if (inv.items[i].Title == null && inv.items[i].ID == id)
            {
                Destroy(inv.slots[i].transform.GetChild(0).gameObject); inv.items[i] = new InventoryModel();
                break;
            }
        }

    }
}

public void FullItem(int id)
{
    InventoryModel itemIsFull = database.FetchItemByID(id);
    if (itemIsFull.Stackable && CheckItemInInventory(itemIsFull))
    {
        for (int y = 0; y < inv.items.Count; y++)
        {
            if (inv.items[y].ID == id)
            {
                ItemData data = inv.slots[y].transform.GetChild(0).GetComponent<ItemData>();
                data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();

                if (data.amount >= maxSize)
                {
                    inv.slots[y].transform.GetChild(0).transform.GetChild(0).GetComponent<Text>().text = "3";
                    data.amount = 3;
                    Debug.Log(data.amount);
                    break;
                }
            }
        }
    }
}

public bool CheckItemInInventory(InventoryModel inventoryModel)
{
    for (int i = 0; i < inv.items.Count; i++)
        if (inv.items[i].Title == inventoryModel.Title)
            return true;
    return false;
}
}

Class used for View

using System.Collections;
/**
 * View class, used to handle the User Interface
 **/

using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;

public class Inventory : MonoBehaviour
{

public GameObject background;
public GameObject slotPanel;
InventoryController inventoryController;
public GameObject inventorySlot;
public GameObject inventoryItem;
public int slotAmount;

public enum type { diamond = 0, iron = 1, gold = 2, fuel = 3 };

public List<InventoryModel> items = new List<InventoryModel>();
public List<GameObject> slots = new List<GameObject>();

private void Start()
{

    inventoryController = GetComponent<InventoryController>();

    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);
    inventoryController.AddItem((int)type.diamond);

    inventoryController.AddItem((int)type.gold);
    inventoryController.AddItem((int)type.fuel);

   inventoryController.FullItem((int)type.diamond);
}
}

Class used for Model

    /**
 * Model class used to handle and store variables
 **/

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

public class InventoryModel
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool Stackable { get; set; }
public string Slug { get; set; }
public Sprite Sprite { get; set; }

public InventoryModel(int id, string title, string description,
    bool stackable, string slug)
{
    this.ID = id;
    this.Title = title;
    this.Description = description;
    this.Stackable = stackable;
    this.Slug = slug;

    this.Sprite = Resources.Load<Sprite>("Sprites/Items/" + slug);
}

public InventoryModel()
{
    this.ID = -1;
}
}

Json File

[
{
"id" : 0,
"title" : "Diamond",
"value" : 5,
"stats":{
    "defence": 9,
    "power" : 8,
    "weight" : 5
    },
"description": "Mined Diamond is stronger than metal",
"stackable" : true,
"rarity" : 10,
"slug": "Diamond"
},

{
"id" : 1,
"title" : "Iron",
"value" : 2,
"stats":{
    "defence" : 5,
    "power" : 6,
    "weight" : 7
},
"description" : "Mined Iron is stronger than bronze",
"stackable" : false,
"rarity" : 6,
"slug" : "Metal"
},

{
"id" : 2,
"title" : "Gold",
"value" : 2,
"stats":{
    "defence" : 0,
    "power" : 0,
    "weight" : 0
},
"description" : "Gold is valuable",
"stackable" : false,
"rarity" : 10,
"slug" : "Gold"
},

{
"id" : 3,
"title" : "Fuel2",
"value" : 2,
"stats":{
    "defence" : 0,
    "power" : 0,
    "weight" : 0
    },
"description" : "Fuel is needed for ship engines",
"stackable" : true,
"rarity" : 2,
"slug" : "Fuel2"
}

]

Body:
Ah, I remember this problem when I was making my inventory system. I made a similar one to Minecraft, slot based, drag and drop.. etc. Anywho lost the source code wah.

I was really, really bored so I decided to copy your code and add a function to check if the item's amount is less than a maximum stack size. Take a look:

InventoryModel itemToAdd = database.FetchItemByID(id);

    // First check if the item is in the inventory
    // This check can be discarded. See below...
    // You might be able to use this check in some form of anti-cheat system, so I've left it there.

    if (CheckItemInInventory(itemToAdd))
    {
        // Iterate through the inventory and check items against their ID/Name
        for (int i = 0; i < inv.items.Count; i++)
        {
            // If the item in the slot has the same ID as the item we want to add...

            if (inv.items[i].ID == id)
            {
                // Check if the item is actually stackable and the slot is not full
                // I.E the stack size (amount) is less than the max stack size.

                // You'll need to add a new variable to your InventoryModel class
                // int maxStackSize

                if (inv.items[i].amount < inv.items[i].maxStackSize && itemToAdd.Stackable)
                {
                    ItemData data = inv.slots[i].transform.GetChild(0).GetComponent<ItemData>();
                    data.amount++;
                    data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
                    break;
                }
                // If not, then we skip adding a new item because this slot is already occupied and it's stack size is full
            }
            else if (inv.items[i].id == -1)
            {
                // If we encounter an empty slot, add a new item.
                inv.items[i] = itemToAdd;
                GameObject itemObj = Instantiate(inv.inventoryItem);
                itemObj.GetComponent<ItemData>().inventoryModel = itemToAdd;
                itemObj.GetComponent<ItemData>().amount = 1;
                itemObj.GetComponent<ItemData>().slot = i;
                itemObj.transform.SetParent(inv.slots[i].transform);
                itemObj.transform.position = Vector2.zero;
                itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
                itemObj.name = itemToAdd.Title;
            }
        }
        // If the code's execution reaches this point, then we are essentially skipping action on the slot.
        // This means that we were not able to find an item that matched the ID OR the stack size was full...
        // So we keep scanning the other slots next in line...
    }
    else
    {
        // do something if the player tried to add an item but it does not exist in their inventory
        // or something doesn't quite add up... Good for anti-cheat systems.
    }

As you can see, I've made some adjustments and some optimizations to your code, including removing some redundant checks. You were checking the player's inventory twice. Once to verify if they had the item, and then again to add the item to the inventory. You can do both operations in one swoop.

I should also mention that I wrote the code in visual studio, so it should be good for copy-paste. Enjoy!


问:
How to create mysql table with many hasMany association in CakePHP?
I'm defining a completely new database. I have now faced a problem
which I would describe as "usual" but still could not find good
information from web. So here's the problem:

I have many tables in my database (which I would describe as guides) such as:

Skills

Places

Activities

and so on...

Now to all these guide types I'd like to add a comment feature and
other similar features like attaching images and videos. I have many guide types so I dropped the idea of having a separate comment image and video tables for each of them. I need one table for each of them.

The question is, what is the best way to achieve this? I have heard and read about 3 solutions and I'm not familiar with none of them.

I have read about using UUIDs would fix this problem but I'm not very familiar how they function. Could someone elaborate on that if that is the correct way to go? Something about UUIDs I read but not quite understood it.

Other thing I have read about is creating a hierarchial model "tree table" which would hold association links. More info at Managing Hierarchical Data in MySQL.

I have also read about creating object tables and using program like object inheritance inside MySQL in a similar way like the hierarchical model.

UUIDs sound most simple so I would appreciate help in there.

I don't know anything about how to use them. But here's how I thought it works - at least you'll get a hang of it what I'm trying to achieve here and how/what I'm misunderstanding about them:

I would create a new table: Guides which could have UUID field.

Then link all those guide types (Skills etc.) to guide table (Guide as parent and the other as child)

Parent and Child have both UUID fields and when creating a guide Parent and Child gets same UUID so they can be linked. Child also has its own Id field.

Then link comments to Guides by using UUID field that points to Guide plus separate id int field for comments.

Please tell me if this is correct way or is it total garbage and if so, how I should do it?

答:
Have you though about using a normal hasMany relationship with a condition? Read about it here.

```<code>class Skill extends AppModel {
  var $hasMany = array(
    'Comment' => array(
      'className'     => 'Comment',
        'conditions'    => array('Comment.type' => 1), // 1 for skills, 2 for places etc. or something like that.
      )
    );
}
</code>```

Body:
Have you though about using a normal hasMany relationship with a condition? Read about it here.

class Skill extends AppModel {
  var $hasMany = array(
    'Comment' => array(
      'className'     => 'Comment',
        'conditions'    => array('Comment.type' => 1), // 1 for skills, 2 for places etc. or something like that.
      )
    );
}

ContentLicense: CC BY-SA 2.5


问:
SQL not displaying null values on a not equals query?
This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns.  The column has four possible values null, 0, 1, 2.  When I run the query as:

```<code>SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';
</code>```

I get the same results as running:

```<code>SELECT * FROM STATUS WHERE STATE = '0';
</code>```

I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?

I'm running my commands through Oracle SQL Developer.

答: use NVL like so: SELECT * FROM STATUS WHERE NVL(STATE,'X') != '1' AND  NVL(STATE,'X')!= '2';

Body:
This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns.  The column has four possible values null, 0, 1, 2.  When I run the query as:

SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2';

I get the same results as running:

SELECT * FROM STATUS WHERE STATE = '0';

I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?

I'm running my commands through Oracle SQL Developer.


问:
Update two similar csv files with same key using pandas
I have two inventory csv, one is the updated version of the other;
the new one can have new rows with keys not presents in old one; missing row for keys no more presents; same keys with updated records:

```<code>sku nome    prezzo  qty codice
1   uno       10    1   11111
2   due       10    1   22222
3   tre       10    1   33333
4   quattro   10    1   44444
5   cinque    10    1   55555
10  dieci     10    1   101010

sku nome    prezzo  qty codice
  1  uno        20    2  11111
  2  due        20    2  22222
  3  tre        20    2  33333
  5  cinque     20    2  55555
 10  dieci      20    2  101010
 11  undici     20    2  111111
</code>```

with reindex union I can menage to have my desired result:

```<code>In [52]: r = b.set_index('sku') \
    ...:       .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \
    ...:       .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \
    ...:       .reset_index()

sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111
</code>```

Now, if the new files had same colums + other that aren't presents in old one,the result is right but I have column rearranged;
how to keep the column structure of new file?

(new file with new colums structure):

```<code>   sku     nome  prezzo  qty  codice   Acolumn     Bcolumn
0    1      uno      20    2   11111   kkkk
1    2      due      20    2   22222               qwerty
2    3      tre      20    2   33333   mmmm
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010   ssss
6   11   undici      20    2  111111   1a2b3c4d
</code>```

or

```<code>   sku     nome   Acolumn  prezzo  qty  codice     Bcolumn
0    1      uno    kkkkk       20    2   11111
1    2      due                20    2   22222     qwerty
2    3      tre                20    2   33333
3    4  quattro                 0    0   44444
4    5   cinque                20    2   55555
5   10    dieci                20    2  101010
6   11   undici                20    2  111111
</code>```

答:
Option 1

I've tried to improve your existing solution. You can use reindex + combine_first + reindex again:

```<code>df1 = df1.set_index('sku')
df2 = df2.set_index('sku')

df = df2.reindex(df1.index.union(df2.index), fill_value=0)
df = df1[['nome', 'codice']].combine_first(df).reindex(columns=df1.columns)

c = df.dtypes == 'float'
df.loc[:, c] = df.loc[:, c].astype(int)

df

   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111
</code>```

Option 2

Alternatively, substitute combine_first with replace + fillna:

```<code>df.nome = df.nome.replace(0, np.nan).fillna(df1.nome)
df.codice = df.codice.replace(0, np.nan).fillna(df1.codice).astype(int)

df.reset_index()

   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111
</code>```

Body:
I have two inventory csv, one is the updated version of the other;
the new one can have new rows with keys not presents in old one; missing row for keys no more presents; same keys with updated records:

sku nome    prezzo  qty codice
1   uno       10    1   11111
2   due       10    1   22222
3   tre       10    1   33333
4   quattro   10    1   44444
5   cinque    10    1   55555
10  dieci     10    1   101010

sku nome    prezzo  qty codice
  1  uno        20    2  11111
  2  due        20    2  22222
  3  tre        20    2  33333
  5  cinque     20    2  55555
 10  dieci      20    2  101010
 11  undici     20    2  111111

with reindex union I can menage to have my desired result:

In [52]: r = b.set_index('sku') \
    ...:       .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \
    ...:       .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \
    ...:       .reset_index()

sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111

Now, if the new files had same colums + other that aren't presents in old one,the result is right but I have column rearranged;
how to keep the column structure of new file?

(new file with new colums structure):

   sku     nome  prezzo  qty  codice   Acolumn     Bcolumn
0    1      uno      20    2   11111   kkkk
1    2      due      20    2   22222               qwerty
2    3      tre      20    2   33333   mmmm
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010   ssss
6   11   undici      20    2  111111   1a2b3c4d

or

   sku     nome   Acolumn  prezzo  qty  codice     Bcolumn
0    1      uno    kkkkk       20    2   11111
1    2      due                20    2   22222     qwerty
2    3      tre                20    2   33333
3    4  quattro                 0    0   44444
4    5   cinque                20    2   55555
5   10    dieci                20    2  101010
6   11   undici                20    2  111111

Body:
Option 1

I've tried to improve your existing solution. You can use reindex + combine_first + reindex again:

df1 = df1.set_index('sku')
df2 = df2.set_index('sku')

df = df2.reindex(df1.index.union(df2.index), fill_value=0)
df = df1[['nome', 'codice']].combine_first(df).reindex(columns=df1.columns)

c = df.dtypes == 'float'
df.loc[:, c] = df.loc[:, c].astype(int)

df

   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111

Option 2

Alternatively, substitute combine_first with replace + fillna:

df.nome = df.nome.replace(0, np.nan).fillna(df1.nome)
df.codice = df.codice.replace(0, np.nan).fillna(df1.codice).astype(int)

df.reset_index()

   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111


问:
geom_vline on R not working for adding vertical line on a ggplot graph
I'm having a problem to draw a graph with multiple lines on R.
I'm trying to add some vertical lines on a plot, but it's not working.

I'm using the following code.

```<code>library(ggplot2)
library("ggthemes")
library("scales")
dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)

p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
   theme(aspect.ratio=.4,text = element_text(size=13),
          panel.grid.major = element_line(colour = "grey"),
          panel.border = element_rect( fill = NA),
          panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016), linetype="dotted", color="red")
</code>```

I tried using another format with this code, but it also didn't worked.

```<code>dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30, 3, 7, 20, 22, 19, 29, 18, 15, 16, 18, 0, 1, 1, 2, 1, 6, 5, 9, 1, 4, 0, 0, 2, 4, 6, 2, 6, 7, 2, 8),
  group = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4)
)

p<- ggplot(data=dat, aes(x=time, y=frequency,group=group, color=as.factor(group) )) +
  geom_line() +
  geom_point() +
  scale_color_manual(breaks = c("1", "2", "3", "4"),
                     values=c("slateblue", "darkgoldenrod", "darkgreen", "chocolate")) +
  xlab("Year") + ylab("Number of publications") + theme_bw() +

guides(shape = FALSE, linetype = FALSE,
       colour = guide_legend(override.aes =  list(shape = c(16, 16, 16,  16),
                                                  linetype = c("solid","solid","solid", "solid"),
                                                  labels= c("All articles","Performance","Correctness","Fault tolerance"),
                                                  title = "Category"
       )))

p +   geom_vline(xintercept=as.numeric(2012), linetype="dotted", color="red", size=3)
</code>```

There are other problems that I have with both codes (that's why I have two different codes), like not being able to order the legend on the first code, or the color is wrong for some reason. The second graph I can't replace the legend text for some reason, but the vertical line is the main problem right now.

答:
I changed the way you created the time column from factor to numeric as follows.

```<code>dat <- data.frame(
  time = 2007:2016,
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)
</code>```

Now it works. In the following code I also change the line size to 2 for clarity.

```<code>p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
  theme(aspect.ratio=.4,text = element_text(size=13),
        panel.grid.major = element_line(colour = "grey"),
        panel.border = element_rect( fill = NA),
        panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016),
                 linetype="dotted",
                 color="red",
                 size = 2)
</code>```

Body:
I'm having a problem to draw a graph with multiple lines on R.
I'm trying to add some vertical lines on a plot, but it's not working.

I'm using the following code.

library(ggplot2)
library("ggthemes")
library("scales")
dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)

p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
   theme(aspect.ratio=.4,text = element_text(size=13),
          panel.grid.major = element_line(colour = "grey"),
          panel.border = element_rect( fill = NA),
          panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016), linetype="dotted", color="red")

I tried using another format with this code, but it also didn't worked.

dat <- data.frame(
  time = factor(c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016"),
                levels=c("2007","2008","2009","2010","2011","2012","2013","2014","2015","2016")),
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30, 3, 7, 20, 22, 19, 29, 18, 15, 16, 18, 0, 1, 1, 2, 1, 6, 5, 9, 1, 4, 0, 0, 2, 4, 6, 2, 6, 7, 2, 8),
  group = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4)
)

p<- ggplot(data=dat, aes(x=time, y=frequency,group=group, color=as.factor(group) )) +
  geom_line() +
  geom_point() +
  scale_color_manual(breaks = c("1", "2", "3", "4"),
                     values=c("slateblue", "darkgoldenrod", "darkgreen", "chocolate")) +
  xlab("Year") + ylab("Number of publications") + theme_bw() +

guides(shape = FALSE, linetype = FALSE,
       colour = guide_legend(override.aes =  list(shape = c(16, 16, 16,  16),
                                                  linetype = c("solid","solid","solid", "solid"),
                                                  labels= c("All articles","Performance","Correctness","Fault tolerance"),
                                                  title = "Category"
       )))

p +   geom_vline(xintercept=as.numeric(2012), linetype="dotted", color="red", size=3)

There are other problems that I have with both codes (that's why I have two different codes), like not being able to order the legend on the first code, or the color is wrong for some reason. The second graph I can't replace the legend text for some reason, but the vertical line is the main problem right now.

Body:
I changed the way you created the time column from factor to numeric as follows.

dat <- data.frame(
  time = 2007:2016,
  #frequency = c(3, 8, 20, 26, 30, 38,29, 27, 13, 1)
  frequency = c(3, 8, 22, 29, 29, 37, 29, 33, 19, 30),
  frequency_performance = c(3, 7, 20, 22, 19, 29, 18, 15, 16, 18),
  frequency_correctness = c(0, 1, 1, 2, 1, 6, 5, 9, 1, 4),
  frequency_fault = c(0, 0, 2, 4, 6, 2, 6, 7, 2, 8)
)

Now it works. In the following code I also change the line size to 2 for clarity.

p <- ggplot(data=dat, aes(x=time)) + #, y=frequency, group=1)) +
  theme(aspect.ratio=.4,text = element_text(size=13),
        panel.grid.major = element_line(colour = "grey"),
        panel.border = element_rect( fill = NA),
        panel.background = element_rect(fill = "white", colour = "grey")) +
  geom_line(aes(y=frequency, colour="slateblue"),group=1, size=1.5) +
  geom_line(aes(y=frequency_performance, colour="darkgoldenrod"),group=1, size=1.5) +
  geom_line(aes(y=frequency_correctness, colour="darkgreen"),group=1, size=1.5) +
  geom_line(aes(y=frequency_fault, colour="chocolate"),group=1, size=1.5) +
  xlab("Year") + ylab("Number of publications") + # Set axis labels
  scale_color_discrete(name = "Category", labels = c("Fault tolerance", "Performance", "Correctness", "All papers")) +
  ggtitle("")

p +   geom_vline(xintercept=c(2010,2012,2014,2016),
                 linetype="dotted",
                 color="red",
                 size = 2)


问:
Retrieve next to last date SQL Server
I think this is a simple problem but I cannot find an easy answer. I need to retrieve the last 2 entries by date. I have used max() to get the latest date; but do not know how to retrieve the next most recent.

The stored procedure code for latest date is:

```<code>SELECT *
FROM Table
WHERE Date=(SELECT MAX(Date) FROM Table);
</code>```

So using a separate procedure how do I get the next most recent?

答:
Or just to get the next most recent only as you stated...thus returning only one row...

```<code>select top 1 t.*
from t
where t.date != (select max(date) from table)
order by date desc;
</code>```

or...

```<code>with cte as(
select
   t.*
   ,row_number() over (order by t.date desc) as RN
from table t)

select *
from cte
where RN = 2
</code>```

Title: Retrieve next to last date SQL Server

Body:
I think this is a simple problem but I cannot find an easy answer. I need to retrieve the last 2 entries by date. I have used max() to get the latest date; but do not know how to retrieve the next most recent.

The stored procedure code for latest date is:

SELECT *
FROM Table
WHERE Date=(SELECT MAX(Date) FROM Table);

So using a separate procedure how do I get the next most recent?

Body:
Or just to get the next most recent only as you stated...thus returning only one row...

select top 1 t.*
from t
where t.date != (select max(date) from table)
order by date desc;

or...

with cte as(
select
   t.*
   ,row_number() over (order by t.date desc) as RN
from table t)

select *
from cte
where RN = 2


问:
IOError for import MNIST datasets
I followed the TensorFlow tutorial for import MNIST datasets，i run those commands:

```<code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
</code>```

then it shows error:

```<code>anaconda2/lib/python2.7/gzip.pyc
IOError: Not a gzipped file
</code>```

I am new to python and tensorflow, and I don't understand what it means, thanks for any help.

My system is ubuntu，run on Ipython 5.1.0.

答:
What it Means:

It means it is looking in the MNIST_data directory and the files it is looking at are not gzip files.  More specifically, it more than likely just means it looked in the directory and couldn't find the files in this case. This could be due to a variety of reasons. I believe in my case for some reason it just wasn't downloading the files when it found the files didn't exist in the MNIST_data directory.

I had this exact problem and it was quite annoying.

Solution:

Get the data via your browser directly from using curl in your console.

```<code>curl -O http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
</code>```

Put the data in your root tmp directory.  I put it in
/tmp/tensorflow/mnist/input_data but you can put it anywhere you want to put it.

Then alter your line to get the mnist data with the directory matching where you put the data.

```<code>mnist = input_data.read_data_sets('tmp/tensorflow/mnist/input_data', one_hot=True)
</code>```

My Environment: (in case that starts to matter for you)

tensorflow pip installed within a virtualenv

python 2.7.10

tensorflow==1.4.0

MacOS Sierra

Title: IOError for import MNIST datasets

Body:
I followed the TensorFlow tutorial for import MNIST datasets，i run those commands:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

then it shows error:

anaconda2/lib/python2.7/gzip.pyc
IOError: Not a gzipped file

I am new to python and tensorflow, and I don't understand what it means, thanks for any help.

My system is ubuntu，run on Ipython 5.1.0.

Body:
What it Means:

It means it is looking in the MNIST_data directory and the files it is looking at are not gzip files.  More specifically, it more than likely just means it looked in the directory and couldn't find the files in this case. This could be due to a variety of reasons. I believe in my case for some reason it just wasn't downloading the files when it found the files didn't exist in the MNIST_data directory.

I had this exact problem and it was quite annoying.

Solution:

Get the data via your browser directly from using curl in your console.

curl -O http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
curl -O http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz

Put the data in your root tmp directory.  I put it in
/tmp/tensorflow/mnist/input_data but you can put it anywhere you want to put it.

Then alter your line to get the mnist data with the directory matching where you put the data.

mnist = input_data.read_data_sets('tmp/tensorflow/mnist/input_data', one_hot=True)

My Environment: (in case that starts to matter for you)

tensorflow pip installed within a virtualenv

python 2.7.10

tensorflow==1.4.0

MacOS Sierra


问:
Creating a container with a slanted edge
I have a client who requested the following in his design:

What is the easiest way to create the yellow container, with the slanted edge on the bottom? Can I do it within the interface builder or do I have to do it programatically? I'm trying to do this in swift.

答:
Can I do it within the interface builder or do I have to do it programmatically?

You'll have to do this programmatically: Define the UIBezierPath, using it as the path of a CAShapeLayer and then mask the view's layer using this shape layer.

```<code>@IBDesignable
class SlantedView: UIView {

    @IBInspectable var slantHeight: CGFloat = 50 { didSet { updatePath() } }

    private let shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 0
        shapeLayer.fillColor = UIColor.white.cgColor    // with masks, the color of the shape layer doesn’t matter; it only uses the alpha channel; the color of the view is dictate by its background color
        return shapeLayer
    }()

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }

    private func updatePath() {
        let path = UIBezierPath()
        path.move(to: bounds.origin)
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY - slantHeight))
        path.close()
        shapeLayer.path = path.cgPath
        layer.mask = shapeLayer
    }
}
</code>```

But by making this an @IBDesignable view, you can then render it in IB so you can at least design the UI with a greater sense of what the final product will look like:

FYI, if you do make this designable, they recommend that you create a separate framework target for your designables (so that if you go to IB while working on your main project, the ability to render the designable views isn't impacted by the fact that your main project may not be in a stable, compilable state).

Body:
Can I do it within the interface builder or do I have to do it programmatically?

You'll have to do this programmatically: Define the UIBezierPath, using it as the path of a CAShapeLayer and then mask the view's layer using this shape layer.

@IBDesignable
class SlantedView: UIView {

    @IBInspectable var slantHeight: CGFloat = 50 { didSet { updatePath() } }

    private let shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = 0
        shapeLayer.fillColor = UIColor.white.cgColor    // with masks, the color of the shape layer doesn’t matter; it only uses the alpha channel; the color of the view is dictate by its background color
        return shapeLayer
    }()

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }

    private func updatePath() {
        let path = UIBezierPath()
        path.move(to: bounds.origin)
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
        path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
        path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY - slantHeight))
        path.close()
        shapeLayer.path = path.cgPath
        layer.mask = shapeLayer
    }
}

But by making this an @IBDesignable view, you can then render it in IB so you can at least design the UI with a greater sense of what the final product will look like:

FYI, if you do make this designable, they recommend that you create a separate framework target for your designables (so that if you go to IB while working on your main project, the ability to render the designable views isn't impacted by the fact that your main project may not be in a stable, compilable state).


问:
Height of sidebar 100% not working
I just can't get the sidebar to work with a full height underneath the header/nav and above the footer.

```<code><html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <header>
      <div class="header">
        <div class="row">
          <div class="col-3">
            <img src="img/logo.png" alt="test">
          </div>
          <div class="col-6">
            <h1>Music</h1>
          </div>
          <div class="col-3">
            <button>sign in</button>
            <button>sign up</button>
          </div>
        </div><!-- end row -->
        <nav>
          <ul>
            <li><a href="#" class="active">home</a></li>
            <li><a href="#">genres</a></li>
            <li><a href="#">artists</a></li>
            <li><a href="#">about</a></li>
            <li><a href="#">contact</a></li>
          </ul>
        </nav>
      </div><!-- end header -->
    </header>
    <main>
      <div class="row">
        <div class="col-9">
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
          <p>test1</p>
        </div>
        <div class="col-3 sidebar">
          <p>test2</p>
        </div>
      </div>
    </main>
    <footer><p>Here comes the footer at the bottom of the page with 100% width</p></footer>
  </body>
</html>
</code>```

Here are my HTML and CSS. I hope someone knows what the solution is.
https://codepen.io/Midoriakwa/pen/wPqzZv

答:
Your sidebar (col-3 sidebar) , has a parent element, classed row.

The row element has no explicit height set, so height: 100% won't work on the child element (col-3 sidebar).

When using height: 100%, you are saying something along the lines of:

Use 100% of the parent's height

If the parent has no height, nothing will happen.

See this question for more clarity.

Title: Height of sidebar 100% not working

Body:
I just can't get the sidebar to work with a full height underneath the header/nav and above the footer.

    <meta charset="utf-8">

Music

            <button>sign in</button>
            <button>sign up</button>

home

genres

artists

about

contact

test1

test1

test1

test1

test1

test1

test1

test1

test1

test1

test1

test1

test2

Here comes the footer at the bottom of the page with 100% width

Here are my HTML and CSS. I hope someone knows what the solution is.
https://codepen.io/Midoriakwa/pen/wPqzZv


问:
How to track changes of my Linux distrib with git?
I am experimenting some linux configuration and I want to track my changes? Of course I don't want to to put my whole OS under version control?

Is there a way (with git, mercurial or any VCS) to track the change without storing the whole OS?

This is what I imagine:

I do a kind of git init -> all hashes of all files are stored, but not the content of the files

I make some changes to my file system -> git detect that the hash of this file has changed

I commit -> the content of the file is stored (or even better the original file and the diff are stored! I know, that is impossible... )

Possible? Impossible? Work-arounds?

EDIT: What I care about is just to minimize the size of the repository and to have a repository containing only my changes. Having all files in my repository is not relevant for me. For example if i push to github I just want it to contain only the files that has changed.

答:
I know this question is old, but I thought this might help someone. Inspired by @Jonathon's comment on the How to record concrete modification of specific files question, I have created a shell script that enables you to monitors all the changes done on a specific file, while keeping all the changes history. the script depends on the inotifywait and git packages being installed.

You can find the script here
https://github.com/hisham-hassan/linux-file-monitor

```<code>Usage: file-monitor.sh [-f|--file] <absolute-file-path> [-m|--monitor|-h|--history]
       file-monitor.sh --help

 -f,--file <absolute-file-path> Adding a file to the monitored files List. The <absolute-file-path>
                                is the absolute file path of the file we need to action.
                                PLEASE NOTE: Relative file path could cause issues in the script,
                                please make sure to use the abolute path of the file. also try to
                                avoid sym links, as it has not been tested.
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -m
 -m, --monitor                  Monitoring all the changes on the file. the monitoring will keep
                                happening as long as the script is running; you may need to run it
                                in the background.
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -m
 -h, --history                  showing the full history of the file.
                                To exit, press "q"
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -h
 --uninstall                    uninstalls the script from the bin direcotry,
                                and removes the monitoring history.
 --install                      Adds the script to the bin directory, and creates
                                the directories and files needed for monitoring.
 --help                         Prints this help message.
</code>```

Body:
I know this question is old, but I thought this might help someone. Inspired by @Jonathon's comment on the How to record concrete modification of specific files question, I have created a shell script that enables you to monitors all the changes done on a specific file, while keeping all the changes history. the script depends on the inotifywait and git packages being installed.

You can find the script here
https://github.com/hisham-hassan/linux-file-monitor

Usage: file-monitor.sh [-f|--file] <absolute-file-path> [-m|--monitor|-h|--history]
       file-monitor.sh --help

 -f,--file <absolute-file-path> Adding a file to the monitored files List. The <absolute-file-path>
                                is the absolute file path of the file we need to action.
                                PLEASE NOTE: Relative file path could cause issues in the script,
                                please make sure to use the abolute path of the file. also try to
                                avoid sym links, as it has not been tested.
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -m
 -m, --monitor                  Monitoring all the changes on the file. the monitoring will keep
                                happening as long as the script is running; you may need to run it
                                in the background.
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -m
 -h, --history                  showing the full history of the file.
                                To exit, press "q"
                                example: file-monitor.sh -f /absolute/path/to/file/test.txt -h
 --uninstall                    uninstalls the script from the bin direcotry,
                                and removes the monitoring history.
 --install                      Adds the script to the bin directory, and creates
                                the directories and files needed for monitoring.
 --help                         Prints this help message.


问:
Setting a dev and prod build with AWS credentials in Xcode?
I have a dev and prod cognito pool, a dev/prod lambda function that pushes to a dev/prod dynamoDb table.

Is there a simple way to have it know when to use the prod credentials (pool id, etc), and when to use the dev credentials?

And same to do with firing the appropriate dev/prod API gateway apis that check the appropriate pools for authentication, and post to the appropriate dynamoDb tables? For now I just manually change the tokens, and in API Gateway, I manually switch out which cognito pool the API gateway authenticates and which tables they post to, which isn't very practical.

答:
If you expose your lambda with API Gateway then just deploy it to two stages - a prod stage which calls the prod lambda which accesses prod Dynamodb & a dev stage which calls dev lambda. In your application, you would just need to change the stage name & you can do so by setting it from Info.plist.

Regarding how to get tokens for prod or dev automatically, it depends on how you get these tokens. For example, you could create a /login resource in API Gateway which takes username + password as parameters and returns tokens. Again, deploy it to two stages which use different Cognito pool in the backend calls. Now, you can use the same variable/property in your application to get the stage name for getting tokens too.

So, by just changing the value of one property you can switch between prod & dev in your app.


问:
Recursive JavaScript function is losing the return value
I want to search a string in a nested JSON object. If the string found in an object, I need to return that object.

I am using a recursive function to achieve this. The problem is, the function is recursing until the end and not returning the object found.

Please see the entire code in jsfiddle

```<code>function search(obj, name) {
    console.log(obj["name"], ",", name, obj["name"] == name);

    if (obj["name"] == name) {
        return obj; //NOT RETURNING HERE
    }
    if (obj.children || obj._children) {
        var ch = obj.children || obj._children;
        //console.log(ch);
        ch.forEach(function(val) {
            search(val, name)
        });
    }
    return -1;
}

search(myJson, "VM10-Proc4")
</code>```

I am not sure what is going wrong.

答:
I know this is an old post, but I can see 2 issues with this:

1) the recursive call isn't returning the result up the call stack i.e.

```<code>search(val, name)
</code>```

Should be

```<code>return search(val, name)
</code>```

2) it looks like you are using array.forEach(). The documentation states:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

What this means is, effectively, when you find the result you are looking for you want to send it back up the call stack. Using array.forEach will continue to recursively look through the hierarchy and return all values, not just the one you are interested in. Therefore the last returned value maybe one you don't expect, like undefined! Therefore use a different method of iterating i.e.

```<code>    for (var i = 0; i < ch.length; i++) {
        var val = ch[i];
        return search(val, name, ret);
    }
</code>```

The accepted answer does spoon feed you part of this answer but doesn't explain why. Hence this answer

Body:
I want to search a string in a nested JSON object. If the string found in an object, I need to return that object.

I am using a recursive function to achieve this. The problem is, the function is recursing until the end and not returning the object found.

Please see the entire code in jsfiddle

function search(obj, name) {
    console.log(obj["name"], ",", name, obj["name"] == name);

    if (obj["name"] == name) {
        return obj; //NOT RETURNING HERE
    }
    if (obj.children || obj._children) {
        var ch = obj.children || obj._children;
        //console.log(ch);
        ch.forEach(function(val) {
            search(val, name)
        });
    }
    return -1;
}

search(myJson, "VM10-Proc4")

I am not sure what is going wrong.

Body:
I know this is an old post, but I can see 2 issues with this:

1) the recursive call isn't returning the result up the call stack i.e.

search(val, name)

Should be

return search(val, name)

2) it looks like you are using array.forEach(). The documentation states:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

What this means is, effectively, when you find the result you are looking for you want to send it back up the call stack. Using array.forEach will continue to recursively look through the hierarchy and return all values, not just the one you are interested in. Therefore the last returned value maybe one you don't expect, like undefined! Therefore use a different method of iterating i.e.

    for (var i = 0; i < ch.length; i++) {
        var val = ch[i];
        return search(val, name, ret);
    }

The accepted answer does spoon feed you part of this answer but doesn't explain why. Hence this answer


问:
VBscript Can't Find Excel File
I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?</p>

```<code>Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")

Set objExcel = Nothing
Set objWorkbook = Nothing
</code>```

答:
As mentioned in the comments

In 9 out of 10 cases, this is permission related

The likeihood is (if you have already confirmed the file path is correct) that the VBScript does not have the permission required to access the file path, but due to the way elevation works along with UAC on most Windows Operating Systems means that VBScript doesn't know about the path, so it isn't reported as a access permission error.

As the path in question refers to a User Profile path the chances of it being permissions related increases.

To fix the problem the host process running the VBScript (wscript.exe or cscript.exe) needs to be run using elevated privileges. You can do this by opening an elevated command prompt (Run as Administrator context menu option) and specifying the host process followed by the script path.

Something like;

cscript.exe "yourscript.vbs"
```

Title: VBscript Can't Find Excel File

Body:
I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")

Set objExcel = Nothing
Set objWorkbook = Nothing


问:
How can I make Sublime Text the default editor for Git?
I have a problem setting Sublime Text 2 as the core.editor with git.

I've read through every post I could find addressing the problem, but still nothing is working for me. I am running Windows.

I have done:

```<code>git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
</code>```

and tried that with various arguments like -m.  When I open my .gitconfig, this is what is in there:

```<code>[user]
    name = Spencer Moran
    email = smoran02@gmail.com
[core]
    editor = 'C:/Program Files/Sublime Text 2/sublime_text.exe'
</code>```

If I go to Git and type:

```<code>README.markdown --edit
</code>```

the README file opens in Notepad, not Sublime Text.

Does anyone have any idea what I'm doing wrong or how I could fix this?

答:
For Mac & Sublime Text 3:

If git config --global core.editor "subl -n -w" doesn't work, use this git config command:

```<code>$ git config --global core.editor "'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl' -n -w"
</code>```

Note: it does not contain escaping backslashes.

Body:
I have a problem setting Sublime Text 2 as the core.editor with git.

I've read through every post I could find addressing the problem, but still nothing is working for me. I am running Windows.

I have done:

git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"

and tried that with various arguments like -m.  When I open my .gitconfig, this is what is in there:

[user]
    name = Spencer Moran
    email = smoran02@gmail.com
[core]
    editor = 'C:/Program Files/Sublime Text 2/sublime_text.exe'

If I go to Git and type:

README.markdown --edit

the README file opens in Notepad, not Sublime Text.

Does anyone have any idea what I'm doing wrong or how I could fix this?

Body:
For Mac & Sublime Text 3:

If git config --global core.editor "subl -n -w" doesn't work, use this git config command:

$ git config --global core.editor "'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl' -n -w"

Note: it does not contain escaping backslashes.


问:
Akamai cache clear/refresh and its APIs
We're using Akamai system as CDN and using Cache Clear/purging function of it to clear the cached assets. Whenever we deploy static/any content on Apache we do manual cache clear from Akamai portal. This manual activity is missed sometimes. We're looking for some options wherein once deployment is done it triggers the Akamai cache clear.

Is there any API available in Akamai which we can utilize for this purpose?

答:
Akamai does provide an API for clearing the cache. It's called the Content Control Utility v3. There are several other versions of the Purge API set, but the CCU v3 is the recommended API against which you should work.

If you require any assistance in implementing that particular API, Akamai also maintains a Customer Community where you can work directly with Akamai employees.

Title: Akamai cache clear/refresh and its APIs


问:
How to close searchView in onOptionsItemSelected(MenuItem item) when onBackPressed don't work?
Need code to close the searchView when BACK is pressed. So far only have code that closes the keyboard when BACK is pressed.

```<code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   if (item.getItemId() == android.R.id.home) {

       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
       View view = this.getCurrentFocus();
       if (view != null) {
           imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    return super.onOptionsItemSelected(item);
     }
</code>```

I tried the following line but this line closes the entire app for some reason when "back" clicked on...

```<code> onBackPressed();
</code>```

The following line is deprecated...

```<code>   MenuItemCompat.collapseActionView(menuItem);
</code>```

I've seen some answers on stackOverflow but most of them have to do with onBackPressed() or adding searchView.collapseActionView().
But I can't add searchView in onOptionsItemSelected(MenuItem item) unless I redeclare it with SearchView searchView = (SearchView) item.getActionView(); and then add searchView.collapseActionView() but then the app crashes when BACK pressed.

I got the keyboard to close but how do I close the searchView in onOptionsItemSelected(MenuItem item) ?

EDIT:

When I use onBackPressed() or super.onBackPressed() or this.onBackPressed(), the first time I click on "back" button, searchView and keyboard close, but when I click on search Icon again to open searchView and keyboard pops up, if I click on "back" again, the entire app closes, not crashes, just closes and takes me to Android Phone home screen. Why is this happening?

答:
Update

```<code> @Override
    public void onBackPressed() {
        if (!yourSearhView.isIconified()) {
            yourSearhView.onActionViewCollapsed();
        } else {
            super.onBackPressed();
        }
    }
</code>```

This won't work if the you have set app:showAsAction="always"

Body:
Need code to close the searchView when BACK is pressed. So far only have code that closes the keyboard when BACK is pressed.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   if (item.getItemId() == android.R.id.home) {

       InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
       View view = this.getCurrentFocus();
       if (view != null) {
           imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
    return super.onOptionsItemSelected(item);
     }

I tried the following line but this line closes the entire app for some reason when "back" clicked on...

 onBackPressed();

The following line is deprecated...

   MenuItemCompat.collapseActionView(menuItem);

I've seen some answers on stackOverflow but most of them have to do with onBackPressed() or adding searchView.collapseActionView().
But I can't add searchView in onOptionsItemSelected(MenuItem item) unless I redeclare it with SearchView searchView = (SearchView) item.getActionView(); and then add searchView.collapseActionView() but then the app crashes when BACK pressed.

I got the keyboard to close but how do I close the searchView in onOptionsItemSelected(MenuItem item) ?

EDIT:

When I use onBackPressed() or super.onBackPressed() or this.onBackPressed(), the first time I click on "back" button, searchView and keyboard close, but when I click on search Icon again to open searchView and keyboard pops up, if I click on "back" again, the entire app closes, not crashes, just closes and takes me to Android Phone home screen. Why is this happening?

Body:
Update

 @Override
    public void onBackPressed() {
        if (!yourSearhView.isIconified()) {
            yourSearhView.onActionViewCollapsed();
        } else {
            super.onBackPressed();
        }
    }

This won't work if the you have set app:showAsAction="always"


问:
How to: A scenebreak in bookdown
I'm trying to write a novel using bookdown: HTML, EPUB, as well as PDF (pdfLaTeX). I'm using the indent mode, so paragraphs begin with an indent. I have the following custom LaTeX command, called \scenebreak, which:

Leaves an empty line between paragraphs when the scene changes within a chapter.

Introduces a ding, if the scene break is at the end of a page, or the beginning of a page.

Resets indent for the paragraph that follows the break (the paragraph that follows the break starts flush left).

Here's the LaTeX:

```<code>% scene breaks
\renewcommand{\pfbreakdisplay}{%
\scriptsize\ding{86}}
\newcommand{\scenebreak}{\pfbreak*\noindent}
\newcommand{\forceindent}{\leavevmode{\indent}}
</code>```

When introducing the scenebreak in LaTeX, I call it so

```<code>Text here

\scenebreak

New scene begins here.
</code>```

In HTML, this is how I've done it:

```<code><div style='text-align:center;'>•</div>
</code>```

I'm aware that a block in bookdown is like a LaTeX environment.

Is a similar setup possible with commands/macros?

答:
I don't really understand your question, but if you are trying to write out different content depending on the different output format, here is what you could do:

```<code>```{r echo=FALSE}
knitr::asis_output(if (knitr:::is_latex_output()) {
  "\\scenebreak"
} else {
  "
•
"
})
```
</code>```

If you have to do this multiple times, create a function and call the function instead, e.g., insert this code chunk in the beginning of your book:

```<code>```{r, include=FALSE}
scenebreak = function() {
  knitr::asis_output(if (knitr:::is_latex_output()) {
    "\\scenebreak"
  } else {
    "
•
"
  })
}
```
</code>```

Then use the function scenebreak() where a break is needed:

```<code>```{r echo=FALSE}
scenebreak()
```
</code>```

Title: How to: A scenebreak in bookdown

Body:
I'm trying to write a novel using bookdown: HTML, EPUB, as well as PDF (pdfLaTeX). I'm using the indent mode, so paragraphs begin with an indent. I have the following custom LaTeX command, called \scenebreak, which:

Leaves an empty line between paragraphs when the scene changes within a chapter.

Introduces a ding, if the scene break is at the end of a page, or the beginning of a page.

Resets indent for the paragraph that follows the break (the paragraph that follows the break starts flush left).

Here's the LaTeX:

% scene breaks
\renewcommand{\pfbreakdisplay}{%
\scriptsize\ding{86}}
\newcommand{\scenebreak}{\pfbreak*\noindent}
\newcommand{\forceindent}{\leavevmode{\indent}}

When introducing the scenebreak in LaTeX, I call it so

Text here

\scenebreak

New scene begins here.

In HTML, this is how I've done it:

•

I'm aware that a block in bookdown is like a LaTeX environment.

Is a similar setup possible with commands/macros?

Body:
I don't really understand your question, but if you are trying to write out different content depending on the different output format, here is what you could do:

```{r echo=FALSE}
knitr::asis_output(if (knitr:::is_latex_output()) {
  "\\scenebreak"
} else {
  "<div style='text-align:center;'>&#8226;</div>"
})
```

If you have to do this multiple times, create a function and call the function instead, e.g., insert this code chunk in the beginning of your book:

```{r, include=FALSE}
scenebreak = function() {
  knitr::asis_output(if (knitr:::is_latex_output()) {
    "\\scenebreak"
  } else {
    "<div style='text-align:center;'>&#8226;</div>"
  })
}
```

Then use the function scenebreak() where a break is needed:

```{r echo=FALSE}
scenebreak()
```


问:
Marklogic 9.0-3 REST Parameters accessing in REST extensions
I have a REST extension and I have beeing accessing the parameters that have been passed, both in GET and POST as follows.. The parameters are passed as form-data or x-www-form-urlencoded. In my REST extension I would access the parameters via xdmp:get-request-field("remoteURL").

In ML-8, this worked where in when calling the WS I would pass in the parameters as remoteURL and it worked..

Now in ML-9.0-3, it does not work, so I tried passing the parameters via rs:remoteURL and access in the REST extension as xdmp:get-request-field("remoteURL") and it fails, but when I access as xdmp:get-request-field("rs:remoteURL"). it works.. Did this got changed in ML-9.0-3 ?

Just for complete I am including my REST extension code as well

```<code>declare function repoTest:post($context as map:map, $params  as map:map,$input   as document-node()*) as document-node()*
{
  let $_ := xdmp:log("Inside the Repo Test POST")
  let $remoteURL :=xdmp:get-request-field("remoteURL")
  let $_ := xdmp:log($remoteURL)
  let $output := json:object()
  let $_ :=  map:put($output, "remoteURL", $remoteURL)
  return document { xdmp:to-json($output) }
};
</code>```

答:
The documented approach has always been to use the rs: prefix for user-defined parameters.

If parameters without the prefix were provided to the extension, that was unexpected.

Hoping that clarifies,

Body:
I have a REST extension and I have beeing accessing the parameters that have been passed, both in GET and POST as follows.. The parameters are passed as form-data or x-www-form-urlencoded. In my REST extension I would access the parameters via xdmp:get-request-field("remoteURL").

In ML-8, this worked where in when calling the WS I would pass in the parameters as remoteURL and it worked..

Now in ML-9.0-3, it does not work, so I tried passing the parameters via rs:remoteURL and access in the REST extension as xdmp:get-request-field("remoteURL") and it fails, but when I access as xdmp:get-request-field("rs:remoteURL"). it works.. Did this got changed in ML-9.0-3 ?

Just for complete I am including my REST extension code as well

declare function repoTest:post($context as map:map, $params  as map:map,$input   as document-node()*) as document-node()*
{
  let $_ := xdmp:log("Inside the Repo Test POST")
  let $remoteURL :=xdmp:get-request-field("remoteURL")
  let $_ := xdmp:log($remoteURL)
  let $output := json:object()
  let $_ :=  map:put($output, "remoteURL", $remoteURL)
  return document { xdmp:to-json($output) }
};