问:
How can I delete a JS created LI with a JS created button?
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

```<code>        <div class="entry-field">
          <label class="task-input" for="task-input">Task:</label>
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>
        </div>
        <section class="task-list">
          <h2>Task List</h2>
          <div class="list-wrap"></div>
            <ul class="item-log">
              <li class="list-item">
                <span class="item-text">this is the item</span>
                <button class="delete-btn">delete</button>
              </li>
            </ul>
          </div>
        </section>
      </main>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

</code>```

答:
JS Fiddle - Todo App

When creating applications where you must dynamically insert similar elements and track them by an ID system, I recommend a more organized approach to eliminate any confusion in your code.

For basic applications you can create custom classes that each have an element, template, ui, uiEventCallbacks, toggleUIEvents, and render methods. On each class, the element is going to be a main HTML element that contains the template markup. The render method parses the template text and assigns it to element.innerHTML. To instantiate the application, just create a new instance of the base class, render it, then append the element to body.

I created an Todo Application with your markup. There are TodoApp, Todos, and Todo classes. The TodoApp contains Todos, and Todos contain instances of Todo.

Todo

```<code>const Todo = class {
  constructor(settings) {
    this.settings = settings
  }
  get settings() { return this._settings }
  set settings(settings) { this._settings = settings }
  get element() {
    if(!this._element) {
      this._element = document.createElement('li')
      this._element.setAttribute('class', 'list-item')
      this._element.setAttribute('id', this.settings.id )
    }
    return this._element
  }
  get ui() { return {
    deleteButton: this.element.querySelectorAll(':scope > .delete-btn'),
  } }
  get uiEventCallbacks() { return {
    deleteButtonClick: (event) => {
      let customEvent = new CustomEvent('removeTodo', {
        bubbles: true,
        details: {
          id: this.settings.id
        }
      })
      this.element.dispatchEvent(
        customEvent
      )
    },
  } }
  remove() {
    this.element.parentElement.removeChild(this.element)
    }
  template() { return `
    <span>${this.settings.value}</span>
    <button class="delete-btn">Delete</button>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'

    ].forEach((eventMethod) => {
      this.ui.deleteButton.item(0)[eventMethod]('click', this.uiEventCallbacks.deleteButtonClick)
    })
  }
  render() {
    const template = this.template()
    this.element.innerHTML = template
    this.toggleUIEvents()
    return this
  }
}
</code>```

Todos

```<code>const Todos = class {
    constructor() {}
  get element() {
    if(!this._element) {
      this._element = document.createElement('section')
      this._element.setAttribute('class', 'task-list')
    }
    return this._element
  }
  get ui() { return {
    itemLog: this.element.querySelectorAll('.item-log')
  } }
  get uiEventCallbacks() { return {
    removeTodo: (event) => {
      console.log(event)
      this.removeTodo()
    },
  } }
  get todos() {
    this._todos = this._todos || []
    return this._todos
  }
  template() { return `
    <h2>Task List</h2>
    <div class="list-wrap">
      <ul class="item-log"></ul>
    </div>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'
    ].forEach((eventMethod) => {
      this.ui.itemLog.item(0)[eventMethod]('removeTodo', this.uiEventCallbacks.removeTodo)
    })
  }
  addTodo(data) {
    const todo = new Todo(data)
    this.todos.push(todo)
    this.ui.itemLog.item(0).appendChild(
      todo.render().element
    )
    return this
  }
  removeTodo(id) {
    let todoIndex = this.todos.reduce((_todoIndex, todo, todoIndex) => {
      if(todo.id === id) _todoIndex = todoIndex
      return _todoIndex
    }, -1)
    let todo = this.todos.splice(todoIndex, 1)[0]
    todo.remove()
    return this
  }
  render(data) {
    const template = this.template(data)
    this.element.innerHTML = template
    this.toggleUIEvents()
    return this
  }
}
</code>```

Todo Application

```<code>const TodoApp = class {
  constructor() {}
  get element() {
    if(!this._element) {
      this._element = document.createElement('main')
    }
    return this._element
  }
  get ui() { return {
    addButton: this.element.querySelectorAll('.add-btn'),
    input: this.element.querySelectorAll('.task-field'),
  } }
  get uiEventCallbacks() { return {
    addTodo: (event) => {
      let taskFieldData = this.ui.input.item(0).value
      this.todos.addTodo({
        id: this.uuid(),
        value: taskFieldData,
      })
    },
  } }
  get todos() {
    this._todos = this._todos || new Todos()
    return this._todos
  }
  uuid() {
    var uuid = '', i, random
    for (i = 0; i < 32; i++) {
      random = Math.random() * 16 | 0
      if (i === 8 || i === 12 || i === 16 || i === 20) {
        uuid += "-"
      }
      uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16)
    }
    return uuid
  }
  template() { return `
    <div class="entry-field">
      <label class="task-input" for="task-input">Task:</label>
      <input type="text" class="task-field" placeholder="Enter Item"/>
      <button class="add-btn">ADD</button>
    </div>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'
    ].forEach((eventMethod) => {
      this.ui.addButton.item(0)[eventMethod]('click', this.uiEventCallbacks.addTodo)
    })
  }
  render(data) {
    const template = this.template(data)
    this.element.innerHTML = template
    this.element.appendChild(this.todos.render().element)
    this.toggleUIEvents()
    return this
  }
}
</code>```

Instantiate Todo Application

```<code>const todoApp = new TodoApp()
const body = document.querySelector('body')
body.insertAdjacentElement('afterbegin', todoApp.render().element)
</code>```

Body:
I am creating a TODO app in JavaScript. How can I understand how to link two created JavaScript items and remove them from the DOM?

TL;DR: The place where I keep getting stuck is navigating the DOM after the list item has been created. I have tried to use a a setAttribute to the created elements with an incriminating "id" tag, but I still can figure out how to iterate over the LI's to find which button was pressed.

Code:

          Task:
          <input type="text" class="task-field" placeholder="Enter Item"/>
          <button class="add-btn">ADD</button>

Task List

                this is the item
                <button class="delete-btn">delete</button>

JavaScript:
let index = 0;

//Obtaining user text, creating a Span element, append span with user text:
function addItem() {
  let itemLog = document.querySelector(".item-log");
  let listItem = document.createElement("LI");
  let deleteBtn = document.createElement("BUTTON");
  let userEntry = document.querySelector(".task-field").value;
  let spanItem = document.createElement("SPAN");
  index++;
  //Creating LI "list-item" and append UL "itemLog"
  itemLog.appendChild(listItem);
  listItem.classList.add("list-item");

  listItem.setAttribute("id", index);
  //Create Span element, assign text from user input, append LI
  spanItem.innerHTML = userEntry;
  listItem.appendChild(spanItem);
  //Create deleteBtn and append to LI
  deleteBtn.innerHTML = "Delete";
  deleteBtn.classList.add("delete-btn");
  deleteBtn.setAttribute("onclick", "deleteItem()");
  deleteBtn.setAttribute("id", index);
  listItem.appendChild(deleteBtn);

  userEntry.value = "";
}

/*
2) Deleting item from list:
  -use event listener to trigger parent node
  -delete child
  */

function deleteItem() {
  let listItem = this.parentElement;
  listItem.parentElement.removeChild(listItem);
}

// Page event listeners
let addBtn = document.querySelector(".add-btn");

addBtn.addEventListener("click", addItem);

Body:
JS Fiddle - Todo App

When creating applications where you must dynamically insert similar elements and track them by an ID system, I recommend a more organized approach to eliminate any confusion in your code.

For basic applications you can create custom classes that each have an element, template, ui, uiEventCallbacks, toggleUIEvents, and render methods. On each class, the element is going to be a main HTML element that contains the template markup. The render method parses the template text and assigns it to element.innerHTML. To instantiate the application, just create a new instance of the base class, render it, then append the element to body.

I created an Todo Application with your markup. There are TodoApp, Todos, and Todo classes. The TodoApp contains Todos, and Todos contain instances of Todo.

Todo

const Todo = class {
  constructor(settings) {
    this.settings = settings
  }
  get settings() { return this._settings }
  set settings(settings) { this._settings = settings }
  get element() {
    if(!this._element) {
      this._element = document.createElement('li')
      this._element.setAttribute('class', 'list-item')
      this._element.setAttribute('id', this.settings.id )
    }
    return this._element
  }
  get ui() { return {
    deleteButton: this.element.querySelectorAll(':scope > .delete-btn'),
  } }
  get uiEventCallbacks() { return {
    deleteButtonClick: (event) => {
      let customEvent = new CustomEvent('removeTodo', {
        bubbles: true,
        details: {
          id: this.settings.id
        }
      })
      this.element.dispatchEvent(
        customEvent
      )
    },
  } }
  remove() {
    this.element.parentElement.removeChild(this.element)
    }
  template() { return `
    <span>${this.settings.value}</span>
    <button class="delete-btn">Delete</button>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'

    ].forEach((eventMethod) => {
      this.ui.deleteButton.item(0)[eventMethod]('click', this.uiEventCallbacks.deleteButtonClick)
    })
  }
  render() {
    const template = this.template()
    this.element.innerHTML = template
    this.toggleUIEvents()
    return this
  }
}

Todos

const Todos = class {
    constructor() {}
  get element() {
    if(!this._element) {
      this._element = document.createElement('section')
      this._element.setAttribute('class', 'task-list')
    }
    return this._element
  }
  get ui() { return {
    itemLog: this.element.querySelectorAll('.item-log')
  } }
  get uiEventCallbacks() { return {
    removeTodo: (event) => {
      console.log(event)
      this.removeTodo()
    },
  } }
  get todos() {
    this._todos = this._todos || []
    return this._todos
  }
  template() { return `
    <h2>Task List</h2>
    <div class="list-wrap">
      <ul class="item-log"></ul>
    </div>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'
    ].forEach((eventMethod) => {
      this.ui.itemLog.item(0)[eventMethod]('removeTodo', this.uiEventCallbacks.removeTodo)
    })
  }
  addTodo(data) {
    const todo = new Todo(data)
    this.todos.push(todo)
    this.ui.itemLog.item(0).appendChild(
      todo.render().element
    )
    return this
  }
  removeTodo(id) {
    let todoIndex = this.todos.reduce((_todoIndex, todo, todoIndex) => {
      if(todo.id === id) _todoIndex = todoIndex
      return _todoIndex
    }, -1)
    let todo = this.todos.splice(todoIndex, 1)[0]
    todo.remove()
    return this
  }
  render(data) {
    const template = this.template(data)
    this.element.innerHTML = template
    this.toggleUIEvents()
    return this
  }
}

Todo Application

const TodoApp = class {
  constructor() {}
  get element() {
    if(!this._element) {
      this._element = document.createElement('main')
    }
    return this._element
  }
  get ui() { return {
    addButton: this.element.querySelectorAll('.add-btn'),
    input: this.element.querySelectorAll('.task-field'),
  } }
  get uiEventCallbacks() { return {
    addTodo: (event) => {
      let taskFieldData = this.ui.input.item(0).value
      this.todos.addTodo({
        id: this.uuid(),
        value: taskFieldData,
      })
    },
  } }
  get todos() {
    this._todos = this._todos || new Todos()
    return this._todos
  }
  uuid() {
    var uuid = '', i, random
    for (i = 0; i < 32; i++) {
      random = Math.random() * 16 | 0
      if (i === 8 || i === 12 || i === 16 || i === 20) {
        uuid += "-"
      }
      uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)).toString(16)
    }
    return uuid
  }
  template() { return `
    <div class="entry-field">
      <label class="task-input" for="task-input">Task:</label>
      <input type="text" class="task-field" placeholder="Enter Item"/>
      <button class="add-btn">ADD</button>
    </div>
  ` }
  toggleUIEvents() {
    [
      'removeEventListener',
      'addEventListener'
    ].forEach((eventMethod) => {
      this.ui.addButton.item(0)[eventMethod]('click', this.uiEventCallbacks.addTodo)
    })
  }
  render(data) {
    const template = this.template(data)
    this.element.innerHTML = template
    this.element.appendChild(this.todos.render().element)
    this.toggleUIEvents()
    return this
  }
}

Instantiate Todo Application

const todoApp = new TodoApp()
const body = document.querySelector('body')
body.insertAdjacentElement('afterbegin', todoApp.render().element)


来源: stackexchange

问:
Printing utf8 characters from utf8 codes in Go
Problem:
I am trying to retrieve the value of a utf8 code designation.

let's say we have this situation:

```<code>//String with the alphabet and some numbers.
var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"
</code>```

I want to output the value of what a utf8 code is assigned to.

If a is 97 in the utf8 table. What function do I call to output the character 'a' if 97 is the utf8 code?

```<code>fmt.Println(aMess[0]) // outputs 97 how do I convert 97 to what it is assigned too?
</code>```

答:
If a is 97 in the utf8 table. What function do I call to output the
  character 'a' if 97 is the utf8 code?

```<code>fmt.Println(aMess[0])
</code>```

For your example,

```<code>package main

import (
    "fmt"
)

func main() {
    var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"
    fmt.Println(aMess[0])
    fmt.Println(string(rune(aMess[0])))
}
</code>```

Playground: https://play.golang.org/p/fbEPtQHe63e

Output:

```<code>97
a
</code>```

References:

proposal: spec: remove string(int) #3939

The Go Blog: Proposals for Go 1.15

#32479. Diagnose string(int) conversion in go vet.

ContentLicense: CC BY-SA 4.0

Body:
Problem:
I am trying to retrieve the value of a utf8 code designation.

let's say we have this situation:

//String with the alphabet and some numbers.
var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"

I want to output the value of what a utf8 code is assigned to.

If a is 97 in the utf8 table. What function do I call to output the character 'a' if 97 is the utf8 code?

fmt.Println(aMess[0]) // outputs 97 how do I convert 97 to what it is assigned too?

Body:
If a is 97 in the utf8 table. What function do I call to output the
  character 'a' if 97 is the utf8 code?

fmt.Println(aMess[0])

For your example,

package main

import (
    "fmt"
)

func main() {
    var aMess string = "abcdefghijklmnopqrstuvwxyz123456789"
    fmt.Println(aMess[0])
    fmt.Println(string(rune(aMess[0])))
}

Playground: https://play.golang.org/p/fbEPtQHe63e

Output:

97
a

References:

proposal: spec: remove string(int) #3939

The Go Blog: Proposals for Go 1.15

#32479. Diagnose string(int) conversion in go vet.


问:
How can I correctly parse array of JSON objects?
this is my data:

```<code>var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]
</code>```

I want to pass this data as a string via HTTP and then read it back as json, instead I'm getting [ '[object Object]', '[object Object]' ]

please assist.

答:
You should use JSON.parse to convert your JSON string to a javascript object.

JSON Object

```<code>var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]
</code>```

JSON String

```<code>var jsonString = JSON.stringify(data);
</code>```

JSON Object back again

```<code>var jsonObject = JSON.parse(jsonString);
</code>```

Body:
this is my data:

var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]

I want to pass this data as a string via HTTP and then read it back as json, instead I'm getting [ '[object Object]', '[object Object]' ]

please assist.

Body:
You should use JSON.parse to convert your JSON string to a javascript object.

JSON Object

var data = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "lllllllllllllllll": "sssssssssss", "ppppppppppp": null, "__typename": "xx" }, { "_id": "5e4595374bee49300c47e1ab", "xxTitle": "ggggggg", "hhhhhhhhhh": "ggggggg", "xxzzzzzz": "ggggggg", "oooooooooooooo": "ggggggg", "xxDescription": "ggggggg", "xxDetails": "ggggggg", "lllllllllllllllll": "ggggggg", "ppppppppppp": "ggggggg", "__typename": "xx" } ]

JSON String

var jsonString = JSON.stringify(data);

JSON Object back again

var jsonObject = JSON.parse(jsonString);


问:
Where can I learn ffmpeg?
I really want to get more into video/audio encoding and decoding, and I’ve heard that ffmpeg is a good tool, but I can’t find any good tutorials for it. Does anyone know a good way to learn it?</p>

答: I think this tutorial is very well written and illustrated https://github.com/leandromoreira/ffmpeg-libav-tutorial</p>

Title: Where can I learn ffmpeg?


问:
"Start by creating and opening a systemd socket file for Gunicorn with sudo privileges" (directory to this file does not *appear* to exist)
I am working on a server running ubuntu 18.04. This digital ocean tutorial on django deployment(https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04) is telling me to do the following:
"We’re now finished configuring our Django application. We can back out of our virtual environment by typing:

(env): deactivate" I am familiar with virtual environments, I did this. Now for the part I am not at all familiar with:
"Start by creating and opening a systemd socket file for Gunicorn with sudo privileges:

```<code>sudo nano /etc/systemd/system/gunicorn.socket
</code>```

"

First, since I just deactivated my env, I am now at justin@ubuntu-s-1vcpu-1gb-nyc3-01:~$. If I ls I only see the project folder I created which holds the virtualenv, the python project, manage.py and the static directory. Nowhere can I find this

```<code>/etc/systemd/system/
</code>```

directory and the command they are telling me to use cannot create directories, only files. So I am very confused, any help would be greatly appreciated.

答: /etc doesn't live inside ~. Try ls /etc to see what's already in that directory. If you need to create that directory, you can do so wih sudo mkdir -p /etc/systemd/system/ (the -p flag is to make sure that, in case systemd is also not present under etc, it will get created).

Body:
I am working on a server running ubuntu 18.04. This digital ocean tutorial on django deployment(https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04) is telling me to do the following:
"We’re now finished configuring our Django application. We can back out of our virtual environment by typing:

(env): deactivate" I am familiar with virtual environments, I did this. Now for the part I am not at all familiar with:
"Start by creating and opening a systemd socket file for Gunicorn with sudo privileges:

sudo nano /etc/systemd/system/gunicorn.socket

"

First, since I just deactivated my env, I am now at justin@ubuntu-s-1vcpu-1gb-nyc3-01:~$. If I ls I only see the project folder I created which holds the virtualenv, the python project, manage.py and the static directory. Nowhere can I find this

/etc/systemd/system/

directory and the command they are telling me to use cannot create directories, only files. So I am very confused, any help would be greatly appreciated.


问:
Inserting null values when seeding laravel app from json file
In my laravel app I have a json file I'm tying to use to seed some products into my database. For some reason when I try to save a product I'm inserting empty values for title and productcategory_id fields, even thought the array values are there, the json is transformed into an array with json_decode all right.

This is my logic:

```<code><?php
use Illuminate\Database\Seeder;
use App\Models\Product;

class ProductsSeeder extends Seeder
{

    public function run()
    {
        $json = File::get(base_path().'/json/Products.json');

        $products = json_decode($json, true);

        var_dump($products);

        foreach ($products as $product)
        {
            echo($product['title']);
            echo($product['productcategory_id']);
            $product = new Product();
            $product->title = $product['title'];
            $product->productcategory_id = $product['productcategory_id'];
            $product->save();
        }
    }
}
</code>```

An excerpt of my json file:

```<code>[
    { "productcategory_id" : 1, "title":"Hamb.Ternera Maxi"},
    { "productcategory_id" : 1, "title":"Hamb. Ternera Doble"},
    { "productcategory_id" : 1, "title":"Hamb. Pollo"},
    { "productcategory_id" : 1, "title":"Hamb. Mini"},
    { "productcategory_id" : 1, "title":"Camp. clásico"},
    { "productcategory_id" : 1, "title":"Camp. ternera"},
]
</code>```

As you can see I use var_dump to see the json data is converted correctly into php assoc array, bt I still get the error. Full error message in my shell is:

```<code>   Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `products` (`title`, `productcategory_id`, `updated_at`, `created_at`) values (, , 2020-02-16 20:25:51, 2020-02-16 20:25:51))

  at C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null")
      C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.
</code>```

答:
The problem is probably that you are using the same variable to loop and to get the value.
try like this:</p>

```<code>foreach ($products as $product)
    {
        echo($product['title']);
        echo($product['productcategory_id']);
        $product_n = new Product();
        $product_n->title = $product['title'];
        $product_n->productcategory_id = $product['productcategory_id'];
        $product_n->save();
    }
</code>```

Body:
In my laravel app I have a json file I'm tying to use to seed some products into my database. For some reason when I try to save a product I'm inserting empty values for title and productcategory_id fields, even thought the array values are there, the json is transformed into an array with json_decode all right.

This is my logic:

<?php
use Illuminate\Database\Seeder;
use App\Models\Product;

class ProductsSeeder extends Seeder
{

    public function run()
    {
        $json = File::get(base_path().'/json/Products.json');

        $products = json_decode($json, true);

        var_dump($products);

        foreach ($products as $product)
        {
            echo($product['title']);
            echo($product['productcategory_id']);
            $product = new Product();
            $product->title = $product['title'];
            $product->productcategory_id = $product['productcategory_id'];
            $product->save();
        }
    }
}

An excerpt of my json file:

[
    { "productcategory_id" : 1, "title":"Hamb.Ternera Maxi"},
    { "productcategory_id" : 1, "title":"Hamb. Ternera Doble"},
    { "productcategory_id" : 1, "title":"Hamb. Pollo"},
    { "productcategory_id" : 1, "title":"Hamb. Mini"},
    { "productcategory_id" : 1, "title":"Camp. clásico"},
    { "productcategory_id" : 1, "title":"Camp. ternera"},
]

As you can see I use var_dump to see the json data is converted correctly into php assoc array, bt I still get the error. Full error message in my shell is:

   Illuminate\Database\QueryException  : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `products` (`title`, `productcategory_id`, `updated_at`, `created_at`) values (, , 2020-02-16 20:25:51, 2020-02-16 20:25:51))

  at C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null")
      C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  2   PDOStatement::execute()
      C:\xampp\htdocs\dtcburger\vendor\laravel\framework\src\Illuminate\Database\Connection.php:458

  Please use the argument -v to see more details.

Body:
The problem is probably that you are using the same variable to loop and to get the value.
try like this:

foreach ($products as $product)
    {
        echo($product['title']);
        echo($product['productcategory_id']);
        $product_n = new Product();
        $product_n->title = $product['title'];
        $product_n->productcategory_id = $product['productcategory_id'];
        $product_n->save();
    }


问:
Python Equivalent to System('PAUSE')
I have been coding a basic calculator in python 3.3 and I want to be able to run it in command window.

but as soon as i get to the end it shuts the windows before I have time to view the final answer.

so I was wondering if there is an equivalent to the c++ System('PAUSE') command to tell it not to go any further until the user is ready.

Here is my calculator code:

```<code>print('Your Very Own Basic Calculator')
first_num = int(input('Please Enter The First Number: '))
second_num = int(input('Please Enter The Second Number: '))
Equation = input('What would you like to do, multiplication, division, subtraction or
if Equation == ('*'):
addition? *, /, -, +')
    print('The Answer is',first_num * second_num)
elif Equation == ("/"):
    print('The Answer is',first_num / second_num)
elif Equation == ('-'):
    print('The Answer is',first_num - second_num)
elif Equation == ('+'):
    print('The Answer is',first_num + second_num)
</code>```

thanks

答:
Here is a simple program to do math with,
A.  "input()" that basically wait's for the user to input a value and based on that value calculates the result, also u will see
B. While True: meaning the program never stops (or at least the user inputs 2 than asked to exit)
Finally some part is on Greek lang. (u will need to translate them)</p>

```<code>import os

# Reads a Float number
def read(thesi):
    try:
        ask_me = f'Δώσε μου τον {thesi} αριθμό'
        os.system(f"say '{ask_me}'")
        number_a = float(input())
        return number_a
    except KeyboardInterrupt:
        print('Ζητήθηκε άμεση έξοδος από το πρόγραμμα')
        quit()
    except ValueError:
        print('Σφάλμα:')
        return read(thesi)

def continue_exit():
    try:
        accept_only = ('1', '2')
        ask_me = '1. Continue   2. Exit the Program'
        os.system(f"say '{ask_me}'")
        number= input()
        if number in accept_only:
            return number
        else:
            print('Try again')
            return continue_exit()
    except KeyboardInterrupt:
        print('Ζητήθηκε άμεση έξοδος από το πρόγραμμα')
        quit()
    except ValueError:
        print('Σφάλμα:')
        return continue_exit()

# Reads the type of the equation
def equation_read():
    lst = ['+', '-', '/', '*', 'mod', 'pow', 'div']
    ask_me = f'μαθηματική πράξη?'
    os.system(f"say '{ask_me}'")
    print('Input --> +  -  /  * mod pow div ')
    equation = input()
    if equation in lst:
        return equation
    print('Σφάλμα')
    return equation_read()

# Checks and does the math
def math(a ,b ,eq):
    forbiden_zero_division = ('/', 'mode', 'div')
    if b == 0 and eq in forbiden_zero_division:
        ask_me = f'Σφάλμα: Δεν επιτρέπεται διαίρεση με το 0'
        os.system(f"say '{ask_me}'")
        return 'Division by 0!'
    if eq == '+':
        ask_me = f'Ζητήθηκε πρόσθεση:'
        os.system(f"say '{ask_me}'")
        return a + b
    elif eq == '-':
        ask_me = f'Ζητήθηκε αφαίρεση:'
        os.system(f"say '{ask_me}'")
        return a - b
    elif eq == '/':
        ask_me = f'Ζητήθηκε διαίρεση:'
        os.system(f"say '{ask_me}'")
        return a / b
    elif eq == '*':
        ask_me = f'Ζητήθηκε πολλαπλασιασμός:'
        os.system(f"say '{ask_me}'")
        return a * b
    elif eq == 'mod':
        ask_me = f'Ζητήθηκε το υπόλοιπο διάιρεσης:'
        os.system(f"say '{ask_me}'")
        return a % b
    elif eq == 'pow':
        ask_me = f'Ζητήθηκε η δύναμη:'
        os.system(f"say '{ask_me}'")
        return a ** b
    elif eq == 'div':
        ask_me = f'Ζητήθηκε ακέραιη διαίρεση:'
        os.system(f"say '{ask_me}'")
        return a // b

while True:
    a = read('πρώτο')  # Read the First Number
    b = read('δεύτερο')  # Read the Second Number
    eq = equation_read()  # Read the Type of the equation
    result = math(a, b, eq) # Do the math
    print(result)
    ask_me = f'Αποτέλεσμα {result}'
    os.system(f"say '{ask_me}'")
    c_e = continue_exit()
    if c_e == '2':
        break
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Equivalent to System('PAUSE')

Body:
I have been coding a basic calculator in python 3.3 and I want to be able to run it in command window.

but as soon as i get to the end it shuts the windows before I have time to view the final answer.

so I was wondering if there is an equivalent to the c++ System('PAUSE') command to tell it not to go any further until the user is ready.

Here is my calculator code:

print('Your Very Own Basic Calculator')
first_num = int(input('Please Enter The First Number: '))
second_num = int(input('Please Enter The Second Number: '))
Equation = input('What would you like to do, multiplication, division, subtraction or
if Equation == ('*'):
addition? *, /, -, +')
    print('The Answer is',first_num * second_num)
elif Equation == ("/"):
    print('The Answer is',first_num / second_num)
elif Equation == ('-'):
    print('The Answer is',first_num - second_num)
elif Equation == ('+'):
    print('The Answer is',first_num + second_num)

thanks

Body:
Here is a simple program to do math with,
A.  "input()" that basically wait's for the user to input a value and based on that value calculates the result, also u will see
B. While True: meaning the program never stops (or at least the user inputs 2 than asked to exit)
Finally some part is on Greek lang. (u will need to translate them)

import os

# Reads a Float number
def read(thesi):
    try:
        ask_me = f'Δώσε μου τον {thesi} αριθμό'
        os.system(f"say '{ask_me}'")
        number_a = float(input())
        return number_a
    except KeyboardInterrupt:
        print('Ζητήθηκε άμεση έξοδος από το πρόγραμμα')
        quit()
    except ValueError:
        print('Σφάλμα:')
        return read(thesi)

def continue_exit():
    try:
        accept_only = ('1', '2')
        ask_me = '1. Continue   2. Exit the Program'
        os.system(f"say '{ask_me}'")
        number= input()
        if number in accept_only:
            return number
        else:
            print('Try again')
            return continue_exit()
    except KeyboardInterrupt:
        print('Ζητήθηκε άμεση έξοδος από το πρόγραμμα')
        quit()
    except ValueError:
        print('Σφάλμα:')
        return continue_exit()

# Reads the type of the equation
def equation_read():
    lst = ['+', '-', '/', '*', 'mod', 'pow', 'div']
    ask_me = f'μαθηματική πράξη?'
    os.system(f"say '{ask_me}'")
    print('Input --> +  -  /  * mod pow div ')
    equation = input()
    if equation in lst:
        return equation
    print('Σφάλμα')
    return equation_read()

# Checks and does the math
def math(a ,b ,eq):
    forbiden_zero_division = ('/', 'mode', 'div')
    if b == 0 and eq in forbiden_zero_division:
        ask_me = f'Σφάλμα: Δεν επιτρέπεται διαίρεση με το 0'
        os.system(f"say '{ask_me}'")
        return 'Division by 0!'
    if eq == '+':
        ask_me = f'Ζητήθηκε πρόσθεση:'
        os.system(f"say '{ask_me}'")
        return a + b
    elif eq == '-':
        ask_me = f'Ζητήθηκε αφαίρεση:'
        os.system(f"say '{ask_me}'")
        return a - b
    elif eq == '/':
        ask_me = f'Ζητήθηκε διαίρεση:'
        os.system(f"say '{ask_me}'")
        return a / b
    elif eq == '*':
        ask_me = f'Ζητήθηκε πολλαπλασιασμός:'
        os.system(f"say '{ask_me}'")
        return a * b
    elif eq == 'mod':
        ask_me = f'Ζητήθηκε το υπόλοιπο διάιρεσης:'
        os.system(f"say '{ask_me}'")
        return a % b
    elif eq == 'pow':
        ask_me = f'Ζητήθηκε η δύναμη:'
        os.system(f"say '{ask_me}'")
        return a ** b
    elif eq == 'div':
        ask_me = f'Ζητήθηκε ακέραιη διαίρεση:'
        os.system(f"say '{ask_me}'")
        return a // b

while True:
    a = read('πρώτο')  # Read the First Number
    b = read('δεύτερο')  # Read the Second Number
    eq = equation_read()  # Read the Type of the equation
    result = math(a, b, eq) # Do the math
    print(result)
    ask_me = f'Αποτέλεσμα {result}'
    os.system(f"say '{ask_me}'")
    c_e = continue_exit()
    if c_e == '2':
        break


问:
Getting error: Missing Authentication Token after AWS API request
I am trying to call a Lambda Function through AWS API Gateway.

I've been getting this error when I tried IAM authentication, API Key Authentication and also with no authentication.

```<code>{"message":"Missing Authentication Token"}
</code>```

Some people had the same problem due to non existing endpoint. However, I've taken my endpoint directly from the Lambda Function AWS Console.

I've been trying to open the URL in the Browser and also on the Postman (with and without a header authentication: x-api-key: *****************).

Both responded with above stated error.

答: Just wanted to mention that if you set your API gateway's authentication to be NONE, make sure you need to Deploy API first before the no authentication setting is in effect.

Body:
I am trying to call a Lambda Function through AWS API Gateway.

I've been getting this error when I tried IAM authentication, API Key Authentication and also with no authentication.

{"message":"Missing Authentication Token"}

Some people had the same problem due to non existing endpoint. However, I've taken my endpoint directly from the Lambda Function AWS Console.

I've been trying to open the URL in the Browser and also on the Postman (with and without a header authentication: x-api-key: *****************).

Both responded with above stated error.


问:
Ready event for templates
In JsViews i can bind events in the following way:

```<code><li id="myElement" data-link="{on 'click' eventHandler}">Some Content</li>
</code>```

This will execute the method "eventHandler" after a click.
But I need an event which will be fired when the template is loaded. I tried "ready" or "show", but nothings works. Is there a event which can handle this?

答:
The {on xxx eventHandler} handles events on HTML elements, such as mouse events, submit, change, blur, etc.

With JsViews, the loading of the template happens directly as a result of your own code calling the link method. So elements in the rendered template will have been rendered during that call, and immediately after you can run whatever code you want to call after rendering and linking, such as using jQuery to find your
 element, and act on the element

JsViews also provides many life-cycle events on tags, so if you want you can create a custom tag just for handling those events:

For example, try running the following code:

```

Title: Ready event for templates

Body:
In JsViews i can bind events in the following way:

Some Content

This will execute the method "eventHandler" after a click.
But I need an event which will be fired when the template is loaded. I tried "ready" or "show", but nothings works. Is there a event which can handle this?

Body:
The {on xxx eventHandler} handles events on HTML elements, such as mouse events, submit, change, blur, etc.

With JsViews, the loading of the template happens directly as a result of your own code calling the link method. So elements in the rendered template will have been rendered during that call, and immediately after you can run whatever code you want to call after rendering and linking, such as using jQuery to find your <li> element, and act on the element

JsViews also provides many life-cycle events on tags, so if you want you can create a custom tag just for handling those events:

For example, try running the following code:

<span id="result"></span>

<script>
var data = {};

$.views.tags("test", {
  attr:"none",
    render: function(data) {
      debugger;
    },
    onBind: function(tagCtx, linkCtx) {
      var elem = this.parentElem;
      elem.textContent += " added text";
    }
  });

  var myTmpl = $.templates('<ul><li id="myElement" data-link="{test}">Some Content</li></ul>');

myTmpl.link("#result", data);

$("#myElement").css('color', 'red');
</script>


问:
How to push to google analytics page title on SPA
good evening everyone,

I'm trying to use GTM for analytics on my SPA website, I manage to get analytics working thanks to this post by @András Szepesházi: Google Tag Manager and Single Page apps, but i just realized that the page title isn't being pushed to analytics. I tried to created new variables but didn't manage to make it work. Any ideas how to do that?

Thanks

答:
Based on the example of your link, after creating the variables and managing the push on page change, you need to setup the Universal Analytics with 2 'Fields to Set':

'title' to {{DL-page title}}

'page' to {{DL - page url}}

In Google Tag Manager Analytics Tag you will have a situation like the following:

So you send both the page and the title with the same Analytics hit.


问:
Shifting Angles using Arctan2
I am currently building a pathing system for a game. I've recently figured out the whole Arctan2(Y,X) function to help with rotating the player to the next way-point. However after a lot of debugging I found out that the angle system used in-game isn't the same as a normal angle plan.

So the issue is the Arctan2(Y,X) function returns an angle that is approtate to the "normal" plan see on the right in the link above, But I need to convert that angle into a usable angle for the In-game angle plan... I hope I am explaining this somewhat decently.

Any advice would be greatly appreciated!

答:
By looking at your picture, it is clear that the mapping f that maps the angle in the left system to a "normal" angle (mod 360) is given by

f: α ↦ 270 − α.

Hence, the inverse mapping, f⁻¹, is given by

f⁻¹: α ↦ 270 − α.

(Clearly, f is an involution.)

Title: Shifting Angles using Arctan2


问:
Is scala.io.StdIn.readLine() a blocking call?
Is scala.io.StdIn.readLine() a blocking call?

From the docs, there is no mention of it being a blocking call.

I want to do something like this:

```<code>while(true){
    val input = scala.io.StdIn.readLine()
    input match{
        case "quit" =>
            ...
        case "stats" =>
            ...
        case _ =>
            ...
    }
}
</code>```

If it's not blocking, will it constantly loop, set input to null, and trigger case _ each time?

If it is blocking, why isn't it shown in the docs? Or where can I see a definition that says it is blocking?

In general, how can I know whether or not a method is blocking?

答:
how can I know whether or not a method is blocking?

Look at the return type of the method. If it is returning Future, IO, or some other effectful value F[A] that wraps a pure value A capable of modelling asynchronous computations, then assume it is non-blocking. For example consider

```<code>def f(v: Int): Future[Int] = Future(v + 1)
def g(v: Int): IO[Int] = IO(v + 1)
</code>```

Here f and g are non-blocking in the sense of the thread that called them not being blocked until v + 1 is evaluated. On the other hand, if the method is returning pure value like so

```<code>def h(v: Int): Int = v + 1
</code>```

then it is best to assume it is blocking. Here h is blocking in the sense of the thread that called it being blocked until v + 1 is computed.

Applying this principle to readLine

```<code>def readLine(): String
</code>```

we see it is returning pure value String so we assume it is blocking. Analysing the source code we see the following stacktrace

```<code>java.io.Reader#read(char[], int, int)
java.io.BufferedReader#fill
java.io.BufferedReader#readLine(boolean)
java.io.BufferedReader#readLine()
scala.io.StdIn#readLine
</code>```

where read states

Reads characters into a portion of an array. This method will block
  until some input is available, an I/O error occurs, or the end of the
  stream is reached.

Body:
Is scala.io.StdIn.readLine() a blocking call?

From the docs, there is no mention of it being a blocking call.

I want to do something like this:

while(true){
    val input = scala.io.StdIn.readLine()
    input match{
        case "quit" =>
            ...
        case "stats" =>
            ...
        case _ =>
            ...
    }
}

If it's not blocking, will it constantly loop, set input to null, and trigger case _ each time?

If it is blocking, why isn't it shown in the docs? Or where can I see a definition that says it is blocking?

In general, how can I know whether or not a method is blocking?

Body:
how can I know whether or not a method is blocking?

Look at the return type of the method. If it is returning Future, IO, or some other effectful value F[A] that wraps a pure value A capable of modelling asynchronous computations, then assume it is non-blocking. For example consider

def f(v: Int): Future[Int] = Future(v + 1)
def g(v: Int): IO[Int] = IO(v + 1)

Here f and g are non-blocking in the sense of the thread that called them not being blocked until v + 1 is evaluated. On the other hand, if the method is returning pure value like so

def h(v: Int): Int = v + 1

then it is best to assume it is blocking. Here h is blocking in the sense of the thread that called it being blocked until v + 1 is computed.

Applying this principle to readLine

def readLine(): String

we see it is returning pure value String so we assume it is blocking. Analysing the source code we see the following stacktrace

java.io.Reader#read(char[], int, int)
java.io.BufferedReader#fill
java.io.BufferedReader#readLine(boolean)
java.io.BufferedReader#readLine()
scala.io.StdIn#readLine

where read states

Reads characters into a portion of an array. This method will block
  until some input is available, an I/O error occurs, or the end of the
  stream is reached.


问:
How can I view the google drive image and video files from the react-native app?
I want to display pictures in my react native app, but only know how to show the pictures from other url's but don't know how can I show the images from the drive in my app,

```<code>  <Image
      style={{width:50, height: 50}}
      source={{uri: 'https://facebook.github.io/react-native/img/tiny_logo.png'}}
   />
</code>```

Above code displays the picture from the link but how can I display the pictures which are in google drive? tried giving sharable links as uri but no use.

Thanks in advance.

答:
Shift + ctrl + I while preview of image opened on Google Drive page.

Shift + ctrl + c and click on the image

Copy the URL in the inspection panel and put it as a source

Body:
I want to display pictures in my react native app, but only know how to show the pictures from other url's but don't know how can I show the images from the drive in my app,

  <Image
      style={{width:50, height: 50}}
      source={{uri: 'https://facebook.github.io/react-native/img/tiny_logo.png'}}
   />

Above code displays the picture from the link but how can I display the pictures which are in google drive? tried giving sharable links as uri but no use.

Thanks in advance.


问:
Clojure. Using Regex to replace sub-strings with the same number of characters
I need to replace the characters of a sub-string for spaces when it's surrounded by asterisks:

```<code>(def my-line "Lorem ipsum dolor, *consetetur*, invidunt ut *labore et dolore magna aliquyam* erat")

(clojure.string/replace my-line #"\*(.*?)\*" "    ")
</code>```

but my code is dumb and sets a static number of spaces and what I need is to replace the same number of characters with spaces:

```<code>consetetur = 9 spaces
labore et dolore magna aliquyam = 31
</code>```

答:
Solution.

As andy_fingerhut mentioned, a vector is created and passed when there are groups of characters captured by the regex:

```<code> (clojure.string/replace my-line #"\*(.*?)\*" #(.toUpperCase (%1 1)))
=> "Lorem ipsum dolor sit amet, CONSETETUR, tempor invidunt ut LABORE ET DOLORE MAGNA ALIQUYAM erat, sed diam"
</code>```

So in my case:

```<code>(clojure.string/replace my-line #"\*(.*?)\*"
       #(clojure.string/join (take (count (% 1)) (repeat " "))))
=> "Lorem ipsum dolor sit amet,           , tempor invidunt ut                                 erat, sed diam"
</code>```

Body:
I need to replace the characters of a sub-string for spaces when it's surrounded by asterisks:

(def my-line "Lorem ipsum dolor, *consetetur*, invidunt ut *labore et dolore magna aliquyam* erat")

(clojure.string/replace my-line #"\*(.*?)\*" "    ")

but my code is dumb and sets a static number of spaces and what I need is to replace the same number of characters with spaces:

consetetur = 9 spaces
labore et dolore magna aliquyam = 31

Body:
Solution.

As andy_fingerhut mentioned, a vector is created and passed when there are groups of characters captured by the regex:

 (clojure.string/replace my-line #"\*(.*?)\*" #(.toUpperCase (%1 1)))
=> "Lorem ipsum dolor sit amet, CONSETETUR, tempor invidunt ut LABORE ET DOLORE MAGNA ALIQUYAM erat, sed diam"

So in my case:

(clojure.string/replace my-line #"\*(.*?)\*"
       #(clojure.string/join (take (count (% 1)) (repeat " "))))
=> "Lorem ipsum dolor sit amet,           , tempor invidunt ut                                 erat, sed diam"


问:
oracle update with correlated query
What is the correct answer? Choose two.

Examine this SQL statement:

```<code>UPDATE orders o
SET customer_name = (
    SELECT cust_last_name FROM customers  WHERE customer_id=o.customer_id
);
</code>```

Which two are true?

A. The subquery is executed before the UPDATE statement is executed.

B. All existing rows in the ORDERS table are updated.

C. The subquery is executed for every updated row in the ORDERS
table.

D. The UPDATE statement executes successfully even if the subquery
selects multiple rows.

E. The subquery is not a correlated subquery.

I know B is correct, but all other selection I believe is incorrect.

A. Subquery executes for every row that the outer query returns, so
it should execute after the outer query.

C. NOT for every updated row, it is for every row that the outer
query returns.

D. I tried. It causes an error ORA-01427: single-row subquery returns
more than one row

E. It is a correlated subquery.

答:
The only second true answer is

F.  this is a wrong desing denormalizing the CUSTOMER_NAME in the orders table and conflicting therefor with the normal form.

The answer C could be right somewhere in the times of Oracle 8 (i.e. 20 years ago) but now it is definitively wrong!.

Oracle introduces the scalar subquery caching event for the reason to limit the number of executions of the subqueries.

Here a Simple Demonstration

This setup in Oracle 19.2 has 10K orders and 1K customers.

```<code>create table customers as
select rownum customer_id, 'cust_'||rownum customer_name from dual connect by level <= 1000;

create index customers_idx1 on customers (customer_id);

create table orders as
select rownum order_id, trunc(rownum/10)+1 customer_id, cast (null as varchar2(100)) customer_name
from dual connect by level <= 10000;
</code>```

The update is performed on 100K rows as expected

```<code>UPDATE /*+ gather_plan_statistics */ orders o
SET customer_name = (
    SELECT customer_name FROM customers  WHERE customer_id=o.customer_id
);
</code>```

The hint gather_plan_statistics collects teh execution statistics which we will examine.

```<code>SQL_ID  8r610vz9fknr6, child number 0
-------------------------------------
UPDATE /*+ gather_plan_statistics */ orders o SET customer_name = (
SELECT customer_name FROM customers  WHERE customer_id=o.customer_id )

Plan hash value: 3416863305

--------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name           | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
--------------------------------------------------------------------------------------------------------------------------
|   0 | UPDATE STATEMENT                     |                |      1 |        |      0 |00:00:00.18 |   60863 |     21 |
|   1 |  UPDATE                              | ORDERS         |      1 |        |      0 |00:00:00.18 |   60863 |     21 |
|   2 |   TABLE ACCESS FULL                  | ORDERS         |      1 |  10000 |  10000 |00:00:00.01 |      21 |     18 |
|   3 |   TABLE ACCESS BY INDEX ROWID BATCHED| CUSTOMERS      |   1001 |      1 |   1000 |00:00:00.01 |    2020 |      3 |
|*  4 |    INDEX RANGE SCAN                  | CUSTOMERS_IDX1 |   1001 |      1 |   1000 |00:00:00.01 |    1020 |      3 |
--------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("CUSTOMER_ID"=:B1)
</code>```

The importatnt information is in the column Start, we see that the table customers were accessed only 1001 time, i.e. nearly only once per customer and not once per order.

Title: oracle update with correlated query

Body:
What is the correct answer? Choose two.

Examine this SQL statement:

UPDATE orders o
SET customer_name = (
    SELECT cust_last_name FROM customers  WHERE customer_id=o.customer_id
);

Which two are true?

A. The subquery is executed before the UPDATE statement is executed.

B. All existing rows in the ORDERS table are updated.

C. The subquery is executed for every updated row in the ORDERS
table.

D. The UPDATE statement executes successfully even if the subquery
selects multiple rows.

E. The subquery is not a correlated subquery.

I know B is correct, but all other selection I believe is incorrect.

A. Subquery executes for every row that the outer query returns, so
it should execute after the outer query.

C. NOT for every updated row, it is for every row that the outer
query returns.

D. I tried. It causes an error ORA-01427: single-row subquery returns
more than one row

E. It is a correlated subquery.

Body:
The only second true answer is

F.  this is a wrong desing denormalizing the CUSTOMER_NAME in the orders table and conflicting therefor with the normal form.

The answer C could be right somewhere in the times of Oracle 8 (i.e. 20 years ago) but now it is definitively wrong!.

Oracle introduces the scalar subquery caching event for the reason to limit the number of executions of the subqueries.

Here a Simple Demonstration

This setup in Oracle 19.2 has 10K orders and 1K customers.

create table customers as
select rownum customer_id, 'cust_'||rownum customer_name from dual connect by level <= 1000;

create index customers_idx1 on customers (customer_id);

create table orders as
select rownum order_id, trunc(rownum/10)+1 customer_id, cast (null as varchar2(100)) customer_name
from dual connect by level <= 10000;

The update is performed on 100K rows as expected

UPDATE /*+ gather_plan_statistics */ orders o
SET customer_name = (
    SELECT customer_name FROM customers  WHERE customer_id=o.customer_id
);

The hint gather_plan_statistics collects teh execution statistics which we will examine.

SQL_ID  8r610vz9fknr6, child number 0
-------------------------------------
UPDATE /*+ gather_plan_statistics */ orders o SET customer_name = (
SELECT customer_name FROM customers  WHERE customer_id=o.customer_id )

Plan hash value: 3416863305

--------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name           | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
--------------------------------------------------------------------------------------------------------------------------
|   0 | UPDATE STATEMENT                     |                |      1 |        |      0 |00:00:00.18 |   60863 |     21 |
|   1 |  UPDATE                              | ORDERS         |      1 |        |      0 |00:00:00.18 |   60863 |     21 |
|   2 |   TABLE ACCESS FULL                  | ORDERS         |      1 |  10000 |  10000 |00:00:00.01 |      21 |     18 |
|   3 |   TABLE ACCESS BY INDEX ROWID BATCHED| CUSTOMERS      |   1001 |      1 |   1000 |00:00:00.01 |    2020 |      3 |
|*  4 |    INDEX RANGE SCAN                  | CUSTOMERS_IDX1 |   1001 |      1 |   1000 |00:00:00.01 |    1020 |      3 |
--------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("CUSTOMER_ID"=:B1)

The importatnt information is in the column Start, we see that the table customers were accessed only 1001 time, i.e. nearly only once per customer and not once per order.


问:
How to write length function for all Monoids
I'm playing around with rewriting simple functions in different ways and I clearly misunderstand some core concepts. Is there a better way to work with limited types like these?

```<code>mlength :: Monoid m => m -> Int
mlength mempty   = 0
mlength (l <> r) = mlength l + mlength r
</code>```

It fails compilation with the following error:

```<code>Parse error in pattern: l <> r
</code>```

I can see that my usage of <> is misguided because there are multiple correct matches for l and r. Even though it looks like it doesn't matter which value is assigned, a value still has to be assigned in the end. Maybe there's a way for me to assert this decision for specific Monoid instances?

```<code>"ab" == ""   <> "ab"
"ab" == "a"  <> "b"
"ab" == "ab" <> ""
</code>```

答:
The Semigroup and Monoid interfaces provide a means to build up values, (<>). They don't, however, give us a way to break down or otherwise extract information from values. That being so, a length generalised beyond some specific type requires a different abstraction.

As discussed in the comments to chi's answer, while Data.Foldable offers a generalised length :: Foldable t => t a -> Int, it isn't quite what you were aiming at -- in particular, the connection between Foldable and Monoid is that foldable structures can be converted to lists/the free monoid, and not that foldables themselves are necessarily monoids.

One other possibility, which is somewhat obscure but closer to the spirit of your question, is the Factorial class from the monoid-subclasses package, a subclass of Semigroup. It is built around factors :: Factorial m => m -> [m], which splits a value into irreducible factors, undoing what sconcat or mconcat do. A generalised length :: Factorial m => m -> Int can then be defined as the length of the list of factors. In any case, note that we still end up needing a further abstraction on the top of Semigroup/Monoid.

Body:
I'm playing around with rewriting simple functions in different ways and I clearly misunderstand some core concepts. Is there a better way to work with limited types like these?

mlength :: Monoid m => m -> Int
mlength mempty   = 0
mlength (l <> r) = mlength l + mlength r

It fails compilation with the following error:

Parse error in pattern: l <> r

I can see that my usage of <> is misguided because there are multiple correct matches for l and r. Even though it looks like it doesn't matter which value is assigned, a value still has to be assigned in the end. Maybe there's a way for me to assert this decision for specific Monoid instances?

"ab" == ""   <> "ab"
"ab" == "a"  <> "b"
"ab" == "ab" <> ""


问:
Check if inputs form are empty jQuery
How can I check in jQuery if inputs with name denominationcomune_{{loop.index}} and denominationcomune_{{loop.index}} are empty not all inputs ?

I have a twig like this:

```<code><form action="" method="post">
    {% for mat in mat_temp_array %}
        <input type="text" name="nomentite_{{loop.index}}"/>
        <input type="text" name="denominationcomune_{{loop.index}}" value="{{ mat.denominationcommun }}"/>
        <input type="text" name="denominationcomerce_{{loop.index}}" value="{{ mat.denominationcomerce }}"/>
    {% endfor %}

     <input type="submit" class="btn" value="save"/>
</form>
</code>```

答: $('input[type="text"]').get().some(item => item.value !== '');</p>

Title: Check if inputs form are empty jQuery

Body:
How can I check in jQuery if inputs with name denominationcomune_{{loop.index}} and denominationcomune_{{loop.index}} are empty not all inputs ?

I have a twig like this:

<form action="" method="post">
    {% for mat in mat_temp_array %}
        <input type="text" name="nomentite_{{loop.index}}"/>
        <input type="text" name="denominationcomune_{{loop.index}}" value="{{ mat.denominationcommun }}"/>
        <input type="text" name="denominationcomerce_{{loop.index}}" value="{{ mat.denominationcomerce }}"/>
    {% endfor %}

     <input type="submit" class="btn" value="save"/>
</form>


问:
How to refresh/update a variable in Makefile?
I have this Makefile:

```<code>CFLAGS = -ffreestanding -O2 -nostdlib -lgcc
BUILD_DIR = ../build
BIN = $(BUILD_DIR)/os.bin
LINKER_SCRIPT = linker.ld
OBJ_FILES := $(shell find $(BUILD_DIR) -iname '*.o')

.PHONY: all

all:
    @make -C boot
    @make -C kernel
    $(CC) -T $(LINKER_SCRIPT) -o $(BIN) $(CFLAGS) $(OBJ_FILES)

</code>```

After compiling (doing make in boot and kernel directories) there should be files with .o extension, however OBJ_FILES is empty. Only after calling make again OBJ_FILES contains the .o files paths which are needed to link. So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

答:
Let's say you have following structure:

```<code>.
|-- Makefile
|-- boot
|   |-- Makefile
|   |-- boot.c
|   `-- boot.h
|-- kernel
|   |-- Makefile
|   |-- kernel.c
|   `-- kernel.h
`-- main.c
</code>```

and your Makefile looks like this

```<code>location = $(CURDIR)

OBJ_FILES = $(shell find $(location) -name '*.o')

all: make_common
        gcc -o main main.c $(OBJ_FILES)

make_common:
        @make -C boot
        @make -C kernel

clean:
        -rm boot/boot.o
        -rm kernel/kernel.o
</code>```

Your source code is quite simple:

```<code>> cat boot/boot.h
int boot();

> cat boot/boot.c
int boot() {
  return 1;
}

> cat kernel/kernel.h
int kernel();

> cat kernel/kernel.c
int kernel() {
  return 2;
}

> cat main.c
#include "boot/boot.h"
#include "kernel/kernel.h"

int main() {
  int result = boot() + kernel();
  return 0;
}
</code>```

"inner" Makefiles contain

```<code>> cat boot/Makefile
all:
    gcc -c boot.c

> cat kernel/Makefile
all:
    gcc -c kernel.c
</code>```

you will get what you are looking for

```<code>> make clean
rm boot/boot.o
rm: boot/boot.o: No such file or directory
make: [clean] Error 1 (ignored)
rm kernel/kernel.o
rm: kernel/kernel.o: No such file or directory
make: [clean] Error 1 (ignored)
> make
gcc -c boot.c
gcc -c kernel.c
gcc -o main main.c ..../boot/boot.o ..../kernel/kernel.o
</code>```

```<code>VAR = val
</code>```

Expanded when the variable is used.

Body:
I have this Makefile:

CFLAGS = -ffreestanding -O2 -nostdlib -lgcc
BUILD_DIR = ../build
BIN = $(BUILD_DIR)/os.bin
LINKER_SCRIPT = linker.ld
OBJ_FILES := $(shell find $(BUILD_DIR) -iname '*.o')

.PHONY: all

all:
    @make -C boot
    @make -C kernel
    $(CC) -T $(LINKER_SCRIPT) -o $(BIN) $(CFLAGS) $(OBJ_FILES)

After compiling (doing make in boot and kernel directories) there should be files with .o extension, however OBJ_FILES is empty. Only after calling make again OBJ_FILES contains the .o files paths which are needed to link. So my question is how do I update OBJ_FILES after compiling in the boot and kernel directories, because OBJ_FILES doesn't update/refresh.

Body:
Let's say you have following structure:

.
|-- Makefile
|-- boot
|   |-- Makefile
|   |-- boot.c
|   `-- boot.h
|-- kernel
|   |-- Makefile
|   |-- kernel.c
|   `-- kernel.h
`-- main.c

and your Makefile looks like this

location = $(CURDIR)

OBJ_FILES = $(shell find $(location) -name '*.o')

all: make_common
        gcc -o main main.c $(OBJ_FILES)

make_common:
        @make -C boot
        @make -C kernel

clean:
        -rm boot/boot.o
        -rm kernel/kernel.o

Your source code is quite simple:

> cat boot/boot.h
int boot();

> cat boot/boot.c
int boot() {
  return 1;
}

> cat kernel/kernel.h
int kernel();

> cat kernel/kernel.c
int kernel() {
  return 2;
}

> cat main.c
#include "boot/boot.h"
#include "kernel/kernel.h"

int main() {
  int result = boot() + kernel();
  return 0;
}

"inner" Makefiles contain

> cat boot/Makefile
all:
    gcc -c boot.c

> cat kernel/Makefile
all:
    gcc -c kernel.c

you will get what you are looking for

> make clean
rm boot/boot.o
rm: boot/boot.o: No such file or directory
make: [clean] Error 1 (ignored)
rm kernel/kernel.o
rm: kernel/kernel.o: No such file or directory
make: [clean] Error 1 (ignored)
> make
gcc -c boot.c
gcc -c kernel.c
gcc -o main main.c ..../boot/boot.o ..../kernel/kernel.o

VAR = val

Expanded when the variable is used.


问:
How do I have my Bot respond with arguments?
So I've built a Telegram bot, which can receive the following commands:

/list

/info 123

This works great, as I can catch /info and pass the additional arguments as ints. But, sadly, the Telegram clients don't see /info 123 as a complete command, but just the /info part. Is there a way to make it recognize the entirety of the command as the command?

I've tried Markdown-ing it: [/info 123](/info 123), but no joy. Is this possible?

答:
This is a fairly rudimentary way of creating kwargs from user input.

Unfortunately, it does require the user to be aware of the fields that can be used as parameters, but if you can provide informative response when the user doesnt provide any detectable kwarg style messages then you could probably make a better experience.

As I say, extremely rudimentary idea, and would probably be achieved faster with the regex filters available. And this would be much more reliable when checking input from the user of the "pesky" variety.

The script relies on || delimiter preceeding the command and as is shown will trim any extra characters like new lines and spaces

You can remove the extra check for commit as this is provided in order to tell the bot that you want to save your input to the database explicitly.

```<code>def parse_kwargs(update):
    commit = False
    kwargs = {}
    if update.message:
        for args in update.message.text.split('||')[1:]:
            for kw_pair in args.split(','):
                key, value = kw_pair.split('=')
                if key.strip() != 'commit':
                    kwargs[key.strip()] = value.strip()
                elif key.strip() == 'commit' and value.strip().lower() == 'true':
                    commit = True
    return kwargs, commit
</code>```

Body:
This is a fairly rudimentary way of creating kwargs from user input.

Unfortunately, it does require the user to be aware of the fields that can be used as parameters, but if you can provide informative response when the user doesnt provide any detectable kwarg style messages then you could probably make a better experience.

As I say, extremely rudimentary idea, and would probably be achieved faster with the regex filters available. And this would be much more reliable when checking input from the user of the "pesky" variety.

The script relies on || delimiter preceeding the command and as is shown will trim any extra characters like new lines and spaces

You can remove the extra check for commit as this is provided in order to tell the bot that you want to save your input to the database explicitly.

def parse_kwargs(update):
    commit = False
    kwargs = {}
    if update.message:
        for args in update.message.text.split('||')[1:]:
            for kw_pair in args.split(','):
                key, value = kw_pair.split('=')
                if key.strip() != 'commit':
                    kwargs[key.strip()] = value.strip()
                elif key.strip() == 'commit' and value.strip().lower() == 'true':
                    commit = True
    return kwargs, commit


问:
GridSearchCV passing fit_params to XGBRegressor in a pipeline yields "ValueError: need more than 1 value to unpack"
Passing fit_params into a pipeline containing an XGBRegressor returns errors regardless of contents

The training dataset has been one hot encoded and is split for use in the pipeline

```<code>train_X, val_X, train_y, val_y = train_test_split(final_train, y, random_state = 0)
</code>```

Create an Imputer -> XGBRegressor pipeline. Set the XGBRegressor's parameters and the fit parameters

```<code>pipe = Pipeline(steps=[("Imputer", Imputer()),
                      ("XGB", XGBRegressor())])

xgb_hyperparams = {'XGB__n_estimators': [1000, 2000, 3000],
                   'XGB__learning_rate': [0.01, 0.03, 0.05, 0.07],
                   'XGB__max_depth': [3, 4, 5]}

fit_parameters = {'XGB__early_stopping_rounds': 5,
              'XGB__eval_metric': 'mae',
              'XGB__eval_set': [(val_X, val_y)],
              'XGB__verbose': False}

grid_search = GridSearchCV(pipe,
                          xgb_hyperparams,
                          #fit_params=fit_parameters,
                          scoring='neg_mean_squared_error',
                          cv=5,
                          n_jobs=1,
                          verbose=3)

grid_search.fit(train_X, train_y, fit_params=fit_parameters)
</code>```

This yields the following output:

```<code>Fitting 5 folds for each of 36 candidates, totalling 180 fits
[CV] XGB__learning_rate=0.01, XGB__n_estimators=1000, XGB__max_depth=3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-76-0751db18c046> in <module>()
----> 1 grid_search.fit(train_X, train_y, fit_params=fit_parameters)

/usr/local/lib/python2.7/site-packages/sklearn/model_selection/_search.pyc in fit(self, X, y, groups, **fit_params)
    638                                   error_score=self.error_score)
    639           for parameters, (train, test) in product(candidate_params,
--> 640                                                    cv.split(X, y, groups)))
    641
    642         # if one choose to see train score, "out" will contain train score info

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    777             # was dispatched. In particular this covers the edge
    778             # case of Parallel used with an exhausted iterator.
--> 779             while self.dispatch_one_batch(iterator):
    780                 self._iterating = True
    781             else:

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in dispatch_one_batch(self, iterator)
    623                 return False
    624             else:
--> 625                 self._dispatch(tasks)
    626                 return True
    627

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in _dispatch(self, batch)
    586         dispatch_timestamp = time.time()
    587         cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self)
--> 588         job = self._backend.apply_async(batch, callback=cb)
    589         self._jobs.append(job)
    590

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.pyc in apply_async(self, func, callback)
    109     def apply_async(self, func, callback=None):
    110         """Schedule a func to be run"""
--> 111         result = ImmediateResult(func)
    112         if callback:
    113             callback(result)

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.pyc in __init__(self, batch)
    330         # Don't delay the application, to avoid keeping the input
    331         # arguments in memory
--> 332         self.results = batch()
    333
    334     def get(self):

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self)
    129
    130     def __call__(self):
--> 131         return [func(*args, **kwargs) for func, args, kwargs in self.items]
    132
    133     def __len__(self):

/usr/local/lib/python2.7/site-packages/sklearn/model_selection/_validation.pyc in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, return_n_test_samples, return_times, error_score)
    456             estimator.fit(X_train, **fit_params)
    457         else:
--> 458             estimator.fit(X_train, y_train, **fit_params)
    459
    460     except Exception as e:

/usr/local/lib/python2.7/site-packages/sklearn/pipeline.pyc in fit(self, X, y, **fit_params)
    246             This estimator
    247         """
--> 248         Xt, fit_params = self._fit(X, y, **fit_params)
    249         if self._final_estimator is not None:
    250             self._final_estimator.fit(Xt, y, **fit_params)

/usr/local/lib/python2.7/site-packages/sklearn/pipeline.pyc in _fit(self, X, y, **fit_params)
    195                                 if step is not None)
    196         for pname, pval in six.iteritems(fit_params):
--> 197             step, param = pname.split('__', 1)
    198             fit_params_steps[step][param] = pval
    199         Xt = X

ValueError: need more than 1 value to unpack
</code>```

答:
You must use **xgb_hyperparams, like in this way: </p>

```<code>gbm.fit(
    X_train_preprocess,
    y_train,
    **param_fit_grid,
)
</code>```

Body:
Passing fit_params into a pipeline containing an XGBRegressor returns errors regardless of contents

The training dataset has been one hot encoded and is split for use in the pipeline

train_X, val_X, train_y, val_y = train_test_split(final_train, y, random_state = 0)

Create an Imputer -> XGBRegressor pipeline. Set the XGBRegressor's parameters and the fit parameters

pipe = Pipeline(steps=[("Imputer", Imputer()),
                      ("XGB", XGBRegressor())])

xgb_hyperparams = {'XGB__n_estimators': [1000, 2000, 3000],
                   'XGB__learning_rate': [0.01, 0.03, 0.05, 0.07],
                   'XGB__max_depth': [3, 4, 5]}

fit_parameters = {'XGB__early_stopping_rounds': 5,
              'XGB__eval_metric': 'mae',
              'XGB__eval_set': [(val_X, val_y)],
              'XGB__verbose': False}

grid_search = GridSearchCV(pipe,
                          xgb_hyperparams,
                          #fit_params=fit_parameters,
                          scoring='neg_mean_squared_error',
                          cv=5,
                          n_jobs=1,
                          verbose=3)

grid_search.fit(train_X, train_y, fit_params=fit_parameters)

This yields the following output:

Fitting 5 folds for each of 36 candidates, totalling 180 fits
[CV] XGB__learning_rate=0.01, XGB__n_estimators=1000, XGB__max_depth=3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-76-0751db18c046> in <module>()
----> 1 grid_search.fit(train_X, train_y, fit_params=fit_parameters)

/usr/local/lib/python2.7/site-packages/sklearn/model_selection/_search.pyc in fit(self, X, y, groups, **fit_params)
    638                                   error_score=self.error_score)
    639           for parameters, (train, test) in product(candidate_params,
--> 640                                                    cv.split(X, y, groups)))
    641
    642         # if one choose to see train score, "out" will contain train score info

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    777             # was dispatched. In particular this covers the edge
    778             # case of Parallel used with an exhausted iterator.
--> 779             while self.dispatch_one_batch(iterator):
    780                 self._iterating = True
    781             else:

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in dispatch_one_batch(self, iterator)
    623                 return False
    624             else:
--> 625                 self._dispatch(tasks)
    626                 return True
    627

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in _dispatch(self, batch)
    586         dispatch_timestamp = time.time()
    587         cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self)
--> 588         job = self._backend.apply_async(batch, callback=cb)
    589         self._jobs.append(job)
    590

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.pyc in apply_async(self, func, callback)
    109     def apply_async(self, func, callback=None):
    110         """Schedule a func to be run"""
--> 111         result = ImmediateResult(func)
    112         if callback:
    113             callback(result)

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/_parallel_backends.pyc in __init__(self, batch)
    330         # Don't delay the application, to avoid keeping the input
    331         # arguments in memory
--> 332         self.results = batch()
    333
    334     def get(self):

/usr/local/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.pyc in __call__(self)
    129
    130     def __call__(self):
--> 131         return [func(*args, **kwargs) for func, args, kwargs in self.items]
    132
    133     def __len__(self):

/usr/local/lib/python2.7/site-packages/sklearn/model_selection/_validation.pyc in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, return_n_test_samples, return_times, error_score)
    456             estimator.fit(X_train, **fit_params)
    457         else:
--> 458             estimator.fit(X_train, y_train, **fit_params)
    459
    460     except Exception as e:

/usr/local/lib/python2.7/site-packages/sklearn/pipeline.pyc in fit(self, X, y, **fit_params)
    246             This estimator
    247         """
--> 248         Xt, fit_params = self._fit(X, y, **fit_params)
    249         if self._final_estimator is not None:
    250             self._final_estimator.fit(Xt, y, **fit_params)

/usr/local/lib/python2.7/site-packages/sklearn/pipeline.pyc in _fit(self, X, y, **fit_params)
    195                                 if step is not None)
    196         for pname, pval in six.iteritems(fit_params):
--> 197             step, param = pname.split('__', 1)
    198             fit_params_steps[step][param] = pval
    199         Xt = X

ValueError: need more than 1 value to unpack

Body:
You must use **xgb_hyperparams, like in this way:

gbm.fit(
    X_train_preprocess,
    y_train,
    **param_fit_grid,
)


问:
Hide/Show table columns depending on the element clicked
I would like to create some type of buttons that would only show the table columns affected to them and hidding every others, and add/remove the active class to the buttons, for example:

```<code><a href="#" class="btn active" id="fruits">Data 1</a>
<a href="#" class="btn" id="vegetables">Data 2</a>
<a href="#" class="btn" id="nuts">Data 3</a>

<table>

    <thead>
        <tr>
            <th class="fruits">First column</th>
            <th class="vegetables">Second column</th>
            <th class="nuts">Third column</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td class="fruits">Test 1</td>
            <td class="vegetables">Test 2</td>
            <td class="nuts">Test 3</td>
        </tr>
    </tbody>

</table>
</code>```

For example, when I click on the "Data 2" button, it adds the "active" class to it, hides every other columns and only shows the items having the class called "vegetables".

I am a beginner and I would like to know if that's possible and how? Thank you.

答:
In order to make a column active, you need to figure out the index of the clicked button. After that, you can iterate through the headers and columns to figure out which ones to show or hide.

The example below will only show the clicked column (th and td) of the clicked button.

Update: If you want to show/hide based on the field that was clicked, you can reference the button id and target the class of each table cell.

Array.from(document.querySelectorAll('.buttons a')).forEach(a => {
  a.addEventListener('click', handleButtonClick);
});

function handleButtonClick(e) {
  let selectedId = e.target.id;
  document.querySelectorAll('.buttons a').forEach((a) => {
    a.classList[a.id === selectedId ? 'add' : 'remove']('active');
  });
  document.querySelectorAll('table > thead > tr th').forEach(th => {
    th.style.display = th.classList.contains(selectedId) ? 'table-cell' : 'none';
  });
  document.querySelectorAll('table > tbody > tr td').forEach(td => {
    td.style.display = td.classList.contains(selectedId) ? 'table-cell' : 'none';
  });
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.buttons a {
  display: inline-block;
  border: thin solid grey;
  padding: 0.25em 0.5em;
  text-decoration: none;
  background: #AAA;
}
.buttons a.active {
  background: #FFF;
}
table, th, td {
  border: thin solid grey;
}
table {
  border-collapse: collapse;
  margin-top: 1em;
}
th, td {
  padding: 0.25em;
}</code>```

  Fruits
  Vegetables
  Nuts

      Fruits
      Vegetables
      Nuts

      Apple
      Artichoke
      Almond

      Banana
      Broccoli
      Brazil Nut

      Cherry
      Carrot
      Cashew

```

Body:
I would like to create some type of buttons that would only show the table columns affected to them and hidding every others, and add/remove the active class to the buttons, for example:

Data 1
Data 2
Data 3

            First column
            Second column
            Third column

            Test 1
            Test 2
            Test 3

For example, when I click on the "Data 2" button, it adds the "active" class to it, hides every other columns and only shows the items having the class called "vegetables".

I am a beginner and I would like to know if that's possible and how? Thank you.

Body:
In order to make a column active, you need to figure out the index of the clicked button. After that, you can iterate through the headers and columns to figure out which ones to show or hide.

The example below will only show the clicked column (th and td) of the clicked button.

Update: If you want to show/hide based on the field that was clicked, you can reference the button id and target the class of each table cell.

Array.from(document.querySelectorAll('.buttons a')).forEach(a => {
  a.addEventListener('click', handleButtonClick);
});

function handleButtonClick(e) {
  let selectedId = e.target.id;
  document.querySelectorAll('.buttons a').forEach((a) => {
    a.classList[a.id === selectedId ? 'add' : 'remove']('active');
  });
  document.querySelectorAll('table > thead > tr th').forEach(th => {
    th.style.display = th.classList.contains(selectedId) ? 'table-cell' : 'none';
  });
  document.querySelectorAll('table > tbody > tr td').forEach(td => {
    td.style.display = td.classList.contains(selectedId) ? 'table-cell' : 'none';
  });
};

.buttons a {
  display: inline-block;
  border: thin solid grey;
  padding: 0.25em 0.5em;
  text-decoration: none;
  background: #AAA;
}
.buttons a.active {
  background: #FFF;
}
table, th, td {
  border: thin solid grey;
}
table {
  border-collapse: collapse;
  margin-top: 1em;
}
th, td {
  padding: 0.25em;
}

<div class="buttons">
  <a href="#" class="btn active" id="fruits">Fruits</a>
  <a href="#" class="btn" id="vegetables">Vegetables</a>
  <a href="#" class="btn" id="nuts">Nuts</a>
</div>
<table>
  <thead>
    <tr>
      <th class="fruits">Fruits</th>
      <th class="vegetables">Vegetables</th>
      <th class="nuts">Nuts</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="fruits">Apple</td>
      <td class="vegetables">Artichoke</td>
      <td class="nuts">Almond</td>
    </tr>
    <tr>
      <td class="fruits">Banana</td>
      <td class="vegetables">Broccoli</td>
      <td class="nuts">Brazil Nut</td>
    </tr>
    <tr>
      <td class="fruits">Cherry</td>
      <td class="vegetables">Carrot</td>
      <td class="nuts">Cashew</td>
    </tr>
  </tbody>
</table>


问:
I want to prevent diagonal movement in Pygame
I'm working on making a version of the game snake and I'm trying to prevent diagonal movement. Is there a way to prevent multiple KEYDOWN events

This is my helper function that detects KEYDOWN events.

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()
        elif event.key == pg.K_RIGHT:
            self.snake.move_right = True
        elif event.key == pg.K_LEFT:
            self.snake.move_left = True
        elif event.key == pg.K_UP:
            self.snake.move_up = True
        elif event.key == pg.K_DOWN:
            self.snake.move_down = True
```

答:
You may want to turn your movement direction variables into a single delta value instead:

if event.key == pg.K_RIGHT:
    self.snake.move_dir = (+1, 0)
elif event.key == pg.K_LEFT:
    self.snake.move_dir = (-1, 0)
elif event.key == pg.K_UP:
    self.snake.move_dir = (0, -1)
elif event.key == pg.K_DOWN:
    self.snake.move_dir = (0, +1)
```

<p>and wherever you move your snake,</p>

```dx, dy = self.move_dir
x += dx
y += dy
```

Body:
You may want to turn your movement direction variables into a single delta value instead:

if event.key == pg.K_RIGHT:
    self.snake.move_dir = (+1, 0)
elif event.key == pg.K_LEFT:
    self.snake.move_dir = (-1, 0)
elif event.key == pg.K_UP:
    self.snake.move_dir = (0, -1)
elif event.key == pg.K_DOWN:
    self.snake.move_dir = (0, +1)

and wherever you move your snake,

dx, dy = self.move_dir
x += dx
y += dy


问:
preg_replace not working after updating to PHP 5.4
I am having problem with preg_replace() I believe after updating my host PHP version from 5.3 to 5.4.

The code was working fine earlier but now having problem:

```<code>function update_comments($comments)
{
  if (!empty($comments) && is_array($comments)) {
    foreach ($comments as &$comment)
      update_comment(&$comment);
  }

  return $comments;
}

function update_comment($comment) {
$repl = '<a href="#">$0</a>';
$comment['comment'] = preg_replace('~#(\d+)~', $repl, $comment['comment']);
return $comment;
}
</code>```

Can anyone help me out?

答:
Welcome to stackoverflow, Abid!

Can you add your current output and the expected output and perhaps your error message? because I see that you use call time pass-by-reference which got removed in 5.4. (update_comment(&$comment)).

I tried to run the code and adopted it and I see that it seems to work fine after changing it. Here is an example in declarative and imperative way of doing it.

```<code>function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        foreach ($comments as $idx => $comment) {
            $comments[$idx] = update_comment($comment);
        }
    }

    return $comments;
}
</code>```

and here as declarative example

```<code>function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        $comments = array_map(function ($comment) {
            return update_comment($comment);
        }, $comments);
    }

    return $comments;
}
</code>```

Here is an example of how I used your code. You can also tinker around here with the specific PHP version: http://sandbox.onlinephpfunctions.com/code/10e616237c0c75c8e3520bdf5866040231879cde

```<code>$comments = update_comments([
    ['comment' => 'This is my #1 comment.'],
    ['comment' => 'This is my #2 comment.']
]);

print_r($comments);

// Array
// (
//     [0] => Array (
//             [comment] => This is my <a href="#">#1</a> comment.
//         )
//
//     [1] => Array (
//             [comment] => This is my <a href="#">#2</a> comment.
//         )
//
// )
</code>```

Let me know if this helps or if your preg_replace() issue still exists.

Body:
I am having problem with preg_replace() I believe after updating my host PHP version from 5.3 to 5.4.

The code was working fine earlier but now having problem:

function update_comments($comments)
{
  if (!empty($comments) && is_array($comments)) {
    foreach ($comments as &$comment)
      update_comment(&$comment);
  }

  return $comments;
}

function update_comment($comment) {
$repl = '$0';
$comment['comment'] = preg_replace('~#(\d+)~', $repl, $comment['comment']);
return $comment;
}

Can anyone help me out?

Body:
Welcome to stackoverflow, Abid!

Can you add your current output and the expected output and perhaps your error message? because I see that you use call time pass-by-reference which got removed in 5.4. (update_comment(&$comment)).

I tried to run the code and adopted it and I see that it seems to work fine after changing it. Here is an example in declarative and imperative way of doing it.

function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        foreach ($comments as $idx => $comment) {
            $comments[$idx] = update_comment($comment);
        }
    }

    return $comments;
}

and here as declarative example

function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        $comments = array_map(function ($comment) {
            return update_comment($comment);
        }, $comments);
    }

    return $comments;
}

Here is an example of how I used your code. You can also tinker around here with the specific PHP version: http://sandbox.onlinephpfunctions.com/code/10e616237c0c75c8e3520bdf5866040231879cde

$comments = update_comments([
    ['comment' => 'This is my #1 comment.'],
    ['comment' => 'This is my #2 comment.']
]);

print_r($comments);

// Array
// (
//     [0] => Array (
//             [comment] => This is my <a href="#">#1</a> comment.
//         )
//
//     [1] => Array (
//             [comment] => This is my <a href="#">#2</a> comment.
//         )
//
// )

Let me know if this helps or if your preg_replace() issue still exists.


问:
Custom ViewRenderer<> displays Forms element behind the native control
In my Xamarin Forms app, I have a custom view that derives from ContentView. On iOS and macOS, I would like to replace this view with a native control ([UI|NS]SegmentedControl). So I created a renderer that derives from ViewRenderer and implemented it.

It's working, but there is a flaw. The original Forms control (known as Element within the renderer) is displaying behind the UISegmentedControl. My expectation is that only the native control would be rendered when using ViewRenderer.

Any changes made to the appearance of the Forms element are reflected on the native control, so simply hiding it or making it transparent won't work.

Here's my iOS renderer.

```<code>public class CustomContentViewRenderer : ViewRenderer<CustomContentView, UISegmentedControl>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomContentView> e) {
        base.OnElementChanged(e);

        if (e.NewElement != null ) {
            if ( Control == null )
                SetNativeControl(new UISegmentedControl(new string[] { "One", "Two", "Three" }));
        }
    }
}
</code>```

CustomContentView here is simply derived from ContentView with a BoxView as content. Here's what it looks like on iOS:

My understanding of renderers is that a custom renderer completely overrides the forms element. Am I missing something big here? Can ViewRenderer<> be used to completely replace a Xamarin ContentView with a native control?

EDIT: In the sample above I'm using a BoxView as a placeholder for the actual cross platform picker I use for UWP. The real control is a StackLayout containing toggle buttons. Here's a screen grab on macOS showing the issue.

In the end, setting Element.Content.IsVisible = false worked.

答:
Yes, you can completely replace the ContentView's native control. And you have done so.

What you are seeing is that the (native control for the) child view (which you've provided as a BoxView) of the ContentView is also displaying.

If you don't want any additional child content, then don't add Content and/or subclass some different class than ContentView. Possible fixes:

Simply remove the Content = new BoxView ... line. I believe that will result in "no child to display". If I'm wrong, then google how to have "no Content".

You might be able to subclass View directly. If not, then you could subclass something simple that usually is used without Content - maybe a BoxView.

Fallback solution: don't set BackgroundColor on the BoxView. Result is an invisible box. (I realize that isn't really what you want: you want to avoid unnecessary creation of views.) [Invisible boxes are occasionally useful as a way to add invisible space in a layout - an alternative to margins.]

From your comment, it sounds like you want to "suppress" the given Content on one platform, as its role is subsumed by the custom control. To do this, have IsVisible property on the child, and set it to false on that platform. This will suppress generation of platform controls for the child and its descendents.

CAUTION: Don't try manipulating Element properties (such as IsVisible) from the custom renderer. This is executing at the wrong moment in the layout/draw sequence. Instead, do from view's code behind or via a Binding. One way to test platform in code is Xamarin.Essentials.DeviceInfo.Platform.

Body:
In my Xamarin Forms app, I have a custom view that derives from ContentView. On iOS and macOS, I would like to replace this view with a native control ([UI|NS]SegmentedControl). So I created a renderer that derives from ViewRenderer and implemented it.

It's working, but there is a flaw. The original Forms control (known as Element within the renderer) is displaying behind the UISegmentedControl. My expectation is that only the native control would be rendered when using ViewRenderer.

Any changes made to the appearance of the Forms element are reflected on the native control, so simply hiding it or making it transparent won't work.

Here's my iOS renderer.

public class CustomContentViewRenderer : ViewRenderer<CustomContentView, UISegmentedControl>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomContentView> e) {
        base.OnElementChanged(e);

        if (e.NewElement != null ) {
            if ( Control == null )
                SetNativeControl(new UISegmentedControl(new string[] { "One", "Two", "Three" }));
        }
    }
}

CustomContentView here is simply derived from ContentView with a BoxView as content. Here's what it looks like on iOS:

My understanding of renderers is that a custom renderer completely overrides the forms element. Am I missing something big here? Can ViewRenderer<> be used to completely replace a Xamarin ContentView with a native control?

EDIT: In the sample above I'm using a BoxView as a placeholder for the actual cross platform picker I use for UWP. The real control is a StackLayout containing toggle buttons. Here's a screen grab on macOS showing the issue.

In the end, setting Element.Content.IsVisible = false worked.