问:
Insert an item into for loop using each_with_index, instead of replacing
Most marketplace website's nowadays have an ad partial injected into the middle of the list, giving users a form to sign up.

Looking to get a better understanding into how each_with_index works and the correct way to insert a div into a list of objects. Let's take a list of, say 10 boxing studios, and using the below code we inject a div into the middle of the list. How do you inject a div without replacing the record entirely?

Expected: the 10 boxing studios with new div in the 6th position (11 items in the list in total)

Actual: 9 boxing studios with the new div replacing one of the boxing studios in the 6th position

```<code>@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Insert ad partial
  else
  # Print out each object in the list
  end
end
</code>```

答:
Given the variables

```<code>@list = (1..10).map { |n| "item #{n}"}
#=> ["item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9", "item 10"]

@signup = 'signup form'
position = 6
</code>```

You can iterate and print the element to be inserted without modifying the array:

```<code>@list.each_with_index do |item, idx|
  p @signup if position == idx + 1 # render the form
  p item
end

# "item 1"
# "item 2"
# "item 3"
# "item 4"
# "item 5"
# "signup form"
# "item 6"
# "item 7"
# "item 8"
# "item 9"
# "item 10"
</code>```

Body:
Most marketplace website's nowadays have an ad partial injected into the middle of the list, giving users a form to sign up.

Looking to get a better understanding into how each_with_index works and the correct way to insert a div into a list of objects. Let's take a list of, say 10 boxing studios, and using the below code we inject a div into the middle of the list. How do you inject a div without replacing the record entirely?

Expected: the 10 boxing studios with new div in the 6th position (11 items in the list in total)

Actual: 9 boxing studios with the new div replacing one of the boxing studios in the 6th position

@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Insert ad partial
  else
  # Print out each object in the list
  end
end

Body:
Given the variables

@list = (1..10).map { |n| "item #{n}"}
#=> ["item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9", "item 10"]

@signup = 'signup form'
position = 6

You can iterate and print the element to be inserted without modifying the array:

@list.each_with_index do |item, idx|
  p @signup if position == idx + 1 # render the form
  p item
end

# "item 1"
# "item 2"
# "item 3"
# "item 4"
# "item 5"
# "signup form"
# "item 6"
# "item 7"
# "item 8"
# "item 9"
# "item 10"


来源: stackexchange

问:
How to concat two columns value like - product_name(product_quantity), ..... from table in while loop and store in a variable
I have a table with two columns : product_name and product_qty with multiple rows

I want output as:

product_name(product_qty).........

like this one

product_one(2), product_two(4), product_three(1)

I'm trying by this method :

```<code>require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['product_name'];
    $qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
    $allItems .= $key."(".$value."), ";
}
</code>```

And getting output as :
product_one(2), product_two(4), product_three(1),

but I don't want comma in last......

答:
OK, the answer is in your question title. :), just as below:

```<code>select concat(product_name,'(',product_qty,')') as result from my_table;
</code>```

And the data example see below:

```<code>mysql> select * from my_table;
+---------------+-------------+
| product_name  | product_qty |
+---------------+-------------+
| product_one   |           2 |
| product_two   |           4 |
| product_three |           1 |
+---------------+-------------+
3 rows in set (0.00 sec)

mysql> select concat(product_name,'(',product_qty,')') as result from my_table;
+------------------+
| result           |
+------------------+
| product_one(2)   |
| product_two(4)   |
| product_three(1) |
+------------------+
3 rows in set (0.00 sec)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table with two columns : product_name and product_qty with multiple rows

I want output as:

product_name(product_qty).........

like this one

product_one(2), product_two(4), product_three(1)

I'm trying by this method :

require 'config.php';
$grand_total = 0;
$items = array();
$qty = array();
$allItems ='';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
    $grand_total +=$row['total_price'];
    $items[] = $row['product_name'];
    $qty[] = $row['qty'];
}
$array = array_combine($items, $qty);
foreach ($array as $key => $value) {
    $allItems .= $key."(".$value."), ";
}

And getting output as :
product_one(2), product_two(4), product_three(1),

but I don't want comma in last......

Body:
OK, the answer is in your question title. :), just as below:

select concat(product_name,'(',product_qty,')') as result from my_table;

And the data example see below:

mysql> select * from my_table;
+---------------+-------------+
| product_name  | product_qty |
+---------------+-------------+
| product_one   |           2 |
| product_two   |           4 |
| product_three |           1 |
+---------------+-------------+
3 rows in set (0.00 sec)

mysql> select concat(product_name,'(',product_qty,')') as result from my_table;
+------------------+
| result           |
+------------------+
| product_one(2)   |
| product_two(4)   |
| product_three(1) |
+------------------+
3 rows in set (0.00 sec)


问:
How to connect databases correctly in SQLAlchemy. Getting NameError: name "User" is not defined
I'm creating a many to many relationship with SQLAlchemy and flask. I think I have make all imports correctly, but for some reason I get error "NameError: name 'User' is not defined".

I read the SQLAlchemy documentation and tried their association object example. Below is my own files. Every db model is under application in it's own folder, example models.py (Picture) in application/pictures folder.

from sqlalchemy.orm import relationship

from application import db
from application.Base import Base

class Picture(Base):

    __tablename__ = "picture"

    #some code

    account_id = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=False)

    likers = relationship("Likes", back_populates="likes")

    def __init__(self, name):
        self.path = name
```

<pre class="lang-py prettyprint-override"><code>from sqlalchemy.orm import relationship

from application import db
from application import Base

class User(Base):

    __tablename__ = "account"

    #some code

    likes = relationship("Likes", back_populates="likers")

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = password

    #code associated to login
</code>```

from sqlalchemy.orm import relationship, backref

from application import db
from application import Base

class Likes(Base):

    __tablename__ = "like"

    #some code

    account_id = db.Column(db.Integer, db.ForeignKey('account.id'),
                           nullable=False)
    picture_id = db.Column(db.Integer, db.ForeignKey('picture.id'),
                           nullable=False)

    likers = relationship(User, back_populates="likes")
    likes = relationship(Picture, back_populates="likers")

    def __init__(self, account_id, picture_id):
        self.account_id = account_id
        self.picture_id = picture_id
```

<pre class="lang-py prettyprint-override"><code>#I have also imported the like db to __init__.py file before db.create_all()

from application.likes import models
</code>```

I excepted the databases to be correctly connected, but I get an error message

likers = relationship(User.id, back_populates="likes")
NameError: name 'User' is not defined

答:
You should enclose your models name in ` or " when your models insertion is unordered. Example:

```<code>likers = relationship('User', back_populates="likes")
likes = relationship('Picture', back_populates="likers")
</code>```

From docs (https://docs.sqlalchemy.org/en/13/orm/relationship_api.html):

When using the Declarative extension, the Declarative initializer allows string arguments to be passed to relationship(). These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the need for related classes to be imported into the local module space before the dependent classes have been declared. It is still required that the modules in which these related classes appear are imported anywhere in the application at some point before the related mappings are actually used, else a lookup error will be raised when the relationship() attempts to resolve the string reference to the related class.

Body:
I'm creating a many to many relationship with SQLAlchemy and flask. I think I have make all imports correctly, but for some reason I get error "NameError: name 'User' is not defined".

I read the SQLAlchemy documentation and tried their association object example. Below is my own files. Every db model is under application in it's own folder, example models.py (Picture) in application/pictures folder.

from sqlalchemy.orm import relationship

from application import db
from application.Base import Base

class Picture(Base):

    __tablename__ = "picture"

    #some code

    account_id = db.Column(db.Integer, db.ForeignKey("account.id"), nullable=False)

    likers = relationship("Likes", back_populates="likes")

    def __init__(self, name):
        self.path = name

from sqlalchemy.orm import relationship

from application import db
from application import Base

class User(Base):

    __tablename__ = "account"

    #some code

    likes = relationship("Likes", back_populates="likers")

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = password

    #code associated to login

from sqlalchemy.orm import relationship, backref

from application import db
from application import Base

class Likes(Base):

    __tablename__ = "like"

    #some code

    account_id = db.Column(db.Integer, db.ForeignKey('account.id'),
                           nullable=False)
    picture_id = db.Column(db.Integer, db.ForeignKey('picture.id'),
                           nullable=False)

    likers = relationship(User, back_populates="likes")
    likes = relationship(Picture, back_populates="likers")

    def __init__(self, account_id, picture_id):
        self.account_id = account_id
        self.picture_id = picture_id

#I have also imported the like db to __init__.py file before db.create_all()

from application.likes import models

I excepted the databases to be correctly connected, but I get an error message

likers = relationship(User.id, back_populates="likes")
NameError: name 'User' is not defined

Body:
You should enclose your models name in ` or " when your models insertion is unordered. Example:

likers = relationship('User', back_populates="likes")
likes = relationship('Picture', back_populates="likers")

From docs (https://docs.sqlalchemy.org/en/13/orm/relationship_api.html):

When using the Declarative extension, the Declarative initializer allows string arguments to be passed to relationship(). These string arguments are converted into callables that evaluate the string as Python code, using the Declarative class-registry as a namespace. This allows the lookup of related classes to be automatic via their string name, and removes the need for related classes to be imported into the local module space before the dependent classes have been declared. It is still required that the modules in which these related classes appear are imported anywhere in the application at some point before the related mappings are actually used, else a lookup error will be raised when the relationship() attempts to resolve the string reference to the related class.


问:
Database auto backup with current data and time
I am trying to take auto backup of Mysql database from batch file with current date and time, but it take backup with 0 Kb.

```<code>echo on

set TIMESTAMP=%DATE:~3,2%%DATE:~0,2%%DATE:~6,4%%TIME:~0,2%%TIME:~3,2%

CD "C:\Program Files\MySql\MySql Server 5.7\bin"

mysqldump -hlocalhost -uusername -ppassword databasename > D:\%TIMESTAMP%.sql
</code>```

Above code generate sql file on location with current date and time, but with 0 kb
means blank database.

答:
Try this. It works for me just using your own directory.

https://github.com/improy/MySQL-DataBase-backup-using-windows-bat-file/blob/master/MySqlBackup.bat

Body:
I am trying to take auto backup of Mysql database from batch file with current date and time, but it take backup with 0 Kb.

echo on

set TIMESTAMP=%DATE:~3,2%%DATE:~0,2%%DATE:~6,4%%TIME:~0,2%%TIME:~3,2%

CD "C:\Program Files\MySql\MySql Server 5.7\bin"

mysqldump -hlocalhost -uusername -ppassword databasename > D:\%TIMESTAMP%.sql

Above code generate sql file on location with current date and time, but with 0 kb
means blank database.


问:
How to display for loop PHP variable in newline in html table
I want to display forloop value in newline in html table

echo "
";
echo "".$i++."	";
echo "".$row['instructorname']."	";
echo "".$row['batchname']."	";
echo "".$row['fromdate']."	";
echo "".$row['todate']."	";

for ($i = $startdate; $i < $todate; $i++) echo ''.$i.'	';
echo "
";
```

I want to display each  $i value in newline but it appears in same line.

答:
Just added in your code

concat "\n" to the front of the statement

```<code>echo "\n" ."<td>" . $row['instructorname'] . "</td>";
echo "\n" ."<td>" . $row['batchname'] . "</td>";
</code>```

I hope it's helps you.

Thank you.

Body:
I want to display forloop value in newline in html table

echo "
";
echo "".$i++."	";
echo "".$row['instructorname']."	";
echo "".$row['batchname']."	";
echo "".$row['fromdate']."	";
echo "".$row['todate']."	";

for ($i = $startdate; $i < $todate; $i++) echo ''.$i.'	';
echo "
";

I want to display each  $i value in newline but it appears in same line.

Body:
Just added in your code

concat "\n" to the front of the statement

echo "\n" ."<td>" . $row['instructorname'] . "</td>";
echo "\n" ."<td>" . $row['batchname'] . "</td>";

I hope it's helps you.

Thank you.


问:
Never change the value of another component
I have this service y the component:

```<code>export class ListUserService {
    public openMeet = new BehaviorSubject<boolean>(false);
</code>```

and from the view i change this variable

```<code><span> <input type="button" id="usuarios" name="more" (click)="change()"
                  value="crear Meet"></span>
</code>```

in the component i have the function change():

```<code> change() {
        this.open ? this.open = false : this.open = true;
        this.listUserService.openMeet.next(this.open);
        });
</code>```

and i want to get the value en other component:

```<code>flagPerfil: boolean;
constructor(private listUserService: ListUserService) {
        listUserService.openMeet.subscribe((flag) => {
            this.flagPerfil = flag;
        });
    }
</code>```

but in the view the value never change:

```<code>  <span>{{flagPerfil}}</span>
</code>```

never change this value, what is the error?

答:
I think the problem is with this line

```<code>this.open ? this.open = false : this.open = true;
</code>```

you are not changing the this.open when the click is happened, you need to change your change() method something like below

```<code> change() {
     this.open = this.open ? false : true;
     this.listUserService.openMeet.next(this.open);
 };
</code>```

I hope this will help..  :)

Body:
I have this service y the component:

export class ListUserService {
    public openMeet = new BehaviorSubject<boolean>(false);

and from the view i change this variable

 <input type="button" id="usuarios" name="more" (click)="change()"
                  value="crear Meet">

in the component i have the function change():

 change() {
        this.open ? this.open = false : this.open = true;
        this.listUserService.openMeet.next(this.open);
        });

and i want to get the value en other component:

flagPerfil: boolean;
constructor(private listUserService: ListUserService) {
        listUserService.openMeet.subscribe((flag) => {
            this.flagPerfil = flag;
        });
    }

but in the view the value never change:

  {{flagPerfil}}

never change this value, what is the error?

Body:
I think the problem is with this line

this.open ? this.open = false : this.open = true;

you are not changing the this.open when the click is happened, you need to change your change() method something like below

 change() {
     this.open = this.open ? false : true;
     this.listUserService.openMeet.next(this.open);
 };

I hope this will help..  :)


问:
Angular focus on input while clicking an element
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

```<code><input class="input" type="text">
<label class="label">Name</label>

<div>
<input class="input" type="text">
<label class="label">Name</label>
</div>
</code>```

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}
```

答:
In the html, add a reference to your input text - #firstNameField and add a method to click event of the label - (click)="focusOnFirstName()"

```<code>    <input #firstNameField class="input" type="text">
    <label class="label" (click)="focusOnFirstName()">First Name</label>

</code>```

In your component declare ViewChild and implement a method to click of label field.

```<code>      @ViewChild("firstNameField") firstNameField;

      focusOnFirstName(){
        this.firstNameField.nativeElement.focus();
      }

</code>```

Body:
I have attached the stackblitz below

https://stackblitz.com/edit/angular-dgx3pe

What i am trying to achieve is while clicking on the label element it should focus on the input.Hence the input:focus  class gets activated.What I belive is that it can be achievable through javascript/jquery.But i prefer the angular way to achieve this.

In Brief,these are the two things i am trying to do,

Make focus on the input element when label is clicked.

When the focus is changed to another input element and if the previous element is not empty(If some value is typed in).The label should maintain its position in the top.

HTML

<input class="input" type="text">
Name

<input class="input" type="text">
Name

CSS

p {
  font-family: Lato;
}
.input
{
  border:none;
  border-bottom:1px solid grey;
  outline:none;
   margin-top:20%;
}
.input:focus
{
    border-bottom:1px solid orange;
}
.label
{
  position:relative;
 left:-170px;
}
.input:focus + .label
{
   bottom:20px;
}

Body:
In the html, add a reference to your input text - #firstNameField and add a method to click event of the label - (click)="focusOnFirstName()"

    <input #firstNameField class="input" type="text">
    <label class="label" (click)="focusOnFirstName()">First Name</label>

In your component declare ViewChild and implement a method to click of label field.

      @ViewChild("firstNameField") firstNameField;

      focusOnFirstName(){
        this.firstNameField.nativeElement.focus();
      }


问:
IMGUR file upload via PHP and cURL
I'm trying to upload an image to IMGUR via PHP.
This is the code:

```<code><?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));

// $data is file data
$pvars   = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl    = curl_init();

curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

$xml = curl_exec($curl);

curl_close ($curl);
</code>```

?>

This is the error message I receive:

Warning: fopen(image.jpg) failed to open stream: No such file or directory

I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob

答:
That warning is because fopen is trying to read in the file image.jpg from the directory from which your script is running.
A good example on how to transfer a file through curl can be seen here

Send file via cURL from form POST in PHP

Where they have $localFile = $_FILES[$fileKey]['tmp_name']; you would put $localFile = '/path/to/image.jpg'; As well as change the server info and add in any other variables you may need to pass to imgur.

ContentLicense: CC BY-SA 3.0

Title: IMGUR file upload via PHP and cURL

Body:
I'm trying to upload an image to IMGUR via PHP.
This is the code:

<?
$filename = "image.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));

// $data is file data
$pvars   = array('image' => base64_encode($data), 'mykey' => IMGUR_API_KEY);
$timeout = 30;
$curl    = curl_init();

curl_setopt($curl, CURLOPT_URL, 'http://api.imgur.com/2/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

$xml = curl_exec($curl);

curl_close ($curl);

?>

This is the error message I receive:

Warning: fopen(image.jpg) failed to open stream: No such file or directory

I don't understand the part: $filename = "image.jpg";
Where does the filename come from since it's a base64 generated string?
Thanks,
Bob


问:
Can't read custom environment variables in node using config.get()
I use config library to manage my configuration files in node application.

I have export my custom env variable in terminal by
  export app_password=12345

and map it into the custom-environment-variable.json file by

```<code>{
  "mail": {
  "password": "app_password"
   }
}
</code>```

when I use config.get('mail.password') in my index.js file (root module) .

I got error: Configuration property "mail.password" is not defined, detail in below:

```<code>/Users/tzhong/Documents/vidly-
backend/node_modules/config/lib/config.js:203
throw new Error('Configuration property "' + property + '" is not
defined');
^

Error: Configuration property "mail.password" is not defined
    at Config.get (/Users/tzhong/Documents/vidly-
 backend/node_modules/config/lib/config.js:203:11)
</code>```

I have use console.log(process.env.app_password) to check if my custom env variable is there, and the app_password show in the terminal.

```<code> Vidly evn is : Vidly backend -- development
 Vidly mail server is : dev-mail-server
 Mail-password is : 12345
 NODE_ENV is : undefined
 app: development
 Mongan enabled...
 Listenning 3000 port ...
</code>```

I want to use console.log(config.get('mail.password')); to show my custom variable in terminal instead of console.log(process.env.app_password)
Any suggestions?

Finally solve the problem :
It's tiny mistake, in config library, the file's name for creating custom environment variable is strict, the file's name should be 'custom-environment-variables.json', I have a wrong spell on 'environment' , after all , thanks for people offer other available package

答:
Instead of using config use .env. Just simply add by typing npm install --save dotenv

```<code>password=some value
</code>```

You can access this by

require("dotenv").config();

console.log(`Password is ${process.env.password}.`);
//Output
Password is *some value*
```

Body:
I use config library to manage my configuration files in node application.

I have export my custom env variable in terminal by
  export app_password=12345

and map it into the custom-environment-variable.json file by

{
  "mail": {
  "password": "app_password"
   }
}

when I use config.get('mail.password') in my index.js file (root module) .

I got error: Configuration property "mail.password" is not defined, detail in below:

/Users/tzhong/Documents/vidly-
backend/node_modules/config/lib/config.js:203
throw new Error('Configuration property "' + property + '" is not
defined');
^

Error: Configuration property "mail.password" is not defined
    at Config.get (/Users/tzhong/Documents/vidly-
 backend/node_modules/config/lib/config.js:203:11)

I have use console.log(process.env.app_password) to check if my custom env variable is there, and the app_password show in the terminal.

 Vidly evn is : Vidly backend -- development
 Vidly mail server is : dev-mail-server
 Mail-password is : 12345
 NODE_ENV is : undefined
 app: development
 Mongan enabled...
 Listenning 3000 port ...

I want to use console.log(config.get('mail.password')); to show my custom variable in terminal instead of console.log(process.env.app_password)
Any suggestions?

Finally solve the problem :
It's tiny mistake, in config library, the file's name for creating custom environment variable is strict, the file's name should be 'custom-environment-variables.json', I have a wrong spell on 'environment' , after all , thanks for people offer other available package

Body:
Instead of using config use .env. Just simply add by typing npm install --save dotenv

password=some value

You can access this by

require("dotenv").config();

console.log(`Password is ${process.env.password}.`);
//Output
Password is *some value*


问:
Where to store client data in angular which is later used in REST-API for getting information
I have an angular application, Whenever a user logs in I get all his data along with a jsonwebtoken from server through REST-API request and store it in localstorage.

After that I use the same user data such as email, account_status, id etc  in other REST-API calls for getting more information. This is obviously not the correct way to do, The user can modify his localstorage data and get other user's information easily.

I am using jsonwebtoken for authentication, verifying the token in authgaurd service through REST-API call.

Can anybody suggest the correct way to store the information with brief description.
Can I use Cookies for the issue?

答:
Create a shared service and import in app module , use it in all components ,

```<code>import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import { MyWrapper } from '../models/models';

@Injectable()
export class SharedService{

  data:any={};

  setData(key,value) {
     this.data[key]=value;
  }

  clearData() {
     this.data={};
  }

  getData(key) {
    return this.data[key];
  }

}
</code>```

Note : This is will not work exactly as local storage, you'll lose data once the browser closed or page refreshed kind of session storage, but still you can put and get data across components.

To set data,

```<code> sharedService.setData("mydata","mydata");
</code>```

To get data,

```<code> sharedService.getData("mydata");
</code>```

If you want the data to be persistent then  alternative ways are you can store the data in the server and get the data in ngOnInit or use some kind of encryption(jsencrypt or cryptojs) when storing the data in local storage so user wont able to modify it.Still it will not be a bullet proof solution.If you are storing some sensitive data , I would recommend you to store it in server.

Body:
Create a shared service and import in app module , use it in all components ,

import { Injectable } from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import { MyWrapper } from '../models/models';

@Injectable()
export class SharedService{

  data:any={};

  setData(key,value) {
     this.data[key]=value;
  }

  clearData() {
     this.data={};
  }

  getData(key) {
    return this.data[key];
  }

}

Note : This is will not work exactly as local storage, you'll lose data once the browser closed or page refreshed kind of session storage, but still you can put and get data across components.

To set data,

 sharedService.setData("mydata","mydata");

To get data,

 sharedService.getData("mydata");

If you want the data to be persistent then  alternative ways are you can store the data in the server and get the data in ngOnInit or use some kind of encryption(jsencrypt or cryptojs) when storing the data in local storage so user wont able to modify it.Still it will not be a bullet proof solution.If you are storing some sensitive data , I would recommend you to store it in server.


问:
Watch app starts with error clientIdentifier for interfaceControllerID not found
I'm having a smartwatch app on watchos2. The app always worked but now when it starts I immediately get this error:

```<code>Lop_WatchKit_Extension[17535:7854201] *********** ERROR -[SPRemoteInterface _interfaceControllerClientIDForControllerID:] clientIdentifier for interfaceControllerID:447E0002 not found
</code>```

I found some topics here on stackoverflow but nothing solved the problem.

答:
If you use didSet on any IBOutlets it will also throw this error in the logs.

class MyInterfaceController: WKInterfaceController {

  @IBOutlet var myLabel: WKInterfaceLabel! {
    didSet {
      myLabel.setTitle("Test")
    }
  }
```

Body:
I'm having a smartwatch app on watchos2. The app always worked but now when it starts I immediately get this error:

Lop_WatchKit_Extension[17535:7854201] *********** ERROR -[SPRemoteInterface _interfaceControllerClientIDForControllerID:] clientIdentifier for interfaceControllerID:447E0002 not found

I found some topics here on stackoverflow but nothing solved the problem.


问:
Nodemon, in express.js, executes a file other than what is specified in package.json, I
Starting up a node.js express app with nodemon. If I run my app with

```<code>nodemon
</code>```

with no file specified, it starts index.js. Which fires up my express app, no problems. However, I am confused as to how it determined index.js was the correct file to start up. I looked in the package.json, for the 'main' and 'scripts' it specifies server.js, like below. Is index.js a fallback file to run for nodemon?

```<code>"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
</code>```

答:
Yes, If no configuration is given nodemon looks for index.js.

```<code>nodemon can be run in a number of ways:

`nodemon` - tries to use package.json#main property to run
`nodemon` - if no package, looks for index.js
`nodemon app.js` - runs app.js
`nodemon --arg app.js --apparg` - eats arg1, and runs app.js with apparg
`nodemon --apparg` - as above, but passes apparg to package.json#main (or
  index.js)
`nodemon --debug app.js
</code>```

https://github.com/remy/nodemon/blob/master/lib/cli/parse.js#L9

Body:
Starting up a node.js express app with nodemon. If I run my app with

nodemon

with no file specified, it starts index.js. Which fires up my express app, no problems. However, I am confused as to how it determined index.js was the correct file to start up. I looked in the package.json, for the 'main' and 'scripts' it specifies server.js, like below. Is index.js a fallback file to run for nodemon?

"description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Body:
Yes, If no configuration is given nodemon looks for index.js.

nodemon can be run in a number of ways:

`nodemon` - tries to use package.json#main property to run
`nodemon` - if no package, looks for index.js
`nodemon app.js` - runs app.js
`nodemon --arg app.js --apparg` - eats arg1, and runs app.js with apparg
`nodemon --apparg` - as above, but passes apparg to package.json#main (or
  index.js)
`nodemon --debug app.js

https://github.com/remy/nodemon/blob/master/lib/cli/parse.js#L9


问:
Could not find com.android.tools.lint:lint-gradle Android Studio 3
I have updated Android Studio to 3.0 and now received a lot of issues.. now stoped on point with such issue:

```<code>Could not resolve all files for configuration ':applib:_lintClassPath'.
> Could not find com.android.tools.lint:lint-gradle:26.1.0-alpha01.
  Searched in the following locations:
      file:/Users/anwender/Library/Android/sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/Library/Android/sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/Library/Android/sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      https://jitpack.io/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      https://jitpack.io/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/dev/project/dk_shopping_checklist/augmented/libs/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/dev/project/dk_shopping_checklist/augmented/libs/lint-gradle.jar
  Required by:
      project :applib
</code>```

Does someone know what the issue can be?

Gradle.build:

```<code>apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 26
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:+'
}
</code>```

I'm using latest gradle version: "gradle-4.2.1-all.zip".

答:
I have changed my current gradle version(3.3.2  to 3.2.1) from the global build.gradle file.

```<code>buildscript {
 repositories {
    google()
    jcenter()
    maven { url 'https://maven.google.com' }
 }

 dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
 }
}

allprojects {
 repositories {
    google()
    jcenter()
    maven { url 'https://maven.google.com' }
 }
}
</code>```

then click on sync gradle button on the top right corner of the screen.

Body:
I have updated Android Studio to 3.0 and now received a lot of issues.. now stoped on point with such issue:

Could not resolve all files for configuration ':applib:_lintClassPath'.
> Could not find com.android.tools.lint:lint-gradle:26.1.0-alpha01.
  Searched in the following locations:
      file:/Users/anwender/Library/Android/sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/Library/Android/sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/Library/Android/sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      file:/Users/anwender/Library/Android/sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      https://jitpack.io/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.pom
      https://jitpack.io/com/android/tools/lint/lint-gradle/26.1.0-alpha01/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/dev/project/dk_shopping_checklist/augmented/libs/lint-gradle-26.1.0-alpha01.jar
      file:/Users/anwender/dev/project/dk_shopping_checklist/augmented/libs/lint-gradle.jar
  Required by:
      project :applib

Does someone know what the issue can be?

Gradle.build:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 26
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:+'
}

I'm using latest gradle version: "gradle-4.2.1-all.zip".

Body:
I have changed my current gradle version(3.3.2  to 3.2.1) from the global build.gradle file.

buildscript {
 repositories {
    google()
    jcenter()
    maven { url 'https://maven.google.com' }
 }

 dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
 }
}

allprojects {
 repositories {
    google()
    jcenter()
    maven { url 'https://maven.google.com' }
 }
}

then click on sync gradle button on the top right corner of the screen.


问:
self.tabBarController?.selectedIndex and perform function in another view controller
I have 4 view controllers in tab bar controller and each embedded with navigation controller. The problem is, I have researched and find the best way to navigate from Viewcontroller0 to Viewcontroller 1 in tab Bar is to use self.tabBarController?.selectedIndex = 1, and it works properly. However, I wish to do the function immediately after the navigation. The following is my attempt but did not work. Anyone have the idea? Big Thanks.

```<code>  @IBAction func GOGOBut(_ sender: Any) {

    self.tabBarController?.selectedIndex = 1

    if let VC = presentingViewController as? TutorViewController {
        VC.observeBBCases()
    }
    //NotificationCenter.default.post(name:  NSNotification.Name(rawValue: "loadBAFS"), object: nil)

}
</code>```

observeBBCases() is the function in TutorViewController
And self.tabBarController?.selectedIndex = 1 is to go the TutorViewController

答:
First get the UINavigationController which contains TutorViewController using the index 1. And get the root view controller TutorViewController of the navigation controller. Then you can call the method observeBBCases

```<code>@IBAction func GOGOBut(_ sender: Any) {
    if let navigationController = self.tabBarController?.viewControllers?[1] as? UINavigationController,
        let vc = navigationController.viewControllers.first as? TutorViewController {
            vc.observeBBCases()
            self.tabBarController?.selectedIndex = 1
    }
}
</code>```

Body:
I have 4 view controllers in tab bar controller and each embedded with navigation controller. The problem is, I have researched and find the best way to navigate from Viewcontroller0 to Viewcontroller 1 in tab Bar is to use self.tabBarController?.selectedIndex = 1, and it works properly. However, I wish to do the function immediately after the navigation. The following is my attempt but did not work. Anyone have the idea? Big Thanks.

  @IBAction func GOGOBut(_ sender: Any) {

    self.tabBarController?.selectedIndex = 1

    if let VC = presentingViewController as? TutorViewController {
        VC.observeBBCases()
    }
    //NotificationCenter.default.post(name:  NSNotification.Name(rawValue: "loadBAFS"), object: nil)

}

observeBBCases() is the function in TutorViewController
And self.tabBarController?.selectedIndex = 1 is to go the TutorViewController

Body:
First get the UINavigationController which contains TutorViewController using the index 1. And get the root view controller TutorViewController of the navigation controller. Then you can call the method observeBBCases

@IBAction func GOGOBut(_ sender: Any) {
    if let navigationController = self.tabBarController?.viewControllers?[1] as? UINavigationController,
        let vc = navigationController.viewControllers.first as? TutorViewController {
            vc.observeBBCases()
            self.tabBarController?.selectedIndex = 1
    }
}


问:
Getting items from object within JSON
I am trying to create a React component that displays results from a test in various courses. I'm unable to access the scores object within the json file. Here is a sample of the json file I'm working with.

```<code>[
    {
    "length": "15",
    "average": "77",
    "created_at": "2019-02-01",
    "course": "MATH311",

    "scores": [
      {
        "correct": "12",
        "student_id": "1"
      },
      {
        "correct": "9",
        "student_id": "2"
      }
    ]
  },
  {
    "length": "25",
    "average": "17",
    "created_at": "2019-02-03",
    "course": "MATH301",

    "scores": [
      {
        "correct": "11",
        "student_id": "3"
      },
      {
        "correct": "17",
        "student_id": "4"
      },
      {
        "correct": "20",
        "student_id": "5"
      },
      {
        "correct": "18",
        "student_id": "6"
      }
    ]
  }
]
</code>```

From this, I want to create a component that displays a card for each exam and contains the "course", "average", "length", and each of the scores. I can get the course, average, and length but cannot get every score because it's an object of its own. The number of scores will vary.

My code looks something like this.

```<code><div className="exams">
{exams && exams.map((exam,index) => {
    return(
        <div>
            <p>{exam.course}</p>
            <p>{exam.average}</p>
            <p>{exam.length}</p>
            <div>
              {exam["scores"][0].id}
              {exam["scores"][0].correct}
            </div>

        </div>
    )
})}
</div>
</code>```

答:
Scores are not an object, they are an array. So you have to map over them just as you did with the exams.

```<code>  exams.map((exam, index) => (
    <div key={index}>
      <p>{exam.course}</p>
      <p>{exam.average}</p>
      <p>{exam.length}</p>
      {exam.scores.map((scores, i) => (
        <div key={scores.student_id}>
          <p>{scores.correct}</p>
          <p>{scores.student_id}</p>
        </div>
      ))}
    </div>
  ));
</code>```

Title: Getting items from object within JSON

Body:
I am trying to create a React component that displays results from a test in various courses. I'm unable to access the scores object within the json file. Here is a sample of the json file I'm working with.

[
    {
    "length": "15",
    "average": "77",
    "created_at": "2019-02-01",
    "course": "MATH311",

    "scores": [
      {
        "correct": "12",
        "student_id": "1"
      },
      {
        "correct": "9",
        "student_id": "2"
      }
    ]
  },
  {
    "length": "25",
    "average": "17",
    "created_at": "2019-02-03",
    "course": "MATH301",

    "scores": [
      {
        "correct": "11",
        "student_id": "3"
      },
      {
        "correct": "17",
        "student_id": "4"
      },
      {
        "correct": "20",
        "student_id": "5"
      },
      {
        "correct": "18",
        "student_id": "6"
      }
    ]
  }
]

From this, I want to create a component that displays a card for each exam and contains the "course", "average", "length", and each of the scores. I can get the course, average, and length but cannot get every score because it's an object of its own. The number of scores will vary.

My code looks something like this.

{exams && exams.map((exam,index) => {
    return(

{exam.course}

{exam.average}

{exam.length}

              {exam["scores"][0].id}
              {exam["scores"][0].correct}

    )
})}

Body:
Scores are not an object, they are an array. So you have to map over them just as you did with the exams.

  exams.map((exam, index) => (
    <div key={index}>
      <p>{exam.course}</p>
      <p>{exam.average}</p>
      <p>{exam.length}</p>
      {exam.scores.map((scores, i) => (
        <div key={scores.student_id}>
          <p>{scores.correct}</p>
          <p>{scores.student_id}</p>
        </div>
      ))}
    </div>
  ));


问:
how to use nested loop join instead of block nested loop join in MySQL?
For the sake of comparison, I am looking for a way to disable block nested loop join and use a simple nested loop join, instead.
Based on MySQL's reference manual, they are both implemented:
https://dev.mysql.com/doc/refman/8.0/en/nested-loop-joins.html
But I've failed to find out how to alter the options to do so!</p>

答:
You can fine tune the behaviour of the optimizer by setting the optimizer_switch system variable:

The optimizer_switch system variable enables control over optimizer behavior. Its value is a set of flags, each of which has a value of on or off to indicate whether the corresponding optimizer behavior is enabled or disabled. This variable has global and session values and can be changed at runtime. The global default can be set at server startup.

[...]

Block Nested-Loop Flags

block_nested_loop (default on)

Controls use of BNL join algorithm.

To completely disable block nested join and using default values for everything else, you can use

```<code>SET optimizer_switch='block_nested_loop=off';
</code>```

An alternative is to use Optimizer hints,

Another way to control the optimizer is by using optimizer hints, which can be specified within individual statements. Because optimizer hints apply on a per-statement basis, they provide finer control over statement execution plans than can be achieved using optimizer_switch. For example, you can enable an optimization for one table in a statement and disable the optimization for a different table. Hints within a statement take precedence over optimizer_switch flags.

[...]

BNL, NO_BNL: Enable or disable BNL for the specified tables.

You can use e.g.

```<code>SELECT /*+ NO_BNL() */ t1.* FROM t1 INNER JOIN t2 INNER JOIN t3;
</code>```

Body:
You can fine tune the behaviour of the optimizer by setting the optimizer_switch system variable:

The optimizer_switch system variable enables control over optimizer behavior. Its value is a set of flags, each of which has a value of on or off to indicate whether the corresponding optimizer behavior is enabled or disabled. This variable has global and session values and can be changed at runtime. The global default can be set at server startup.

[...]

Block Nested-Loop Flags

block_nested_loop (default on)

Controls use of BNL join algorithm.

To completely disable block nested join and using default values for everything else, you can use

SET optimizer_switch='block_nested_loop=off';

An alternative is to use Optimizer hints,

Another way to control the optimizer is by using optimizer hints, which can be specified within individual statements. Because optimizer hints apply on a per-statement basis, they provide finer control over statement execution plans than can be achieved using optimizer_switch. For example, you can enable an optimization for one table in a statement and disable the optimization for a different table. Hints within a statement take precedence over optimizer_switch flags.

[...]

BNL, NO_BNL: Enable or disable BNL for the specified tables.

You can use e.g.

SELECT /*+ NO_BNL() */ t1.* FROM t1 INNER JOIN t2 INNER JOIN t3;


问:
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use random.seed(), a for statement and a multiplication. I understand that the random.seed([x]) generates an initial value that could be used in the proceeding section of the code. However, I can't figure out how to proceed after obtaining the value of the random:

```<code>import random
random.seed(70)
print(random.random()) # This returns a value of 0.909769237923872
</code>```

How do I use this value to generate a random value between 30 and 35?

Note: Without the specific directions above, I have been able to write two codes that function as desired, so please I am not looking for alternative ways of writing the code.

答:
Here is a general code to find random number between any two floating point numbers.

```<code>from random import random, seed

def rand_no(x_lower, x_upper):
    '''
    Function to generate random number
    x_lower     :   lower bound value
    x_upper     :   upper bound value
    '''
    random_number = x_lower + (x_upper - x_lower)*random()
    return random_number

if __name__ == '__main__':

    seed_value = 70 # Seed value for random generator
    seed(seed_value)

    print('Printing a list of 10 random numbers\n')
    for i in range(10):
        sample_value = rand_no(30, 35)
        print("Number %d = %4.2f"%(i+1, sample_value))
</code>```

Output is as follows:

```<code>Printing a list of 10 random numbers

Number 1 = 34.55
Number 2 = 31.47
Number 3 = 32.30
Number 4 = 30.68
Number 5 = 34.98
Number 6 = 30.77
Number 7 = 33.37
Number 8 = 32.99
Number 9 = 33.57
Number 10 = 32.05
</code>```

Body:
I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use random.seed(), a for statement and a multiplication. I understand that the random.seed([x]) generates an initial value that could be used in the proceeding section of the code. However, I can't figure out how to proceed after obtaining the value of the random:

import random
random.seed(70)
print(random.random()) # This returns a value of 0.909769237923872

How do I use this value to generate a random value between 30 and 35?

Note: Without the specific directions above, I have been able to write two codes that function as desired, so please I am not looking for alternative ways of writing the code.

Body:
Here is a general code to find random number between any two floating point numbers.

from random import random, seed

def rand_no(x_lower, x_upper):
    '''
    Function to generate random number
    x_lower     :   lower bound value
    x_upper     :   upper bound value
    '''
    random_number = x_lower + (x_upper - x_lower)*random()
    return random_number

if __name__ == '__main__':

    seed_value = 70 # Seed value for random generator
    seed(seed_value)

    print('Printing a list of 10 random numbers\n')
    for i in range(10):
        sample_value = rand_no(30, 35)
        print("Number %d = %4.2f"%(i+1, sample_value))

Output is as follows:

Printing a list of 10 random numbers

Number 1 = 34.55
Number 2 = 31.47
Number 3 = 32.30
Number 4 = 30.68
Number 5 = 34.98
Number 6 = 30.77
Number 7 = 33.37
Number 8 = 32.99
Number 9 = 33.57
Number 10 = 32.05


问:
Why is my query turning into a boolean and how do I prevent this, so I can iterate over it?
I've created a link in the template that points to a route which should render a page that allows the user to see the name of the person logged in, as well as all the posts they've ever made. I made the necessary queries, but it's telling me that TypeError:

Bool is not iterable.

I tried to convert the variable into a string, but it doesn't show the information I need. I actually need access to the whole table so that I can customize what shows up on the template. In particular I need a for loop to go through all the entries in the table and list each one by the column I specify.

This is the route:

```<code>@app.route('/users/<id>/view')
def view_user(id):
    mysql = connectToMySQL('quotes_dash2')
    query = 'SELECT * FROM quotes WHERE user_id = %(q_id);'
    data = {
        "q_id": id
    }
    userQuotes = mysql.query_db(query, data)

    mysql2 = connectToMySQL('quotes_dash2')
    query2 = "SELECT * FROM users WHERE id = %(us_id);"
    data2 = {
        "us_id": session['userid']
    }
    our_user = mysql2.query_db(query2, data2)

    return render_template('view.html', userQuotes = userQuotes, ourUser = our_user)
</code>```

And this is the template that I am trying to create (bare html):

```<code><h1>{{ourUser['first_name']}} {{ourUser['last_name']}}'s Quotes</h1>

    <ul>
        {% for quote in userQuotes %}
        <li>
            {{ quote['author'] }}: {{ quote['quote_content'] }}
            <hr>
        </li>

        {% endfor %}
    </ul>
</code>```

I expect it so that when I click on the user's name (from another page), it will bring me to a view page that has the user's name at the top, along with all the posts that the user made (they're quotes with authors). What I'm getting instead is:

TypeError: 'bool' object is not iterable

And the traceback is focusing on:

```<code>return render_template('view.html', userQuotes = userQuotes, ourUser = our_user)
</code>```

and

```<code>{% for quote in userQuotes %}
</code>```

I get it that userQuotes is a bool, but I did not intend for it to be that way, and I don't know how to change it so I can iterate through the table represented by userQuotes.

Any help would be greatly appreciated!

答: I figured out the problem. It's working now. In case anyone else runs into this problem and is curious, the problem was that I accidentally forgot to type the letter "s" after the end parentheses in the queries. So, it should've been %(us_id)s instead of %(us_id).</p>

Body:
I've created a link in the template that points to a route which should render a page that allows the user to see the name of the person logged in, as well as all the posts they've ever made. I made the necessary queries, but it's telling me that TypeError:

Bool is not iterable.

I tried to convert the variable into a string, but it doesn't show the information I need. I actually need access to the whole table so that I can customize what shows up on the template. In particular I need a for loop to go through all the entries in the table and list each one by the column I specify.

This is the route:

@app.route('/users/<id>/view')
def view_user(id):
    mysql = connectToMySQL('quotes_dash2')
    query = 'SELECT * FROM quotes WHERE user_id = %(q_id);'
    data = {
        "q_id": id
    }
    userQuotes = mysql.query_db(query, data)

    mysql2 = connectToMySQL('quotes_dash2')
    query2 = "SELECT * FROM users WHERE id = %(us_id);"
    data2 = {
        "us_id": session['userid']
    }
    our_user = mysql2.query_db(query2, data2)

    return render_template('view.html', userQuotes = userQuotes, ourUser = our_user)

And this is the template that I am trying to create (bare html):

{{ourUser['first_name']}} {{ourUser['last_name']}}'s Quotes

        {% for quote in userQuotes %}

            {{ quote['author'] }}: {{ quote['quote_content'] }}

        {% endfor %}

I expect it so that when I click on the user's name (from another page), it will bring me to a view page that has the user's name at the top, along with all the posts that the user made (they're quotes with authors). What I'm getting instead is:

TypeError: 'bool' object is not iterable

And the traceback is focusing on:

return render_template('view.html', userQuotes = userQuotes, ourUser = our_user)

and

{% for quote in userQuotes %}

I get it that userQuotes is a bool, but I did not intend for it to be that way, and I don't know how to change it so I can iterate through the table represented by userQuotes.

Any help would be greatly appreciated!


答:
As Scores is an array and not an object, use map to iterate over all entries of scores. Like this:

```<code>  <div className="exams">
    {exams && exams.map((exam,index) => { return(
    <div>
        <p>{exam.course}</p>
        <p>{exam.average}</p>
        <p>{exam.length}</p>
        <div>

            {exam && exam["scores"] && exam["scores"].map((score,index) => { return(
            <div>
                {score.correct} {score.student_id}

            </div>
            ) } )}
        </div>

    </div>
    ) })}
</div>
</code>```

Title: Getting items from object within JSON

Body:
As Scores is an array and not an object, use map to iterate over all entries of scores. Like this:

  <div className="exams">
    {exams && exams.map((exam,index) => { return(
    <div>
        <p>{exam.course}</p>
        <p>{exam.average}</p>
        <p>{exam.length}</p>
        <div>

            {exam && exam["scores"] && exam["scores"].map((score,index) => { return(
            <div>
                {score.correct} {score.student_id}

            </div>
            ) } )}
        </div>

    </div>
    ) })}
</div>


答:
exam.scores is an array. With javascript you can iterate over it with map, generating a jsx element for each item in exam.scores just like you already did for the exams array. The code may look like this

```<code><div>
    {exam.scores.map(score => {
        return(
            <div key={score.student.id}>
                <p>score: {score.correct}</p>
            </div>
        )
    }}
</div>
</code>```

You need to make sure that each child element has a unique key value when you map over an array.

Title: Getting items from object within JSON

Body:
exam.scores is an array. With javascript you can iterate over it with map, generating a jsx element for each item in exam.scores just like you already did for the exams array. The code may look like this

<div>
    {exam.scores.map(score => {
        return(
            <div key={score.student.id}>
                <p>score: {score.correct}</p>
            </div>
        )
    }}
</div>

You need to make sure that each child element has a unique key value when you map over an array.


问:
AMP with Ruby on Rails : Impossible to use a a Google Font
I am implementing AMP pages on my Rails app. However I can't get my font to work. It raises this error on the Google Search Console :

"CSS syntax error in the "amp-custom style" tag. Incorrect declaration."
Ligne 14:63 quot;Raleway", sans-serif}.banner{color:white;tex...

This is my application.amp.erb

```<code><!doctype html>
<html ⚡>
  <head>
    <meta charset="utf-8">
    <link rel="canonical" href="<%= url_for(format: :html, only_path: false) %>" >
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script>
    <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
    <script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
    <script async custom-element="amp-font" src="https://cdn.ampproject.org/v0/amp-font-0.1.js"></script>
    <% if Rails.application.assets && Rails.application.assets['amp/application'] %>
      <style amp-custom>
        <%= Rails.application.assets['amp/application'].to_s.html_safe %>
      </style>
    <% else %>
    <style amp-custom><%= File.read "#{Rails.root}/public#{stylesheet_path('amp/application', host: nil)}" %>
    </style>
    <% end %>
  </head>
  <body>
    <amp-font
      layout="nodisplay"
      timeout="3000"
      font-family="Raleway">
    </amp-font>
    <div class="amp">
      <%= render "shared/navbar" %>
      <%= yield %>
    </div>
  </body>
</html>`
</code>```

And the beginning of my application.scss that I import for my AMP views which triggers the error on the Google Console :

```<code>body {
  font-family: "Raleway", sans-serif;
}
</code>```

I tried everything, @font-face included, but nothing worked.

However, according to the official documentation (https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/custom_fonts) the link syntax should work with Google Fonts which is obviously a white-listed font provider allowed by AMP.

答:
A couple of things about the @font-face method.

The @font-face line has to be the FIRST line in your CSS stylesheet. Put all fonts imported this way at the top of the stylesheet.

It can be tricky linking to Google URLs, because Google gives a different URL for every browser when you get the actual font path. Raleway in Safari on my new MacBook gets the new woff2 format:

url('https://fonts.gstatic.com/s/raleway/v13/1Ptug8zYS_SKggPNyC0IT4ttDfA.woff2') format('woff2');

Use a different computer and Google serves up an older woff font:
url('https://fonts.gstatic.com/s/raleway/v13/1Ptug8zYS_SKggPNyC0ISQ.woff) format('woff');

These will work, if your browser happens to be the one you were using when you got the font link, or equivalent. I couldn't get @font-face to work with the link in your HTML head:
href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap". It seems to need a link to the actual font file, whether .ttf or .woff or .woff2.

The surest way is probably to download the font from Google, and use @font-face with the actual path to the font residing with the rest of your Rails application assets. Something like:

```<code><style type = "text/css">
@font-face {
font-family: 'Raleway Regular';
src:url('/app_assets/Raleway/Raleway-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

body {
font-family: 'Raleway Regular';
}
</style>
</code>```

(I just put the style tags to demonstrate that nothing can go before the @font-face line in the stylesheet.)

To download, go to the Raleway font at Google Fonts. Select it with the red plus sign, then open the menu at the bottom of the page. Click the download arrow:

The downloaded folder will contain 18 different style of Raleway, from Raleway-Regular.ttf to Raleway-BlackItalic.ttf to Raleway-Thin.ttf. You can use only the regular style like I did, or link them all in their own @font-face tags at the top of the CSS page.

Body:
I am implementing AMP pages on my Rails app. However I can't get my font to work. It raises this error on the Google Search Console :

"CSS syntax error in the "amp-custom style" tag. Incorrect declaration."
Ligne 14:63 quot;Raleway", sans-serif}.banner{color:white;tex...

This is my application.amp.erb

<!doctype html>

    <meta charset="utf-8">
    <link rel="canonical" href="<%= url_for(format: :html, only_path: false) %>" >
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap" rel="stylesheet">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">

    <% if Rails.application.assets && Rails.application.assets['amp/application'] %>

    <% else %>

    <% end %>

    <amp-font
      layout="nodisplay"
      timeout="3000"
      font-family="Raleway">
    </amp-font>

      <%= render "shared/navbar" %>
      <%= yield %>

`

And the beginning of my application.scss that I import for my AMP views which triggers the error on the Google Console :

body {
  font-family: "Raleway", sans-serif;
}

I tried everything, @font-face included, but nothing worked.

However, according to the official documentation (https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/custom_fonts) the link syntax should work with Google Fonts which is obviously a white-listed font provider allowed by AMP.

Body:
A couple of things about the @font-face method.

The @font-face line has to be the FIRST line in your CSS stylesheet. Put all fonts imported this way at the top of the stylesheet.

It can be tricky linking to Google URLs, because Google gives a different URL for every browser when you get the actual font path. Raleway in Safari on my new MacBook gets the new woff2 format:

url('https://fonts.gstatic.com/s/raleway/v13/1Ptug8zYS_SKggPNyC0IT4ttDfA.woff2') format('woff2');

Use a different computer and Google serves up an older woff font:
url('https://fonts.gstatic.com/s/raleway/v13/1Ptug8zYS_SKggPNyC0ISQ.woff) format('woff');

These will work, if your browser happens to be the one you were using when you got the font link, or equivalent. I couldn't get @font-face to work with the link in your HTML head:
href="https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap". It seems to need a link to the actual font file, whether .ttf or .woff or .woff2.

The surest way is probably to download the font from Google, and use @font-face with the actual path to the font residing with the rest of your Rails application assets. Something like:

<style type = "text/css">
@font-face {
font-family: 'Raleway Regular';
src:url('/app_assets/Raleway/Raleway-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

body {
font-family: 'Raleway Regular';
}
</style>

(I just put the style tags to demonstrate that nothing can go before the @font-face line in the stylesheet.)

To download, go to the Raleway font at Google Fonts. Select it with the red plus sign, then open the menu at the bottom of the page. Click the download arrow:

The downloaded folder will contain 18 different style of Raleway, from Raleway-Regular.ttf to Raleway-BlackItalic.ttf to Raleway-Thin.ttf. You can use only the regular style like I did, or link them all in their own @font-face tags at the top of the CSS page.


问:
Hide a list except the selected list option
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

```<code><ul class="links">
  <li class="us">United States</li>
  <li class="canada">Canada</li>
  <li class="france">France</li>
  <li class="china">China</li>
  <li class="englande">England</li>
</code>```

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

答:
Something like this will do the trick:

```<code>// Initially hide everything apart from the active list item
$('ul li.active').show()
  .siblings().hide();

// Set up a click handler that will show all the list items when the active
// element is clicked on, or makes the clicked on item the active item and hides
// the rest.
$('ul li').click(function(){
  var $parent=$(this).parent();
  if ($parent.is('.open')){
    $parent.removeClass('open');
    $(this).addClass('active')
      .siblings().removeClass('active').hide();
  }
  else {
    $parent.addClass('open').children().show();
  }
});
</code>```

Here is a working JSBIN example: http://jsbin.com/onile4

Hope this helps!

Body:
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

United States

Canada

France

China

England

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

Body:
Something like this will do the trick:

// Initially hide everything apart from the active list item
$('ul li.active').show()
  .siblings().hide();

// Set up a click handler that will show all the list items when the active
// element is clicked on, or makes the clicked on item the active item and hides
// the rest.
$('ul li').click(function(){
  var $parent=$(this).parent();
  if ($parent.is('.open')){
    $parent.removeClass('open');
    $(this).addClass('active')
      .siblings().removeClass('active').hide();
  }
  else {
    $parent.addClass('open').children().show();
  }
});

Here is a working JSBIN example: http://jsbin.com/onile4

Hope this helps!


问:
Convert a Long/ULong to an unsigned hexadecimal string with padding zeros
How to convert a Long/ULong representing an unsigned long to an unsigned hexadecimal string with padding zeros (a 16-digit hexadecimal string)?

I am looking for a simple and neat solution in Kotlin or Java.

答:
I have found the solution using x/X in String.format():

```<code>fun Long.to16DigitUnsignedLowercaseHexString() =
    "%016x".format(this)

fun Long.to16DigitUnsignedUppercaseHexString() =
    "%016X".format(this)
</code>```

I have tested that it works for boundary values 0L, 1L, Long.MAX_VALUE, -1L, and Long.MIN_VALUE, so there should be no problems.

A similar question is asked in java - How can I pad an integer with zeros on the left? - Stack Overflow. When looking at this for the first time, I didn't expect it to work because I thought that x/X is for signed hexadecimal formatting. It turned out I was wrong and x/X is exactly for unsigned hexadecimal formatting.

Body:
I have found the solution using x/X in String.format():

fun Long.to16DigitUnsignedLowercaseHexString() =
    "%016x".format(this)

fun Long.to16DigitUnsignedUppercaseHexString() =
    "%016X".format(this)

I have tested that it works for boundary values 0L, 1L, Long.MAX_VALUE, -1L, and Long.MIN_VALUE, so there should be no problems.

A similar question is asked in java - How can I pad an integer with zeros on the left? - Stack Overflow. When looking at this for the first time, I didn't expect it to work because I thought that x/X is for signed hexadecimal formatting. It turned out I was wrong and x/X is exactly for unsigned hexadecimal formatting.


问:
xarray n00b question: can it handle irregularly sized matrices?
What I'm trying to do is something like this:

```<code>x['a'] = np.array( [1,2,3] ) # 1x3
x['b'] = np.array( [ (1,2,3), (4,5,6) ] ) # 2x3
# a and b differ in the size of their first dimension
</code>```

My first intuition is a dictionary of arrays/pandas Dataframes but maybe xarray can handle this more elegantly.  I did a quick scan of the documentation and examples but didn't see what I was looking for.

Any pointers would be appreciated. Thank you. :)

答: Opps, the functionality I'm looking for is in xarray.Datasets.</p>

Body:
What I'm trying to do is something like this:

x['a'] = np.array( [1,2,3] ) # 1x3
x['b'] = np.array( [ (1,2,3), (4,5,6) ] ) # 2x3
# a and b differ in the size of their first dimension

My first intuition is a dictionary of arrays/pandas Dataframes but maybe xarray can handle this more elegantly.  I did a quick scan of the documentation and examples but didn't see what I was looking for.

Any pointers would be appreciated. Thank you. :)


问:
Does number pipe number:'1.0-0' rounds the number?
I was using number:'1.0-0' to hide any decimal places.
Does it round off the number coz I have heard some say it does if it does then that would be a problem for me.</p>

```<code>{{file?.progress | number:'1.0-0'}}
</code>```

答:
It will round, as mentioned in angular docs:

If no parameters are specified, the function rounds off to the nearest value using this rounding method. The behavior differs from that of the JavaScript Math.round() function. In the following case for example, the pipe rounds down where Math.round() rounds up:

```<code>-2.5 | number:'1.0-0'
> -3
Math.round(-2.5)
> -2
</code>```

https://angular.io/api/common/DecimalPipe

Body:
I was using number:'1.0-0' to hide any decimal places.
Does it round off the number coz I have heard some say it does if it does then that would be a problem for me.

{{file?.progress | number:'1.0-0'}}

Body:
It will round, as mentioned in angular docs:

If no parameters are specified, the function rounds off to the nearest value using this rounding method. The behavior differs from that of the JavaScript Math.round() function. In the following case for example, the pipe rounds down where Math.round() rounds up:

-2.5 | number:'1.0-0'
> -3
Math.round(-2.5)
> -2

https://angular.io/api/common/DecimalPipe


问:
VBA Code just stops in the middle execution with out completing code (NOT A HANG)
I have some code that is copying a upwards of 1K files or so from a network drive to a SharePoint site.  When it has completed that task, It calls the following sub.  When I step through the code it seems to work fine, and it worked fine on some of the smaller lists I uploaded.  However when I just let it run it magically stops executing code and behaves as if everything has successfully been executed.  I know it hasn't because The workbook I picked to be open is still open and the workbook I am running the code from is blank.

The best I can surmise is the code stops executing right around:

SourceWB.Sheets("Sheet1").Activate

Because the destination sheet is still blank, I am pretty sure the cells.copy is not executing.  The only other thing I can think of is it somehow is grabbing the Destination worksheet as the source work sheet, so nothing actually gets copied and I wind up with a blank sheet.  I rule that out though as at the end of my main sub a message box is supposed to appear when things are complete and no message box appears.

Can anyone spot an issue or shed some light on what may be happening.  Frustrating that it works when stepping through. (as long as there is a break point afterwards)

```<code>Sub ImportIndex()

'Copies Sheet1 from a user selected workbook
'into current work book

    Dim DestinationWS As Worksheet
    Dim DestinationR As Range
    Dim SourceWB As Workbook
    Dim FilenameWB As String

    'clear sheet1 of any previous data/formats etc
    Clear_Worksheet ("Sheet1")

    'Set the location of where the sheet is to be copied to
    Set DestinationWS = ThisWorkbook.Sheets("Sheet1")
    Set DestinationR = DestinationWS.Range("A1")

    'Open the source workbook through file picker
    '****************************************************************
    'Error may occur if workbook is already open
    'Look into how to deal with this in the future
    '****************************************************************
    FilenameWB = Application.GetOpenFilename()

    Set SourceWB = Workbooks.Open(Filename:=FilenameWB)

    'Ensure "sheet1" is the active worksheet
    SourceWB.Sheets("Sheet1").Activate

    'Copies active wrokesheet to Destination
    Cells.Copy DestinationR

    'close the source workbook without saving changes
    SourceWB.Close savechanges:=False

End Sub
</code>```

I did look at the following question, but it was related to Word.  According to one comment, the most recent build seems to have solved their issue.

Clearworksheet function as requested

```<code>Sub Clear_Worksheet(Sheetname As String)
'Deletes all cells in the provide worksheet name
'currently will cause an error if the sheet does not exist
    With ThisWorkbook.Sheets(Sheetname)
        .Cells.Delete Shift:=xlUp
        Range("A1").Activate 'probably do no need this activate
    End With

End Sub
</code>```

I just re ran the code with the elimination of ACTIVATE and also having removed all stepping break points.  I also changed the copy line to 'SourceWB.Sheets("Sheet1").Cells.Copy` as suggested.  The code still stopped executing after opening the sheet and before copying the sheet to Thisworkbook.

on a side note, I also notice sometimes while stepping through the code and I do a file pick or folder pick, the code seems to terminate unless I have a break point set somewhere slightly after it.

答:
I've commented that not sure why it would stop... having a wild guess it could be because of the very large range you're copying (the whole sheet...).

You should either set the range of what you are copying (cell 1 to last row/column), or in this case, since you are not adding to pre-existent data, could be better off to just copy the sheet.

See if rewriting your code this way would help?

Sub ImportIndex()
'Copies Sheet1 from a user selected workbook
'into current work book

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim SourceWB As Workbook
    Dim FilenameWB As String

    'Open the source workbook through file picker
    On Error Resume Next
    FilenameWB = Application.GetOpenFilename()
    Set SourceWB = Workbooks.Open(Filename:=FilenameWB)
    On Error GoTo 0

    If Not SourceWB Is Nothing Then
        'ws.Name = "something else" 'rename this if you want to keep "Sheet1" name from the source workbook
        SourceWB.Sheets("Sheet1").Copy After:=ws
        ws.Delete

        'close the source workbook without saving changes
        SourceWB.Close savechanges:=False
    Else
        'Some error handling here... msgbox/debug.print etc
    End If

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With

End Sub
```

PS: Note that there are various ways to handle opening a workbook, but for simplicity reasons, this should work just fine.

Body:
I have some code that is copying a upwards of 1K files or so from a network drive to a SharePoint site.  When it has completed that task, It calls the following sub.  When I step through the code it seems to work fine, and it worked fine on some of the smaller lists I uploaded.  However when I just let it run it magically stops executing code and behaves as if everything has successfully been executed.  I know it hasn't because The workbook I picked to be open is still open and the workbook I am running the code from is blank.

The best I can surmise is the code stops executing right around:

SourceWB.Sheets("Sheet1").Activate

Because the destination sheet is still blank, I am pretty sure the cells.copy is not executing.  The only other thing I can think of is it somehow is grabbing the Destination worksheet as the source work sheet, so nothing actually gets copied and I wind up with a blank sheet.  I rule that out though as at the end of my main sub a message box is supposed to appear when things are complete and no message box appears.

Can anyone spot an issue or shed some light on what may be happening.  Frustrating that it works when stepping through. (as long as there is a break point afterwards)

Sub ImportIndex()

'Copies Sheet1 from a user selected workbook
'into current work book

    Dim DestinationWS As Worksheet
    Dim DestinationR As Range
    Dim SourceWB As Workbook
    Dim FilenameWB As String

    'clear sheet1 of any previous data/formats etc
    Clear_Worksheet ("Sheet1")

    'Set the location of where the sheet is to be copied to
    Set DestinationWS = ThisWorkbook.Sheets("Sheet1")
    Set DestinationR = DestinationWS.Range("A1")

    'Open the source workbook through file picker
    '****************************************************************
    'Error may occur if workbook is already open
    'Look into how to deal with this in the future
    '****************************************************************
    FilenameWB = Application.GetOpenFilename()

    Set SourceWB = Workbooks.Open(Filename:=FilenameWB)

    'Ensure "sheet1" is the active worksheet
    SourceWB.Sheets("Sheet1").Activate

    'Copies active wrokesheet to Destination
    Cells.Copy DestinationR

    'close the source workbook without saving changes
    SourceWB.Close savechanges:=False

End Sub

I did look at the following question, but it was related to Word.  According to one comment, the most recent build seems to have solved their issue.

Clearworksheet function as requested

Sub Clear_Worksheet(Sheetname As String)
'Deletes all cells in the provide worksheet name
'currently will cause an error if the sheet does not exist
    With ThisWorkbook.Sheets(Sheetname)
        .Cells.Delete Shift:=xlUp
        Range("A1").Activate 'probably do no need this activate
    End With

End Sub

I just re ran the code with the elimination of ACTIVATE and also having removed all stepping break points.  I also changed the copy line to 'SourceWB.Sheets("Sheet1").Cells.Copy` as suggested.  The code still stopped executing after opening the sheet and before copying the sheet to Thisworkbook.

on a side note, I also notice sometimes while stepping through the code and I do a file pick or folder pick, the code seems to terminate unless I have a break point set somewhere slightly after it.

Body:
I've commented that not sure why it would stop... having a wild guess it could be because of the very large range you're copying (the whole sheet...).

You should either set the range of what you are copying (cell 1 to last row/column), or in this case, since you are not adding to pre-existent data, could be better off to just copy the sheet.

See if rewriting your code this way would help?

Sub ImportIndex()
'Copies Sheet1 from a user selected workbook
'into current work book

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim SourceWB As Workbook
    Dim FilenameWB As String

    'Open the source workbook through file picker
    On Error Resume Next
    FilenameWB = Application.GetOpenFilename()
    Set SourceWB = Workbooks.Open(Filename:=FilenameWB)
    On Error GoTo 0

    If Not SourceWB Is Nothing Then
        'ws.Name = "something else" 'rename this if you want to keep "Sheet1" name from the source workbook
        SourceWB.Sheets("Sheet1").Copy After:=ws
        ws.Delete

        'close the source workbook without saving changes
        SourceWB.Close savechanges:=False
    Else
        'Some error handling here... msgbox/debug.print etc
    End If

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With

End Sub

PS: Note that there are various ways to handle opening a workbook, but for simplicity reasons, this should work just fine.


问:
Bredis 0.07 - Sending HMSET command with multiple entries
Trying to figure out the best way to send a HMSET command with a large (possibly 2000 pairs).

What im currently doing is creating a single string for each chunk of pairs, set up as 'key "value"'.  Is this the best way, or each as a param to the single_command_t, or as a iterator, with the command, key, and all value pairs after? @Ivan Baidakou

 modbusResponseCommands.emplace_back(bredis::single_command_t("MULTI"));
...
for (int j = 0; j < data._readCoilsResponses.size(); ++j) {
   int regId = data._readCoilsResponses[j].first;
   int regValue = data._readCoilsResponses[j].second;

   dataStr += std::to_string(regId) + '"';
   dataStr += std::to_string(regValue) + '"';
   dataStr += " ";
   if (j != 0 && j % 2000 == 0) {
        modbusResponseCommands.emplace_back(
            bredis::single_command_t(
                "HMSET",
                _key + ":rcres:unitId:" + std::to_string(unit.first),
                dataStr
            )
        );
        dataStr = "";
    }
}
modbusResponseCommands.emplace_back(
    bredis::single_command_t(
        "HMSET",
        _key + ":rcres:unitId:" + std::to_string(unit.first),
        dataStr
    )
);
...
modbusResponseCommands.emplace_back(bredis::single_command_t("EXEC"));
...
```

答:
You do not need MULTI, as HMSET already supports multiple key/values at once.

```<code>using pair_t = std::pair<std::string, std::string>;
using holder_t = std::vector<pair_t>;
holder_t holder;
std::vector<std::pair<int, int>> _readCoilsResponses;
r::single_command_t cmd{"HMSET"};
for (int j = 0; j < _readCoilsResponses.size(); ++j) {
   int regId = _readCoilsResponses[j].first;
   int regValue = _readCoilsResponses[j].second;
   holder.emplace_back(std::to_string(regId), std::to_string(regValue));
   auto& last_pair = holder.back();
   cmd.arguments.emplace_back(last_pair.first);
   cmd.arguments.emplace_back(last_pair.second);
}
</code>```

Basically MULTI should have the same effect as HMSET with all arguments, but it will put slightly more load on redis-server.

You can omit MULTI and just send a list of HMSET commands, which will be executed non-atomically, but that's way you'll give some breath for redis-server; but that should matter if you send megabytes of data.

Body:
You do not need MULTI, as HMSET already supports multiple key/values at once.

using pair_t = std::pair<std::string, std::string>;
using holder_t = std::vector<pair_t>;
holder_t holder;
std::vector<std::pair<int, int>> _readCoilsResponses;
r::single_command_t cmd{"HMSET"};
for (int j = 0; j < _readCoilsResponses.size(); ++j) {
   int regId = _readCoilsResponses[j].first;
   int regValue = _readCoilsResponses[j].second;
   holder.emplace_back(std::to_string(regId), std::to_string(regValue));
   auto& last_pair = holder.back();
   cmd.arguments.emplace_back(last_pair.first);
   cmd.arguments.emplace_back(last_pair.second);
}

Basically MULTI should have the same effect as HMSET with all arguments, but it will put slightly more load on redis-server.

You can omit MULTI and just send a list of HMSET commands, which will be executed non-atomically, but that's way you'll give some breath for redis-server; but that should matter if you send megabytes of data.


问:
Fastest way to fill a matrix with Random bytes
I want to fill an array with random values. The code I wrote is this one:

```<code>public class PersonalityMap
{
    const int size = 16;
    byte[,] fullMap = new byte[size, size];

    /// <summary>
    /// Generates a random map
    /// </summary>
    public PersonalityMap()
    {
        Random random = new Random();
        byte[] row = new byte[size];
        for (int i = 0; i < size; i++)
        {
            random.NextBytes(row);
            for (int j = 0; j < size; j++)
                fullMap[i, j] = row[j];
        }
    }
}
</code>```

But I feel there's a way to do it faster.

答:
Well, you could create one single-dimensional array, fill that, and then copy it with Buffer.BlockCopy:

```<code>Random random = new Random();
byte[] row = new byte[size * size];
random.NextBytes(row);
Buffer.BlockCopy(row, 0, fullMap, 0, size * size);
</code>```

However, before you try to optimize even further - just how quick do you need this to be? Have you benchmarked your application and determined that this is the bottleneck of your application?

Body:
I want to fill an array with random values. The code I wrote is this one:

public class PersonalityMap
{
    const int size = 16;
    byte[,] fullMap = new byte[size, size];

    ///
    /// Generates a random map
    ///
    public PersonalityMap()
    {
        Random random = new Random();
        byte[] row = new byte[size];
        for (int i = 0; i < size; i++)
        {
            random.NextBytes(row);
            for (int j = 0; j < size; j++)
                fullMap[i, j] = row[j];
        }
    }
}

But I feel there's a way to do it faster.

Body:
Well, you could create one single-dimensional array, fill that, and then copy it with Buffer.BlockCopy:

Random random = new Random();
byte[] row = new byte[size * size];
random.NextBytes(row);
Buffer.BlockCopy(row, 0, fullMap, 0, size * size);

However, before you try to optimize even further - just how quick do you need this to be? Have you benchmarked your application and determined that this is the bottleneck of your application?


问:
How to use window's keydown listener for keys Chrome uses as shortcuts?
Strange problem I've come across running this code in Google Chrome:

window.addEventListener('keydown', function (event) {
    console.log(event)
})
```

<p>While I see the log for some keys ("w", "a", "s", spacebar, "esc", for example) - other keys do not trigger this event: "d", "r", "l"</p>

<p>In fact, some of these letters (like "r") are a built-in shortcut in Chrome that cause some other event to fire, i.e a page refresh.</p>

<p>Interestingly, using <code>preventDefault</code> does not solve the problem:</p>

<pre class="lang-js prettyprint-override"><code>window.addEventListener('keydown', function (event) {
    event.preventDefault()
    console.log(event)
})
</code>```

Note that in Firefox the original code (without preventDefault) works fine - but not in Chrome.

Any idea how to solve this?

Update
Might be worth noting (though I'm not sure why this affects it) that when running this code from the file system, there is no problem on Chrome. But once this code is being served (i.e from localhost) then we run into the issue.

答:
```<code>document.addEventListener("keydown",function(e){
        console.log(e.keyCode);
    })
</code>```

you can use  e or event..
if you keydown any key , you will get the specific keycode for that key.
then you can put any conditions like,

```<code>if(e.keyCode == 32){
   video.pause();
}
</code>```

32 is the keycode of spacebar

Body:
Strange problem I've come across running this code in Google Chrome:

window.addEventListener('keydown', function (event) {
    console.log(event)
})

While I see the log for some keys ("w", "a", "s", spacebar, "esc", for example) - other keys do not trigger this event: "d", "r", "l"

In fact, some of these letters (like "r") are a built-in shortcut in Chrome that cause some other event to fire, i.e a page refresh.

Interestingly, using preventDefault does not solve the problem:

window.addEventListener('keydown', function (event) {
    event.preventDefault()
    console.log(event)
})

Note that in Firefox the original code (without preventDefault) works fine - but not in Chrome.

Any idea how to solve this?

Update
Might be worth noting (though I'm not sure why this affects it) that when running this code from the file system, there is no problem on Chrome. But once this code is being served (i.e from localhost) then we run into the issue.

Body:
document.addEventListener("keydown",function(e){
        console.log(e.keyCode);
    })

you can use  e or event..
if you keydown any key , you will get the specific keycode for that key.
then you can put any conditions like,

if(e.keyCode == 32){
   video.pause();
}

32 is the keycode of spacebar


问:
Multidimensional Array - Illegal String Offset
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

```<code>$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);
</code>```

I am trying to get the value of end in the date array. I have tried this:

```<code>foreach($fields as $field) {
  echo $field['end'];
}
</code>```

this outputs the data but also the illegal offset error.

I have tried this:

```<code>foreach($fields as $key => $value) {
  echo $value['end'];
}
</code>```

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

```<code>foreach($fields['date'] as $field) {
    $field['end'];
  }
</code>```

This is just an error.

And finally

```<code>foreach($fields as $field) {
  $field['date']['end'];
}
</code>```

just an error.

答:
You don't need to iterate, just access the fields directly:</p>

```<code>echo $fields['date']['end'];
</code>```

Body:
I have an array that for some reason keeps kicking back an error "Illegal String Offset" I have tried several ways to loop through it but none seem to work.

$fields = Array (
[cookies] => Array (
    [timeout] => 0
    [votes_per_cookie] => 1
    [enabled] => on
    )
[ip] => Array (
    [timeout] => 0
    [filter] =>
    )
[direct] =>  Array ( )
[membership] => Array (
    [type] => Array ( )
    [once] =>  Array ( )
    )
[captcha] =>  Array ( )
[quota] => Array (
    [votes] => 1000
    )
[date] => Array (
    [start] => 1553846400
    [end] => 1554767940
    [enabled] => on
    )
[selection] => Array (
    [minimum] => 1
    [maximum] => 1
    )
[unique_id] => 1547834405
[results] => Array (
    [require_vote] => Array (
        [enabled] => on
        )
    )
);

I am trying to get the value of end in the date array. I have tried this:

foreach($fields as $field) {
  echo $field['end'];
}

this outputs the data but also the illegal offset error.

I have tried this:

foreach($fields as $key => $value) {
  echo $value['end'];
}

This also outputs the same reponse.

if I echo key using the above loop, it returns the appropriate keys (cookies, ip, direct, membership, etc)

I have also tried:

foreach($fields['date'] as $field) {
    $field['end'];
  }

This is just an error.

And finally

foreach($fields as $field) {
  $field['date']['end'];
}

just an error.

Body:
You don't need to iterate, just access the fields directly:

echo $fields['date']['end'];


问:
Detect if string contains any spaces
How do I detect if a string has any whitespace characters?

The below only detects actual space characters. I need to check for any kind of whitespace.

```<code>if(str.indexOf(' ') >= 0){
    console.log("contains spaces");
}
</code>```

答:
```<code>var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);
</code>```

Title: Detect if string contains any spaces

Body:
How do I detect if a string has any whitespace characters?

The below only detects actual space characters. I need to check for any kind of whitespace.

if(str.indexOf(' ') >= 0){
    console.log("contains spaces");
}


问:
Get SQL Connection error while using Web Service with local SQL Server database
I'm setting up a web service, I wanted to use the local database so I created a local SQL Server database in this project. The web service runs just fine on localhost, but the problem when I invoke a method to Load data from the local database on this project, I'm getting an error:

System.Data.SqlClient.SqlException:

  An attempt to attach an auto-named database for file C:\Program Files (x86)\IIS Express\TourTravelDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

TourTravelDB.mdf is my local database

I've added a connection string in my web.config but it's still not working.

Here is my connection string.

```<code><connectionStrings>
    <add name="CS"
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\TourTravelDB.mdf;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
</connectionStrings>
</code>```

I've also tried to move my database to the IIS Express directory, it works but when run it from another computer, I have to move the database again.

Does anyone have an idea how to solve this?

答:
This may help you..

Add "User Instance=True;" in your connection string.

```<code>  <connectionStrings>
    <add name="aspnet_staterKits_Test_TimeTracker"
         connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf;"/>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer"
         connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf;"/>
  </connectionStrings>
</code>```

if doesn't work then try out the below links..

forums.asp.net

codeproject.com

Already existing thread in stack overflow

Body:
I'm setting up a web service, I wanted to use the local database so I created a local SQL Server database in this project. The web service runs just fine on localhost, but the problem when I invoke a method to Load data from the local database on this project, I'm getting an error:

System.Data.SqlClient.SqlException:

  An attempt to attach an auto-named database for file C:\Program Files (x86)\IIS Express\TourTravelDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

TourTravelDB.mdf is my local database

I've added a connection string in my web.config but it's still not working.

Here is my connection string.

<connectionStrings>
    <add name="CS"
         connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\TourTravelDB.mdf;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

I've also tried to move my database to the IIS Express directory, it works but when run it from another computer, I have to move the database again.

Does anyone have an idea how to solve this?

Body:
This may help you..

Add "User Instance=True;" in your connection string.

  <connectionStrings>
    <add name="aspnet_staterKits_Test_TimeTracker"
         connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf;"/>
    <remove name="LocalSqlServer"/>
    <add name="LocalSqlServer"
         connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|aspnetdb.mdf;"/>
  </connectionStrings>

if doesn't work then try out the below links..

forums.asp.net

codeproject.com

Already existing thread in stack overflow