问:
Laravel hasMany returns an empty array or error
I have seen a plethora of related questions but can't seem to figure out what is going on.
I am using Laravel 7.x, I have a Categories and a Products table.

Categories:

```<code>CREATE TABLE categories (
    id int(11) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT '',
    PRIMARY KEY (`id`)
)
</code>```

Products:

```<code>CREATE TABLE products (
    id int(11) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT '',
    category_id int(11) unsigned DEFAULT NULL,
    PRIMARY KEY (id),
    KEY category_id (category_id),
    CONSTRAINT products_ibfk_1 FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE
)
</code>```

In Laravel I can do Product::first()->catgory and then get the relevant category, with the hasMany relationship things seem to go pear shaped.

Defining Category as such:

```<code>public function products()
{
    return $this->hasMany(Product::class);
}
</code>```

Gives the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.category_id' in 'where clause' (SQL: select * from categories where categories.category_id = 1 and categories.category_id is not null)

Adding the foreign key and local key simply returns an empty array:

```<code>Category::find(1)->products;

...

public function products()
{
    return $this->hasMany(Product::class, 'id', 'category_id');
}

...

Illuminate\Database\Eloquent\Collection {#306 ▼
   #items: []
}
</code>```

What is it that I am missing here?

*EDIT:
Adding the FK as mentioned still results in the above mentioned SQL error

```<code>class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id');
    }
}
</code>```

alt tried...

```<code>class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }
}
</code>```

答:
your problem lies in this relation:

```<code>public function products()
{
    return $this->hasMany(Product::class, 'id', 'category_id');
}
</code>```

hasMany take as a second parameter the foreign key of the relation in the many table ...
the third parameter represent the local primary key ... in this case the Category local primary key .. by default should be 'id'
when you write category_id as the third parameter laravel look for the
column category_id in category and it did not find it ...

in Category model the relation should be:

```<code>public function products()
{
    return $this->hasMany(Product::class, 'category_id');
}
</code>```

the opposite relation in Product class should be:

```<code> public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }
</code>```

more details

https://laravel.com/docs/7.x/eloquent-relationships#one-to-many

Body:
I have seen a plethora of related questions but can't seem to figure out what is going on.
I am using Laravel 7.x, I have a Categories and a Products table.

Categories:

CREATE TABLE categories (
    id int(11) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT '',
    PRIMARY KEY (`id`)
)

Products:

CREATE TABLE products (
    id int(11) unsigned NOT NULL AUTO_INCREMENT,
    name varchar(255) DEFAULT '',
    category_id int(11) unsigned DEFAULT NULL,
    PRIMARY KEY (id),
    KEY category_id (category_id),
    CONSTRAINT products_ibfk_1 FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE ON UPDATE CASCADE
)

In Laravel I can do Product::first()->catgory and then get the relevant category, with the hasMany relationship things seem to go pear shaped.

Defining Category as such:

public function products()
{
    return $this->hasMany(Product::class);
}

Gives the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'categories.category_id' in 'where clause' (SQL: select * from categories where categories.category_id = 1 and categories.category_id is not null)

Adding the foreign key and local key simply returns an empty array:

Category::find(1)->products;

...

public function products()
{
    return $this->hasMany(Product::class, 'id', 'category_id');
}

...

Illuminate\Database\Eloquent\Collection {#306 ▼
   #items: []
}

What is it that I am missing here?

*EDIT:
Adding the FK as mentioned still results in the above mentioned SQL error

class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id');
    }
}

alt tried...

class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }
}

Body:
your problem lies in this relation:

public function products()
{
    return $this->hasMany(Product::class, 'id', 'category_id');
}

hasMany take as a second parameter the foreign key of the relation in the many table ...
the third parameter represent the local primary key ... in this case the Category local primary key .. by default should be 'id'
when you write category_id as the third parameter laravel look for the
column category_id in category and it did not find it ...

in Category model the relation should be:

public function products()
{
    return $this->hasMany(Product::class, 'category_id');
}

the opposite relation in Product class should be:

 public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

more details

https://laravel.com/docs/7.x/eloquent-relationships#one-to-many


来源: stackexchange

问:
Save Matplotlib figure as TIFF
Does anyone know how to save a Matplotlib figure as *.tiff? It seems that this format is not supported in Python, while the journals are quite often ask for that format.

I am adding some minimal code:

```<code># -*- coding: utf-8 -*-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# fig setup
fig = plt.figure(figsize=(5,5), dpi=300)
ax = fig.gca(projection='3d')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.zaxis.set_ticklabels([])

# draw a surface
xx, yy = np.meshgrid(range(-1,2), range(-1,2))
zz = np.zeros(shape=(3,3))
ax.plot_surface(xx, yy, zz, color='#c8c8c8', alpha=0.3)
ax.plot_surface(xx, zz, yy, color='#b6b6ff', alpha=0.2)

# draw a point
ax.scatter([0],[0],[0], color='b', s=200)
</code>```

This works:

```<code>fig.savefig('3dPlot.pdf')
</code>```

But this does not:

```<code>fig.savefig('3dPlot.tif')
</code>```

答:
All you have to do is install Pillow .
Then you can use just this:

```<code>fig.savefig('3dPlot.tiff')
</code>```

ContentLicense: CC BY-SA 4.0

Title: Save Matplotlib figure as TIFF

Body:
Does anyone know how to save a Matplotlib figure as *.tiff? It seems that this format is not supported in Python, while the journals are quite often ask for that format.

I am adding some minimal code:

# -*- coding: utf-8 -*-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

# fig setup
fig = plt.figure(figsize=(5,5), dpi=300)
ax = fig.gca(projection='3d')
ax.set_xlim([-1,1])
ax.set_ylim([-1,1])
ax.set_zlim([-1,1])
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
ax.axes.zaxis.set_ticklabels([])

# draw a surface
xx, yy = np.meshgrid(range(-1,2), range(-1,2))
zz = np.zeros(shape=(3,3))
ax.plot_surface(xx, yy, zz, color='#c8c8c8', alpha=0.3)
ax.plot_surface(xx, zz, yy, color='#b6b6ff', alpha=0.2)

# draw a point
ax.scatter([0],[0],[0], color='b', s=200)

This works:

fig.savefig('3dPlot.pdf')

But this does not:

fig.savefig('3dPlot.tif')

Body:
All you have to do is install Pillow .
Then you can use just this:

fig.savefig('3dPlot.tiff')


问:
Codeigniter 4 cookies issue not able to set
This is my controller code.  I am not able to set and get the cookies in Codeigniter 4.</p>

```<code>helper('cookie');
$this->response->set_cookie('forgetpwd',$token, time() + (3600),"/",site_url());
print_r($this->request->get_cookie('forgetpwd'));
die();
</code>```

答:
Do not use die() because then the cookie will not be set. Let the method return instead so CI can output cookies and headers.

You do not need the helper, don't load it.

site_url() does not produce the string you should be using. It includes the protocol, i.e. https://example.com when all you should use is 'example.com'.

You have the domain and path arguments reversed and as others have said the call is to setCookie() as in

```<code>$this->response->setCookie('forgetpwd', $token, 3600, example.com);
</code>```

The expire argument can be the life (in seconds) you want. The setCookie() method will add time() to it for you.

I don't supply a path argument because you need the default value of '/'.

Body:
This is my controller code.  I am not able to set and get the cookies in Codeigniter 4.

helper('cookie');
$this->response->set_cookie('forgetpwd',$token, time() + (3600),"/",site_url());
print_r($this->request->get_cookie('forgetpwd'));
die();

Body:
Do not use die() because then the cookie will not be set. Let the method return instead so CI can output cookies and headers.

You do not need the helper, don't load it.

site_url() does not produce the string you should be using. It includes the protocol, i.e. https://example.com when all you should use is 'example.com'.

You have the domain and path arguments reversed and as others have said the call is to setCookie() as in

$this->response->setCookie('forgetpwd', $token, 3600, example.com);

The expire argument can be the life (in seconds) you want. The setCookie() method will add time() to it for you.

I don't supply a path argument because you need the default value of '/'.


问:
Can't create handler inside thread that has not called Looper.prepare()
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

```<code>public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });
</code>```

StartPayment Method:

```<code>    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}
</code>```

答: you cant change any UI in thread you can use runOnUIThread or AsyncTask for more detail about this click here

ContentLicense: CC BY-SA 3.0

Body:
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });

StartPayment Method:

    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}


问:
Why won't react modal input value populate when state is updated?
I have a modal that is triggered on a button click that needs to be populated with an input value that can be edited by the user. When the button is clicked, modal state is updated, but the input either:

a. doesn't reflect the updated state as its value (this happens when I use 'defaultValue'
--or--

b. won't let the user edit the value in the input (this happens when I use 'value'.

How can I populate the input with the current state and also be able to edit it?  Shouldn't changing the state that the input value is set to trigger a re-render of the modal?

```<code>function EditModal(props) {
    const [value, setValue] = useState(props.modalVal);
    const[hidden, setHidden] = useState(true)
    const[initialRender, setInitialRender] = useState(true)
    useEffect(()=>{
        setInitialRender(false)
    },[])
    useEffect(() => {
        setValue(props.modalVal)// <-- why doesn't this update input value?
    }, [props.modalVal]);
    useEffect(()=>{
        if(!initialRender){
            setHidden(false)
        }
    },[value])
    return (
        <Modal hidden={hidden} >
            <Text>Edit Item</Text>
            <form action="submit" onSubmit={props.submit}>
                <Input onChange={props.handleChange} defaultValue={value} />
                <Button>OK</Button>
            </form>
        </Modal>
    )
}
</code>```

答:
If you set the value using value then when the user edits it, you need to ensure that the onChange function you specify updates the value so that on the next render, the value is updated.

It looks like you have a value (props.modalVal) that you should use as value (note that you do not need the useEffect or the useState for this, as changing props causes a re-render). What you therefore need to make sure is that props.handleChange changes modalValue

Something like this:

```<code><Input onChange={props.handleChange} value={props.modalValue} />
</code>```

and in the parent component:

```<code>const ParentComponent = ()=> {
  const [modalValue, setModalValue] = useState('initialValue');

  const handleChange = (event) => {
    setModalValue(event.currentTarget.value);
  };

  return (
    <EditModal handleChange={handleChange} modalValue={modalValue} />
  )
}
</code>```

Body:
I have a modal that is triggered on a button click that needs to be populated with an input value that can be edited by the user. When the button is clicked, modal state is updated, but the input either:

a. doesn't reflect the updated state as its value (this happens when I use 'defaultValue'
--or--

b. won't let the user edit the value in the input (this happens when I use 'value'.

How can I populate the input with the current state and also be able to edit it?  Shouldn't changing the state that the input value is set to trigger a re-render of the modal?

function EditModal(props) {
    const [value, setValue] = useState(props.modalVal);
    const[hidden, setHidden] = useState(true)
    const[initialRender, setInitialRender] = useState(true)
    useEffect(()=>{
        setInitialRender(false)
    },[])
    useEffect(() => {
        setValue(props.modalVal)// <-- why doesn't this update input value?
    }, [props.modalVal]);
    useEffect(()=>{
        if(!initialRender){
            setHidden(false)
        }
    },[value])
    return (
        <Modal hidden={hidden} >
            <Text>Edit Item</Text>
            <form action="submit" onSubmit={props.submit}>
                <Input onChange={props.handleChange} defaultValue={value} />
                <Button>OK</Button>
            </form>
        </Modal>
    )
}

Body:
If you set the value using value then when the user edits it, you need to ensure that the onChange function you specify updates the value so that on the next render, the value is updated.

It looks like you have a value (props.modalVal) that you should use as value (note that you do not need the useEffect or the useState for this, as changing props causes a re-render). What you therefore need to make sure is that props.handleChange changes modalValue

Something like this:

<Input onChange={props.handleChange} value={props.modalValue} />

and in the parent component:

const ParentComponent = ()=> {
  const [modalValue, setModalValue] = useState('initialValue');

  const handleChange = (event) => {
    setModalValue(event.currentTarget.value);
  };

  return (
    <EditModal handleChange={handleChange} modalValue={modalValue} />
  )
}


问:
Write and Read nested Map to Firebase Document from Flutter
I am struggling to write (and also haven't yet figured out how to read) nested maps in firebase from my flutter app. I'm writing an expense tracker where the list of categories is stored within each logbook. I can map, save, and retrieve the primitive fields to and from firebase, where I get lost is trying to write the map of the categories and subcategories to firebase and then how to read them.

Solving for both categories and subcategories is essentially the same so I'll just present one of them. Also, I currently have the category Id as both the key and part of the category class itself, I'll be deleting the Id from the class itself later, as I believe its bad practice, it's just helping me at the moment elsewhere.

I've also been following the BLOC method, so I also have models that convert to entities for dealing with firebase.

This is a category (I've removed irrelevant info such as props and to string):

```<code>```
    class MyCategory extends Equatable {
  final String id;
  final String name;
  final IconData iconData;

  MyCategory({@required this.id, @required this.name, this.iconData});
  MyCategoryEntity toEntity() {
    return MyCategoryEntity(
      id: id,
      name: name,
      iconCodePoint: iconData.codePoint.toString(),
      iconFontFamily: iconData.fontFamily,
    );
  }

  static MyCategory fromEntity(MyCategoryEntity entity) {
    return MyCategory(
      id: entity.id,
      name: entity.name,
      iconData: IconData(int.parse(entity.iconCodePoint),
          fontFamily: entity.iconFontFamily),
    );
  }
}
```
</code>```

The model entity for the category has JsonSerialization and also uses the Icon codepoint/fontFamily as it seems to be more friendly to pass back and forth from firebase than IconData directly.

```<code>```
    @JsonSerializable()
class MyCategoryEntity extends Equatable {
  final String id;
  final String name;
  final String iconCodePoint;
  final String iconFontFamily;

  const MyCategoryEntity(
      {this.id, this.name, this.iconCodePoint, this.iconFontFamily});

  factory MyCategoryEntity.fromJson(Map<String, dynamic> json) =>
      _$MyCategoryEntityFromJson(json);

  Map<String, dynamic> toJson() => _$MyCategoryEntityToJson(this);
```
</code>```

I don't think you need to see the Log model as its more the LogEntity that speaks directly to firebase. This is where I'm completely stuck. I've seen a few examples of how to pass a list of objects, but I can't seem to figure out how to pass a map of objects. I'm also not sure how I'd read it back into the LogEntity from firestore (as can be seen in my two TODOs down below).

```<code>```
    class LogEntity extends Equatable {
  final String uid;
  final String id;
  final String logName;
  final String currency;
  final bool active;
  //String is the category id
  final Map<String, MyCategory> categories;
  final Map<String, MySubcategory> subcategories;

  const LogEntity({this.uid, this.id, this.logName, this.currency, this.categories, this.subcategories, this.active});

  static LogEntity fromSnapshot(DocumentSnapshot snap) {
    return LogEntity(
      uid: snap.data[UID],
      id: snap.documentID,
      logName: snap.data[LOG_NAME],
      currency: snap.data[CURRENCY_NAME],
      //TODO de-serialize categories and subcategories
      active: snap.data[ACTIVE],

    );
  }

  Map<String, Object> toDocument() {
    return {
      UID: uid,
      LOG_NAME: logName,
      CURRENCY_NAME: currency,
    //TODO serialize categories and subcategories, this does doesn't work
      CATEGORIES: categories.map((key, value) => categories[key].toEntity().toJson()).toString(),
      ACTIVE: active,
    };
  }
}
```
</code>```

I'm really hoping for some help on this as the only examples I've been able to understand are lists, not maps. Also I want to use a similar method in a few places in this app, so figuring this out is critical.

Git: https://github.com/cver22/expenses2

答:
Exporting Data

Firebase needs a Map<String, dynamic>, where dynamic is one of its supported types (like a string, number, map, array, etc.). Thus, if you have a custom object, like MyCategory in your example, you need to .map() it to one of the supported types (yet another Map<String, dynamic> in this case). Thus, you can do a <map that you need to convert>.map((key, value) => MapEntry(key, <method to convert each value to a Map<String, dynamic>>)). Your example is almost correct, but it has a toString() which will make Firebase store it as a string, and not as a map (which is not the desired behavior). As discussed in the comments, removing the toString() should resolve that issue.

Retrieving Data

Similar to the exporting data, Firebase will provide you with a Map<String, dynamic> where dynamic is one of Firebase's supported types, which for category and subcategory are yet again Map<String, dynamic>s. Consequently, you need to convert the snap.data[KEY], which is a dynamic, to a Map<String, YourObject> of the corresponding type in your code. The steps to parse this are like so:

Take data from snapshot as dynamic

Cast this dynamic data to a Map

.map() this cast-ed data to your own types

Thus, something like the following should work:

```<code>    return LogEntity(
      uid: snap.data[UID],
      id: snap.documentID,
      logName: snap.data[LOG_NAME],
      currency: snap.data[CURRENCY_NAME],
      categories: (snap.data[CATEGORIES] as Map<String, dynamic>).map((key, value) => MapEntry(key, MyCategory.fromEntity(MyCategoryEntity.fromJson(value)))),
      // todo subcategories should follow the same form as categories; I will leave that one up to you
      active: snap.data[ACTIVE],

    );
</code>```

Retrieving Nested Primitive Types

I'd like to make a note here as well in case anyone finds this question searching for how to parse a nested map/list that uses primitive types from Firebase (like a Map<String, String>, Map<String, int>, or List<String> to name a few). In that case, check out the Map<String, PrimitiveType>.from() and List<PrimitiveType>.from() constructors; they will probably do exactly what you want, assuming PrimitiveType is one of Firebase's supported types. If not, see the above answer.

One more small thing: I did not look over all of your code, but one thing I couldn't help but notice was your static LogEntity fromSnapshot(). In Dart, you typically use factory or named constructors depending on the use case, but by no means am I an expert.

Body:
I am struggling to write (and also haven't yet figured out how to read) nested maps in firebase from my flutter app. I'm writing an expense tracker where the list of categories is stored within each logbook. I can map, save, and retrieve the primitive fields to and from firebase, where I get lost is trying to write the map of the categories and subcategories to firebase and then how to read them.

Solving for both categories and subcategories is essentially the same so I'll just present one of them. Also, I currently have the category Id as both the key and part of the category class itself, I'll be deleting the Id from the class itself later, as I believe its bad practice, it's just helping me at the moment elsewhere.

I've also been following the BLOC method, so I also have models that convert to entities for dealing with firebase.

This is a category (I've removed irrelevant info such as props and to string):

    class MyCategory extends Equatable {
  final String id;
  final String name;
  final IconData iconData;

  MyCategory({@required this.id, @required this.name, this.iconData});
  MyCategoryEntity toEntity() {
    return MyCategoryEntity(
      id: id,
      name: name,
      iconCodePoint: iconData.codePoint.toString(),
      iconFontFamily: iconData.fontFamily,
    );
  }

  static MyCategory fromEntity(MyCategoryEntity entity) {
    return MyCategory(
      id: entity.id,
      name: entity.name,
      iconData: IconData(int.parse(entity.iconCodePoint),
          fontFamily: entity.iconFontFamily),
    );
  }
}

The model entity for the category has JsonSerialization and also uses the Icon codepoint/fontFamily as it seems to be more friendly to pass back and forth from firebase than IconData directly.

    @JsonSerializable()
class MyCategoryEntity extends Equatable {
  final String id;
  final String name;
  final String iconCodePoint;
  final String iconFontFamily;

  const MyCategoryEntity(
      {this.id, this.name, this.iconCodePoint, this.iconFontFamily});

  factory MyCategoryEntity.fromJson(Map<String, dynamic> json) =>
      _$MyCategoryEntityFromJson(json);

  Map<String, dynamic> toJson() => _$MyCategoryEntityToJson(this);

I don't think you need to see the Log model as its more the LogEntity that speaks directly to firebase. This is where I'm completely stuck. I've seen a few examples of how to pass a list of objects, but I can't seem to figure out how to pass a map of objects. I'm also not sure how I'd read it back into the LogEntity from firestore (as can be seen in my two TODOs down below).

    class LogEntity extends Equatable {
  final String uid;
  final String id;
  final String logName;
  final String currency;
  final bool active;
  //String is the category id
  final Map<String, MyCategory> categories;
  final Map<String, MySubcategory> subcategories;

  const LogEntity({this.uid, this.id, this.logName, this.currency, this.categories, this.subcategories, this.active});

  static LogEntity fromSnapshot(DocumentSnapshot snap) {
    return LogEntity(
      uid: snap.data[UID],
      id: snap.documentID,
      logName: snap.data[LOG_NAME],
      currency: snap.data[CURRENCY_NAME],
      //TODO de-serialize categories and subcategories
      active: snap.data[ACTIVE],

    );
  }

  Map<String, Object> toDocument() {
    return {
      UID: uid,
      LOG_NAME: logName,
      CURRENCY_NAME: currency,
    //TODO serialize categories and subcategories, this does doesn't work
      CATEGORIES: categories.map((key, value) => categories[key].toEntity().toJson()).toString(),
      ACTIVE: active,
    };
  }
}

I'm really hoping for some help on this as the only examples I've been able to understand are lists, not maps. Also I want to use a similar method in a few places in this app, so figuring this out is critical.

Git: https://github.com/cver22/expenses2

Body:
Exporting Data

Firebase needs a Map<String, dynamic>, where dynamic is one of its supported types (like a string, number, map, array, etc.). Thus, if you have a custom object, like MyCategory in your example, you need to .map() it to one of the supported types (yet another Map<String, dynamic> in this case). Thus, you can do a <map that you need to convert>.map((key, value) => MapEntry(key, <method to convert each value to a Map<String, dynamic>>)). Your example is almost correct, but it has a toString() which will make Firebase store it as a string, and not as a map (which is not the desired behavior). As discussed in the comments, removing the toString() should resolve that issue.

Retrieving Data

Similar to the exporting data, Firebase will provide you with a Map<String, dynamic> where dynamic is one of Firebase's supported types, which for category and subcategory are yet again Map<String, dynamic>s. Consequently, you need to convert the snap.data[KEY], which is a dynamic, to a Map<String, YourObject> of the corresponding type in your code. The steps to parse this are like so:

Take data from snapshot as dynamic

Cast this dynamic data to a Map

.map() this cast-ed data to your own types

Thus, something like the following should work:

    return LogEntity(
      uid: snap.data[UID],
      id: snap.documentID,
      logName: snap.data[LOG_NAME],
      currency: snap.data[CURRENCY_NAME],
      categories: (snap.data[CATEGORIES] as Map<String, dynamic>).map((key, value) => MapEntry(key, MyCategory.fromEntity(MyCategoryEntity.fromJson(value)))),
      // todo subcategories should follow the same form as categories; I will leave that one up to you
      active: snap.data[ACTIVE],

    );

Retrieving Nested Primitive Types

I'd like to make a note here as well in case anyone finds this question searching for how to parse a nested map/list that uses primitive types from Firebase (like a Map<String, String>, Map<String, int>, or List<String> to name a few). In that case, check out the Map<String, PrimitiveType>.from() and List<PrimitiveType>.from() constructors; they will probably do exactly what you want, assuming PrimitiveType is one of Firebase's supported types. If not, see the above answer.

One more small thing: I did not look over all of your code, but one thing I couldn't help but notice was your static LogEntity fromSnapshot(). In Dart, you typically use factory or named constructors depending on the use case, but by no means am I an expert.


问:
Should I await a Firestore set call in Firebase cloud functions
Let's say I have a cloud function like this

```<code>export const setData = functions.https.onCall(async (data, context) => {
    await admin.firestore().doc("myPath").set({data: "myData"})
    return {success: true}
})
</code>```

If I don't care about the firestore set call is successful or not,
can I remove the await? So the function returns earlier and reduces CPU usage time.

```<code>export const setData = functions.https.onCall(async (data, context) => {
    admin.firestore().doc("myPath").set({data: "myData"})
    return {success: true}
})
</code>```

答:
This is more like JS question than Firebase itself.

If you really don't care, no problem but you'll never know if anything returned or not, even if the function could be called normally as the return might just finish everything before the Firebase call is complete.

"returns earlier and reduces CPU usage time."

Using less CPU might be just a signal that your function is not working properly.

Also, Firebase is really fast and scalable, I would always recommend then/catch's to keep execution and catch errors, even just for logging purposes. Something like:

admin.firestore().doc("myPath").set({data: "myData"}).then(response => {
    return whateverYouWant(response)
}).catch(err => {
    return handleWhateverError(err)
})
```

Also, there's no need to keep async if you have no await in the function anymore.

Body:
Let's say I have a cloud function like this

export const setData = functions.https.onCall(async (data, context) => {
    await admin.firestore().doc("myPath").set({data: "myData"})
    return {success: true}
})

If I don't care about the firestore set call is successful or not,
can I remove the await? So the function returns earlier and reduces CPU usage time.

export const setData = functions.https.onCall(async (data, context) => {
    admin.firestore().doc("myPath").set({data: "myData"})
    return {success: true}
})

Body:
This is more like JS question than Firebase itself.

If you really don't care, no problem but you'll never know if anything returned or not, even if the function could be called normally as the return might just finish everything before the Firebase call is complete.

"returns earlier and reduces CPU usage time."

Using less CPU might be just a signal that your function is not working properly.

Also, Firebase is really fast and scalable, I would always recommend then/catch's to keep execution and catch errors, even just for logging purposes. Something like:

admin.firestore().doc("myPath").set({data: "myData"}).then(response => {
    return whateverYouWant(response)
}).catch(err => {
    return handleWhateverError(err)
})

Also, there's no need to keep async if you have no await in the function anymore.


问:
Android Dalvik Emulator cannot connect to GPS
I am beginner in Android and I have a problem with GPS in the Dalvik Emulator.
I added hardware gps support on AVD and after booting I checked Use GPS Satellites in

```<code>Settings -> Location & Security -> Use GPS Satellites.
</code>```

I enable Use GPS Satellites but there is no indication that GPS is turned on. There is no  satellite indicator at the top of the screen.

I tried to send coordinates to the emulator via DDMS (on a simple application) and it still doesn't work.

答: Have you requested location/location updates in your app? If you haven't, the GPS won't get enabled until some application requests location from it, even though it's turned on.</p>

Body:
I am beginner in Android and I have a problem with GPS in the Dalvik Emulator.
I added hardware gps support on AVD and after booting I checked Use GPS Satellites in

Settings -> Location & Security -> Use GPS Satellites.

I enable Use GPS Satellites but there is no indication that GPS is turned on. There is no  satellite indicator at the top of the screen.

I tried to send coordinates to the emulator via DDMS (on a simple application) and it still doesn't work.


问:
gem native extension error while installing cocoapods
Am trying to reinstall cocoapods in my MacBook air after changing my SSD, now am getting this bellow error.

sudo gem install cocoapods

Building native extensions.  This could take a while... ERROR:  Error
  installing cocoapods:     ERROR: Failed to build gem native extension.

```<code>current directory: /Library/Ruby/Gems/2.3.0/gems/ffi-1.12.2/ext/ffi_c
</code>```

/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -r
  ./siteconf20200308-27204-6l0a5q.rb extconf.rb mkmf.rb can't find
  header files for ruby at
  /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in
  /Library/Ruby/Gems/2.3.0/gems/ffi-1.12.2 for inspection. Results
  logged to
  /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-18/2.3.0/ffi-1.12.2/gem_make.out

答:
For me it worked by installing a previous version of cocoapods

```<code>sudo gem install cocoapods -v 1.8.4
</code>```

Hope it helps

Body:
Am trying to reinstall cocoapods in my MacBook air after changing my SSD, now am getting this bellow error.

sudo gem install cocoapods

Building native extensions.  This could take a while... ERROR:  Error
  installing cocoapods:     ERROR: Failed to build gem native extension.

current directory: /Library/Ruby/Gems/2.3.0/gems/ffi-1.12.2/ext/ffi_c

/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby -r
  ./siteconf20200308-27204-6l0a5q.rb extconf.rb mkmf.rb can't find
  header files for ruby at
  /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in
  /Library/Ruby/Gems/2.3.0/gems/ffi-1.12.2 for inspection. Results
  logged to
  /Library/Ruby/Gems/2.3.0/extensions/universal-darwin-18/2.3.0/ffi-1.12.2/gem_make.out

Body:
For me it worked by installing a previous version of cocoapods

sudo gem install cocoapods -v 1.8.4

Hope it helps


问:
How can I show sub-categories only when the parent category is clicked?
I want to achieve that whenever a user click on any parent category it should show sub-categories of that one below automatically.

I have added ul.children { display: none; } as well in stylesheet. So, now it's showing only parent categories.

jQuery('li.cat-item').on('click', function() {
  $('ul.children').hide();
  $(this).find('ul.children').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul.children {
  display: none;
}</code>```

  Parent Category

      Sub Category

```

But this one is not working.

答:
jQuery('li.cat-item').on('click',function(event){
    event.preventDefault();
    $('ul.children').hide();
    $(this).find('ul.children').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul.children{ display: none; }</code>```

        Parent Category

                Sub Category

```

You haven't nested the menu and submenu items properly. I added preventDefault to your jQuery snippet because, according to the Mozilla Developer Docs:

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Body:
I want to achieve that whenever a user click on any parent category it should show sub-categories of that one below automatically.

I have added ul.children { display: none; } as well in stylesheet. So, now it's showing only parent categories.

jQuery('li.cat-item').on('click', function() {
  $('ul.children').hide();
  $(this).find('ul.children').show();
});

ul.children {
  display: none;
}

  Parent Category

      Sub Category

But this one is not working.

Body:
jQuery('li.cat-item').on('click',function(event){
    event.preventDefault();
    $('ul.children').hide();
    $(this).find('ul.children').show();
});

ul.children{ display: none; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li class="cat-item cat-item-25">
        <a href="link">Parent Category</a>
        <ul class="children">
            <li class="cat-item cat-item-13">
                <a href="link">Sub Category</a>
            </li>
        </ul>
    </li>
</ul>

You haven't nested the menu and submenu items properly. I added preventDefault to your jQuery snippet because, according to the Mozilla Developer Docs:

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.


问:
Does the vmware vCenter api support summary metrics across multiple vms?
Does the vCenter 6.7 API have a summary metrics endpoint across vms in a cluster?

or

Do i have to make an API call for each VM and aggregate all the data later.

Thanks

答:
Performance Manager service is going to be your best resource for this question: https://code.vmware.com/apis/704/vsphere/vim.PerformanceManager.html </p>

<p>Cliff's notes: The cluster level will have limited amount of metrics that can be sourced and summarized as VM stats, so it will really depend on what metrics you're looking for. </p>

Body:
Performance Manager service is going to be your best resource for this question: https://code.vmware.com/apis/704/vsphere/vim.PerformanceManager.html

Cliff's notes: The cluster level will have limited amount of metrics that can be sourced and summarized as VM stats, so it will really depend on what metrics you're looking for.


问:
Can't display Data in ComboBox Control of DropDownStyle (DropDownList)
I have the following requirement,

I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database    Table, and it's working fine.

```<code>(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))
</code>```

But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.

```<code>(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))
</code>```

When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.

Am I missing something here or is it like that? Any advice will be highly appreciated.

Im filling it in runtime using a procedure.

```<code>Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    cmbDisProfile.DataSource = tempTb
    cmbDisProfile.DisplayMember = "discount_profile"
End Sub
</code>```

Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.

My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.

```<code>Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)

        Return fetchedDataTable

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)

    Dim SqlCmd As New SqlCommand(sqlString, conn)
    Dim dataAdapter As New SqlDataAdapter(SqlCmd)
    Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
    dataAdapter.Update(tbToUpdate)

End Sub

Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
    Try
        Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"

        'Dim searchString As String = txtCategoryCode.Text
        '        searchOwnerCmd.Parameters.Clear()
        '        searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")

        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(searchSql)

        If tempTb.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)

        Return fetchedSearchTB

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
</code>```

答:
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.

proposed,

ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"

does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),

```<code>Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    Dim i As Integer = 0
    For i = 0 To tempTb.Rows.Count - 1
        cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
    Next
End Sub
</code>```

After adding we can use the following code to display the data on combobox (DropDownList).

```<code>Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
    Try
        Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(sqlString)

        If Len(txtItCode.Text) < 4 Then
            cmdAdd.Enabled = False
            cmdDelete.Enabled = False
            cmdSave.Enabled = False
        Else
            If tempTb.Rows.Count > 0 Then

                With tempTb
                    txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
                    cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
                    cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
                    cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
                    cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
                End With
                cmdAdd.Enabled = False
                cmdDelete.Enabled = True
                cmdSave.Enabled = True
            Else
                cmdAdd.Enabled = True
                cmdDelete.Enabled = False
                cmdSave.Enabled = False
                txtItName.Text = ""
                Call fillItCategories()
                Call fillProProfile()
                Call filldisProfiles()
                Call fillFinCat()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
</code>```

Body:
I have the following requirement,

I have a ComboBox Control (DropDownList Style) which user has to select a given value, but can not edit. Then I save it to a Database    Table, and it's working fine.

(dataRow("it_discount_profile") = Trim(cmbDisProfile.Text))

But when I try to show the same Data in the same ComboBox by retrieving it from the Database, it won't show.

(cmbDisProfile.Text = Trim(tempTb.Rows(0).Item("it_discount_profile")))

When I change the ComboBox to "DropDown Style", it works. But then the User can edit it.

Am I missing something here or is it like that? Any advice will be highly appreciated.

Im filling it in runtime using a procedure.

Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    cmbDisProfile.DataSource = tempTb
    cmbDisProfile.DisplayMember = "discount_profile"
End Sub

Ok. Actually, Im trying to migrate one of my old project from VB to VB.Net. VB.Net is little new to me. Im using a self built classto reduce codes in other places. Im attaching the class below.

My actual requirement is to populate the combo box from a table. I like to do it in run time. I don't want users to edit it. If they want to add a new value, they have separate place (Form) for that. I think im doing it in a wrong way. If possible please give a sample code since I'm not familiar with the proposed method.

Public Function myFunctionFetchTbData(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedDataTable As DataTable = fetchedDataSet.Tables(0)

        Return fetchedDataTable

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

' this sub will update a table
Public Sub MyMethodUpdateTable(ByVal sqlString As String, ByVal tbToUpdate As DataTable)

    Dim SqlCmd As New SqlCommand(sqlString, conn)
    Dim dataAdapter As New SqlDataAdapter(SqlCmd)
    Dim objCommandBuilder As New SqlClient.SqlCommandBuilder(dataAdapter)
    dataAdapter.Update(tbToUpdate)

End Sub

Public Function MyMethodfindRecord(ByVal strSearckKey As String, ByVal tableName As String, ByVal strColumnName As String) As Boolean
    Try
        Dim searchSql As String = "SELECT * FROM " & tableName & " WHERE " & strColumnName & "='" & strSearckKey & "'"

        'Dim searchString As String = txtCategoryCode.Text
        '        searchOwnerCmd.Parameters.Clear()
        '        searchOwnerCmd.Parameters.AddWithValue("a", "%" & search & "%")

        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(searchSql)

        If tempTb.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function
Public Function myFunctionFetchSearchTB(ByVal inputSqlString As String) As DataTable
    Try
        Dim SqlCmd As New SqlCommand(inputSqlString, conn)
        Dim dataAdapter As New SqlDataAdapter(SqlCmd)

        Dim fetchedDataSet As New DataSet
        fetchedDataSet.Clear()
        dataAdapter.Fill(fetchedDataSet)

        Dim fetchedSearchTB As DataTable = fetchedDataSet.Tables(0)

        Return fetchedSearchTB

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Function

Body:
Thank you guys for all the advice's. The only way it can be done is the way u said. I thought of putting the working code and some points for the benefit of all.

proposed,

ComboBox1.SelectedIndex = comboBox1.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))"

does not work when u bind the datatable to the combobox. The values should be added to the combo box in run time if the above "SelectedIndex" method to work. The code to add items to the combobox is as follows(myClassTableActivities is a class defined by myself and its shown above),

Private Sub filldisProfiles()
    Dim sqlString As String = "SELECT discount_profile FROM tb_discount_profiles"
    Dim tempTb As DataTable
    Dim myTbClass As myClassTableActivities = New myClassTableActivities()
    tempTb = myTbClass.myFunctionFetchTbData(sqlString)

    Dim i As Integer = 0
    For i = 0 To tempTb.Rows.Count - 1
        cmbDisProfile.Items.Add(Trim(tempTb.Rows(i).Item("discount_profile")))
    Next
End Sub

After adding we can use the following code to display the data on combobox (DropDownList).

Private Sub txtItCode_TextChanged(sender As Object, e As EventArgs) Handles txtItCode.TextChanged
    Try
        Dim sqlString As String = "SELECT * FROM tb_items where it_code='" & Trim(txtItCode.Text) & "'"
        Dim tempTb As DataTable
        Dim myTbClass As myClassTableActivities = New myClassTableActivities()
        tempTb = myTbClass.myFunctionFetchTbData(sqlString)

        If Len(txtItCode.Text) < 4 Then
            cmdAdd.Enabled = False
            cmdDelete.Enabled = False
            cmdSave.Enabled = False
        Else
            If tempTb.Rows.Count > 0 Then

                With tempTb
                    txtItName.Text = Trim(tempTb.Rows(0).Item("it_name"))
                    cmbDisProfile.SelectedIndex = cmbDisProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_discount_profile")))
                    cmbProfitProfile.SelectedIndex = cmbProfitProfile.FindStringExact(Trim(tempTb.Rows(0).Item("it_profit_profile")))
                    cmbItCategory.SelectedIndex = cmbItCategory.FindStringExact(Trim(tempTb.Rows(0).Item("it_category")))
                    cmbFinanCategory.SelectedIndex = cmbFinanCategory.FindStringExact((tempTb.Rows(0).Item("it_finance_category")))
                End With
                cmdAdd.Enabled = False
                cmdDelete.Enabled = True
                cmdSave.Enabled = True
            Else
                cmdAdd.Enabled = True
                cmdDelete.Enabled = False
                cmdSave.Enabled = False
                txtItName.Text = ""
                Call fillItCategories()
                Call fillProProfile()
                Call filldisProfiles()
                Call fillFinCat()
            End If
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try


问:
Testing shared_preferences on flutter
I'm writing a flutter application and I'm having this issue when writing the tests. This method is supposed to write data into TextFields and tap a button which saves this data in SharedPrefs:

testWidgets('Click on login saves the credentials',
      (WidgetTester tester) async {

    await tester.pumpWidget(MyApp());

    await tester.enterText(find.byKey(Key('phoneInput')), 'test');
    await tester.enterText(find.byKey(Key('passwordInput')), 'test');
    await tester.tap(find.byIcon(Icons.lock));

    SharedPreferences prefs = await SharedPreferences.getInstance();
    expect(prefs.getString('phone'), 'test');
    expect(prefs.getString('password'), 'test');
  });
```

<p>This test will fail getting the SharedPreferences instance with this error:</p>

```The following TimeoutException was thrown running a test:
TimeoutException after 0:00:03.500000: The test exceeded the timeout. It may have hung.
Consider using "addTime" to increase the timeout before expensive operations.
```

Update: Seems that the problem is not actually the timeout because even with 60 seconds the test is not capable of resolving the SharedPreferences instance.

答:
You could use the provided mock setMockInitialValues

testWidgets('Click on login saves the credentials',
      (WidgetTester tester) async {

    await tester.pumpWidget(MyApp());

    SharedPreferences.setMockInitialValues(<String, dynamic>{
      'flutter.phone': '',
      'flutter.password': '',
    });

    await tester.enterText(find.byKey(Key('phoneInput')), 'test');
    await tester.enterText(find.byKey(Key('passwordInput')), 'test');
    await tester.tap(find.byIcon(Icons.lock));

    SharedPreferences prefs = await SharedPreferences.getInstance();
    expect(prefs.getString('phone'), 'test');
    expect(prefs.getString('password'), 'test');
  });
```

Title: Testing shared_preferences on flutter

Body:
I'm writing a flutter application and I'm having this issue when writing the tests. This method is supposed to write data into TextFields and tap a button which saves this data in SharedPrefs:

testWidgets('Click on login saves the credentials',
      (WidgetTester tester) async {

    await tester.pumpWidget(MyApp());

    await tester.enterText(find.byKey(Key('phoneInput')), 'test');
    await tester.enterText(find.byKey(Key('passwordInput')), 'test');
    await tester.tap(find.byIcon(Icons.lock));

    SharedPreferences prefs = await SharedPreferences.getInstance();
    expect(prefs.getString('phone'), 'test');
    expect(prefs.getString('password'), 'test');
  });

This test will fail getting the SharedPreferences instance with this error:

The following TimeoutException was thrown running a test:
TimeoutException after 0:00:03.500000: The test exceeded the timeout. It may have hung.
Consider using "addTime" to increase the timeout before expensive operations.

Update: Seems that the problem is not actually the timeout because even with 60 seconds the test is not capable of resolving the SharedPreferences instance.


问:
ScrollViewer won't scroll on empty parts of the Grid
I have a Grid with a ScrollViewer around it:

```<code><ScrollViewer>
    <Grid x:Name="MainGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
    </Grid>
</ScrollViewer>
</code>```

I the code-behind I fill this Grid with a dynamic amount of RowDefinitions. In the first column, I always put a TextBlock displaying a certain time of day (08:00, 08:10, ...):

http://www.youth-area.ch/users/finnland/times.png

My problem now is the scolling. When I mousescroll with my cursor over the textblocks, it scrolls without a problem. But when I place my cursoer over the empty part of the grid (right side), it won't scroll.

How do I fix that?

答: I think you might just have to set a background on your Grid?</p>

Body:
I have a Grid with a ScrollViewer around it:

<ScrollViewer>
    <Grid x:Name="MainGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
    </Grid>
</ScrollViewer>

I the code-behind I fill this Grid with a dynamic amount of RowDefinitions. In the first column, I always put a TextBlock displaying a certain time of day (08:00, 08:10, ...):

http://www.youth-area.ch/users/finnland/times.png

My problem now is the scolling. When I mousescroll with my cursor over the textblocks, it scrolls without a problem. But when I place my cursoer over the empty part of the grid (right side), it won't scroll.

How do I fix that?


问:
how to get virtual user number, iteration number and total virtual users count during runtime in Gatling Scala script?
Is there any way to get virtual user number, iteration number and total virtual users count during runtime in Gatling Scala script and how can use those information in script like in requests or custom code?

I am looking for similar functions like ${__threadNum} and ${__iterationNum} of JMeter.

For example-
If I have one scenario and I am running it with 10 virtual users and each virtual user will iterate the scenario 20 times then how will how know the iteration/repeat number with respect to each virtual user. And also how will I know the current status of virtual user (means which virtual user is running now and how many iteration it has completed) and save it in variable so that I can use it in script.

答:
First, Gatling's virtual users are not threads.
You probably use this term because of JMeter's leaking implementation detail.

In Gatling, you get real time stats in the console.

If you want real time charts, the best solution is FrontLine.


问:
Calcute mean for same time on different dates
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

```<code>dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))
</code>```

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

```<code>time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667
</code>```

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

答:
The answer to your question is no. Objects of class POSIXct must have a date.

Here's an approach with lubridate and dplyr:

```<code>library(dplyr)
library(lubridate)
dat %>%
  mutate(hour = hour(date_and_time),
         minute = minute(date_and_time)) %>%
  group_by(hour,minute) %>%
  dplyr::summarise(mean_amount = mean(amount))
#   hour minute mean_amount
#  <int>  <int>       <dbl>
#1    13     23        6.33
#2    13     24       27.7
</code>```

Body:
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

Body:
The answer to your question is no. Objects of class POSIXct must have a date.

Here's an approach with lubridate and dplyr:

library(dplyr)
library(lubridate)
dat %>%
  mutate(hour = hour(date_and_time),
         minute = minute(date_and_time)) %>%
  group_by(hour,minute) %>%
  dplyr::summarise(mean_amount = mean(amount))
#   hour minute mean_amount
#  <int>  <int>       <dbl>
#1    13     23        6.33
#2    13     24       27.7


问:
'TypeError: only integer scalar arrays can be converted to a scalar index' when extracting elements from array
I am trying to pull certain indices from an array column of a dataframe by calling the index from a 1D array.

```<code>import pandas as pd
import numpy as np
from operator import itemgetter

i = np.arange(10)
range1 = np.where((i>=0) & (i<=2))
range2 = np.where((i>=3) & (i<=4))
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['a', 'b', 'c', 'd', 'e']].values.tolist()
df
</code>```

I used this method to extract the elements-

```<code>df['arr1']=df['arr'].apply(lambda x:itemgetter(*range1)(x))
df['arr2']=df['arr'].apply(lambda x:itemgetter(*range2)(x))
</code>```

But got the error-

```<code>TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

I tried converting the ranges to type integer using-

```<code>df['arr1'] = np.array(df['arr'])[range1.astype(int)]
</code>```

But got the error-

```<code>AttributeError: 'tuple' object has no attribute 'astype'
</code>```

So then I tried-

```<code>df['arr1'] = np.array(df['arr'])[int(range1)]
</code>```

But got the error-

```<code>TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
</code>```

Not sure how to proceed.

答:
When you define both ranges, change your code to:

```<code>range1 = i[np.where((i>=0) & (i<=2))]
range2 = i[np.where((i>=3) & (i<=4))]
</code>```

i.e. create an array containing elements of i indicated by where,
so the result is also ndarray with respectively filtered content.

Note that np.where((i>=0) & (i<=2)) alone yields a generator
comprehension containing (array([0, 1, 2], dtype=int64),), i.e.:

a tuple composed of a single element,

this element is a ndarray containing [0, 1, 2].

So such tuple cannot be used as an argument of itemgetter, but after the
proposed change in your code each range contains a Numpy array,
which you can use there.

Another 2, probably more natural solutions: Define both ranges as plain
pythonic lists:

```<code>range1 = [0, 1, 2]
range2 = [3, 4]
</code>```

or Numpy arrays:

```<code>range1 = np.arange(3)
range2 = np.arange(3, 5)
</code>```

Body:
I am trying to pull certain indices from an array column of a dataframe by calling the index from a 1D array.

import pandas as pd
import numpy as np
from operator import itemgetter

i = np.arange(10)
range1 = np.where((i>=0) & (i<=2))
range2 = np.where((i>=3) & (i<=4))
df = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
df['arr'] = df[['a', 'b', 'c', 'd', 'e']].values.tolist()
df

I used this method to extract the elements-

df['arr1']=df['arr'].apply(lambda x:itemgetter(*range1)(x))
df['arr2']=df['arr'].apply(lambda x:itemgetter(*range2)(x))

But got the error-

TypeError: only integer scalar arrays can be converted to a scalar index

I tried converting the ranges to type integer using-

df['arr1'] = np.array(df['arr'])[range1.astype(int)]

But got the error-

AttributeError: 'tuple' object has no attribute 'astype'

So then I tried-

df['arr1'] = np.array(df['arr'])[int(range1)]

But got the error-

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

Not sure how to proceed.

Body:
When you define both ranges, change your code to:

range1 = i[np.where((i>=0) & (i<=2))]
range2 = i[np.where((i>=3) & (i<=4))]

i.e. create an array containing elements of i indicated by where,
so the result is also ndarray with respectively filtered content.

Note that np.where((i>=0) & (i<=2)) alone yields a generator
comprehension containing (array([0, 1, 2], dtype=int64),), i.e.:

a tuple composed of a single element,

this element is a ndarray containing [0, 1, 2].

So such tuple cannot be used as an argument of itemgetter, but after the
proposed change in your code each range contains a Numpy array,
which you can use there.

Another 2, probably more natural solutions: Define both ranges as plain
pythonic lists:

range1 = [0, 1, 2]
range2 = [3, 4]

or Numpy arrays:

range1 = np.arange(3)
range2 = np.arange(3, 5)


问:
How test NFC on emulator?
Android Studio 4.0

I success start android emulator (Android 10.0). Nice.

But I need to pass data between emulators by NFC protocol. Is it possible on emulator to work with NFC?

答:
I'm sorry for the bad news but ther's no official NFC support in the AVD since Google never implemented it.

Years ago there was an openNFC project but I just found out the website is no longer avaliable.

The only solution looks like is to use USB debugging.

Title: How test NFC on emulator?


问:
AMPL IDE error : The IDE cannot find the AMPL executable
I'm using windows 10 and I downloaded ampl package. When I ran amplide.exe file, I got this error:

```<code>The IDE cannot find the AMPL executable.
For assistance, copy this entire message and send it to licensing@ampl.com.
Search paths:
C:\Users\~\Desktop\GNE
C:/Users/~/Desktop/GNE/amplide/jre/bin/server
C:/Users/~/Desktop/GNE/amplide/jre/bin
C:/Users/~/Desktop/GNE/amplide/jre/lib/amd64
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\System32\OpenSSH\
C:\Program Files\Microsoft VS Code\bin
C:\baron
C:\Program Files\PuTTY\
C:\Program Files\Git\cmd
C:\Anaconda3
C:\Anaconda3\Library\mingw-w64\bin
C:\Anaconda3\Library\usr\bin
C:\Anaconda3\Library\bin
C:\Anaconda3\Scripts
C:\Users\~\AppData\Local\Microsoft\WindowsApps
C:\Users\~\Desktop\GNE\amplide
</code>```

How can I fix it?

答:
It's rare. You could try to reinstall the AMPL and the AMPL IDE.

AMPL: AMPL for students
AMPL IDE: AMPL IDE

Then, put your ampl with the student license inside the folder of IDE.

Regards

Body:
I'm using windows 10 and I downloaded ampl package. When I ran amplide.exe file, I got this error:

The IDE cannot find the AMPL executable.
For assistance, copy this entire message and send it to licensing@ampl.com.
Search paths:
C:\Users\~\Desktop\GNE
C:/Users/~/Desktop/GNE/amplide/jre/bin/server
C:/Users/~/Desktop/GNE/amplide/jre/bin
C:/Users/~/Desktop/GNE/amplide/jre/lib/amd64
C:\WINDOWS\system32
C:\WINDOWS
C:\WINDOWS\System32\Wbem
C:\WINDOWS\System32\WindowsPowerShell\v1.0\
C:\WINDOWS\System32\OpenSSH\
C:\Program Files\Microsoft VS Code\bin
C:\baron
C:\Program Files\PuTTY\
C:\Program Files\Git\cmd
C:\Anaconda3
C:\Anaconda3\Library\mingw-w64\bin
C:\Anaconda3\Library\usr\bin
C:\Anaconda3\Library\bin
C:\Anaconda3\Scripts
C:\Users\~\AppData\Local\Microsoft\WindowsApps
C:\Users\~\Desktop\GNE\amplide

How can I fix it?


问:
Dynamics controls lost on postback
This old chestnut again.

My page is constructed as follows; I have a dropdownlist which is databound on first load. When the user selects a value from this, a postback is performed which then databinds a repeater control.

The ItemTemplate of this repeater control contains a placeholder control. In code behind in the ItemDataBound event of the repeater, I am adding two controls dynamically to this placeholder, a hiddenfield and a checkbox.

When the user clicks the save button, I then want to iterate over all those dynamically created hiddenfields and checkboxes and determine their values. However when the user clicks the save button, those controls no longer exist as shown in the page trace.

I know this is a lifecycle issue and the articles I've seen on this suggest using Init methods to dynamically create your controls but I can't because of the way my page works, e.g. the repeater control only appears and binds after a value is chosen from the dropdownlist.

What do I need to do to maintain the dynamic controls through the postback caused by clicking on the save button?

答:
The problem is when you hit the save button probabily you dont re-bind the repeater and the controls you have added at run time withint the ItemDataBound event are not longer available(because they don't exist anymore)
Why don't you add those control at design time using the Eval function the set up the value of the hidden field?</p>

Title: Dynamics controls lost on postback


答:
If by datetime you mean POSIXct then that class cannot represent times without a date; however, the chron times class can.

The following converts the date/time to a chron object, ch, and then converts that to a times object, time_of_day, and truncate that to the minute. Finally we aggregate amount by that.

```<code>library(chron)

ch <- as.chron(format(dat$date_and_time))
time_of_day <- trunc(ch - dates(ch), "min")
ag <- aggregate(amount ~ time_of_day, dat, mean)
</code>```

giving:

```<code>> ag
  time_of_day    amount
1    13:23:00  6.333333
2    13:24:00 27.666667

> str(ag)
'data.frame':   2 obs. of  2 variables:
 $ time_of_day: 'times' num  13:23:00 13:24:00
  ..- attr(*, "format")= chr "h:m:s"
 $ amount     : num  6.33 27.67
</code>```

Title: Calcute mean for same time on different dates

Body:
If by datetime you mean POSIXct then that class cannot represent times without a date; however, the chron times class can.

The following converts the date/time to a chron object, ch, and then converts that to a times object, time_of_day, and truncate that to the minute. Finally we aggregate amount by that.

library(chron)

ch <- as.chron(format(dat$date_and_time))
time_of_day <- trunc(ch - dates(ch), "min")
ag <- aggregate(amount ~ time_of_day, dat, mean)

giving:

> ag
  time_of_day    amount
1    13:23:00  6.333333
2    13:24:00 27.666667

> str(ag)
'data.frame':   2 obs. of  2 variables:
 $ time_of_day: 'times' num  13:23:00 13:24:00
  ..- attr(*, "format")= chr "h:m:s"
 $ amount     : num  6.33 27.67


问:
I received an EOL error on a print line. Can anyone help me with it?
I'm getting an EOL error and am unsure how to fix it.

My code is as follows:
print ("I'm so glad you feel " + emotion + ", " + username")

I get the following error
print ("I'm so glad you feel " + emotion + ", " + username")

Error: EOL while scanning string literal

Is anyone able to give me advice?

Edit: the arrow is under the final bracket

答:
Replace print ("I'm so glad you feel " + emotion + ", " + username")
with

print ("I'm so glad you feel " + emotion + ", " + username).

It is because of trailing " , you must close " on the same line as you can see there is extra double quote after username!

" must occur in pairs you must close a double quote after starting it!


问:
Python not writing whole output into file
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)
</code>```

Content of writing.txt

```<code>/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&
</code>```

Output of internallinks.txt

```<code>www.icom.org.cn/icom/faculty/viewer/?id=470&
</code>```

Output of command print (combined) before with is closed

```<code>PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>
</code>```

答:
You are assigning a new string to the combined variable you have to add the old with assigned combined to assign all of the strings

```<code>internallink = "www.icom.org.cn"
combined = ''
for every_line in tt:
    # If you don't want the text on newline you can remove `\n`
    combined = combined + internallink + every_line.strip() + '\n'

print(combined)
</code>```

OutPut:-

```<code>www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470
</code>```

Body:
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)

Content of writing.txt

/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&

Output of internallinks.txt

www.icom.org.cn/icom/faculty/viewer/?id=470&

Output of command print (combined) before with is closed

PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>

Body:
You are assigning a new string to the combined variable you have to add the old with assigned combined to assign all of the strings

internallink = "www.icom.org.cn"
combined = ''
for every_line in tt:
    # If you don't want the text on newline you can remove `\n`
    combined = combined + internallink + every_line.strip() + '\n'

print(combined)

OutPut:-

www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470


问:
Failed to restore the NuGet packages: Error: MSBuild tools not found
I am trying to get React Native For Windows working, but I am having tough times installing the required dependencies. I have installed Visual Studio and installed the required dependencies as well

I am gettign following error Failed to restore the NuGet packages: Error: MSBuild tools not found. Make sure all required components have been installed (e.g. v141 support) when i run

```<code> npx react-native run-windows
</code>```

I have found issue regarding this https://github.com/microsoft/react-native-windows/issues/3263 but the solution  does not work for me
 I have installed everything related to this

I have nodejs installed in my PC.

I am using the recommended version of React Native

答:
It looks like you don't have the Desktop development workload selected in the VS installer. See this:
dependencies</p>

Body:
I am trying to get React Native For Windows working, but I am having tough times installing the required dependencies. I have installed Visual Studio and installed the required dependencies as well

I am gettign following error Failed to restore the NuGet packages: Error: MSBuild tools not found. Make sure all required components have been installed (e.g. v141 support) when i run

 npx react-native run-windows

I have found issue regarding this https://github.com/microsoft/react-native-windows/issues/3263 but the solution  does not work for me
 I have installed everything related to this

I have nodejs installed in my PC.

I am using the recommended version of React Native


问:
PHP/MySQL - Performance considerations querying (select only) 48k rows
I am currently attempting to build a web application that relies quite heavily on postcode data (supplied from OS CodePoint Open). The postcode database has 120 tables which breaks down the initial postcode prefix (i.e. SE, WS, B). Inside these tables there are between 11k - 48k rows with 3 fields (Postcode, Lat, Lng).

What I need to be able to do is for a user to come online, enter their postcode i.e. SE1 1LD which then selects the SE table, and converts the postcode into a lat / lng.

I am fine with doing this on a PHP level. My concern is.. well the huge number of rows that will be queried and whether it is going to grind my website to a halt?

If there are any techniques that I should know about, please do let me know.. I've never worked with tables with big numbers in!

Thanks :)

答: selecting from 48k rows in mysql is not big, in fact its rather small. index it properly and you are fine.</p>


问:
PowerShell bug “execution of scripts is disabled on this system.”
I have a power shell script that runs to stop services, 'stop / terminate process' , delete 2 files and then restart.

I can run this script perfect on my Windows 10 64 Bit Host Machine - with ZERO issues.
I try to run it in my Virtual Machines and I get the error

cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170

SO just for giggles I went to see my group policies and they are not configured on either machine.

Administrative Templates > Windows Components > Windows PowerShell
Not Configured.

So why the issue on the virtual machine and not in my host ?

EDIT
Ran Get-ExecutionPolicy and also Get-ExecutionPolicy-List on VM
Restricted

```<code>MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined
</code>```

Ran it on my Host

```<code>        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine    Unrestricted
</code>```

I do not know how my local machine was changed - software installation ??

答:
Run Powershell as an administrator and run the following command:
set-executionpolicy remotesigned

Body:
I have a power shell script that runs to stop services, 'stop / terminate process' , delete 2 files and then restart.

I can run this script perfect on my Windows 10 64 Bit Host Machine - with ZERO issues.
I try to run it in my Virtual Machines and I get the error

cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170

SO just for giggles I went to see my group policies and they are not configured on either machine.

Administrative Templates > Windows Components > Windows PowerShell
Not Configured.

So why the issue on the virtual machine and not in my host ?

EDIT
Ran Get-ExecutionPolicy and also Get-ExecutionPolicy-List on VM
Restricted

MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine       Undefined

Ran it on my Host

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine    Unrestricted

I do not know how my local machine was changed - software installation ??


答: You just don't create them dynamically just on the on selection change of the drop-down set visibility true or false for the repeater that will solve your problem.on post back you have to again create those control as they are Dynamically created.</p>

Title: Dynamics controls lost on postback

Body:
This old chestnut again.

My page is constructed as follows; I have a dropdownlist which is databound on first load. When the user selects a value from this, a postback is performed which then databinds a repeater control.

The ItemTemplate of this repeater control contains a placeholder control. In code behind in the ItemDataBound event of the repeater, I am adding two controls dynamically to this placeholder, a hiddenfield and a checkbox.

When the user clicks the save button, I then want to iterate over all those dynamically created hiddenfields and checkboxes and determine their values. However when the user clicks the save button, those controls no longer exist as shown in the page trace.

I know this is a lifecycle issue and the articles I've seen on this suggest using Init methods to dynamically create your controls but I can't because of the way my page works, e.g. the repeater control only appears and binds after a value is chosen from the dropdownlist.

What do I need to do to maintain the dynamic controls through the postback caused by clicking on the save button?


问:
Installing Shippo PHP Manually
Is there a way to install the Shippo PHP files manually without Composer or Laravel?

I uploaded the files manually, but I get an error when I run the examples:

Warning:
  require_once(/var/www/html/shippo/examples../../vendor/autoload.php):
  failed to open stream: No such file or directory.

I'm not familiar with Composer or Laravel and have not been able to get Composer to work.

答:
Shippo.php has the tests for cURL, JSON and mbstring internally so don't worry about it.</p>

```<code>// Tested on PHP 5.2, 5.3
if (!function_exists('curl_init')) {
    throw new Exception('Shippo needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
    throw new Exception('Shippo needs the JSON PHP extension.');
}
if (!function_exists('mb_detect_encoding')) {
    throw new Exception('Shippo needs the Multibyte String PHP extension.');
}
</code>```

Title: Installing Shippo PHP Manually

Body:
Shippo.php has the tests for cURL, JSON and mbstring internally so don't worry about it.

// Tested on PHP 5.2, 5.3
if (!function_exists('curl_init')) {
    throw new Exception('Shippo needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
    throw new Exception('Shippo needs the JSON PHP extension.');
}
if (!function_exists('mb_detect_encoding')) {
    throw new Exception('Shippo needs the Multibyte String PHP extension.');
}


问:
Jmeter correlation for values with no left or right boundries
I wanna correlate a alphanumeric 81fe8bfe87576c3ecb22426f8e57847382917acf value returned from a POST API request as Response which consists of no left or right boundaries, I am using ^[a-zA-Z0-9]+$ as regex expression which is a correct regex expression with Jmeter RegExp Tester, but unable to extract the alphanumeric value from the response and store in a variable as determined by the logs using Regular Expression Extractor.

But, Values returned by the logs shows unable to extract alphanumeric value using Regular Expression Extractor.

Here is my Regular Expression Extractor to extract the alphanumeric value

I already have tried out all the Fields to check options available, nothing works. I am not sure , exactly why is it not working as the regex expression ^[a-zA-Z0-9]+$ is correct, maybe it's related to empty or no left and right boundaries.

Would really appreciate any resolution provided.

答:
You need to surround your regular expression with parentheses in order to have a capture group, see Meta Characters chapter of JMeter User Manual for more information

Given you need to extract only alphanumeric characters you can simplify your regular expression to just (\w+)

Given you need to get the full response you can just use Boundary Extractor and leave both boundaries blank - JMeter will store the whole response into a JMeter Variable (it will work for JMeter 5.2 or higher, see JMeter Bug 63775 for details

If you need to store the whole response into a JMeter Variable and want to use Regular Expression Extractor for this the relevant regular expression would be (?s)(^.*)


问:
why dropzone submits form twice
Hi I am trying to integrate my form with some other fields and dropzone I find that the controller is called twice not sure why.
Could anyone please help me

```<code>autoProcessQueue : false,
    uploadMultiple : true,
    maxFilesize : 256, // MB
    parallelUploads : 10,
    maxFiles : 10,
    addRemoveLinks : true,
    previewsContainer : ".dropzone-previews",

    //The setting up of the dropzone
    init : function() {

        var myDropzone = this;

        // first set autoProcessQueue = false
        $("form").one("submit", function(event) {
              myDropzone.processQueue();

        });
</code>```

thanks
priya

答:
Just try with the following code in the init function:

```<code>init: function() {
      dz = this;
            document.getElementById("submit").addEventListener("click", function handler(e) {
                if (dz.getAcceptedFiles().length > 0) {
                    e.currentTarget.removeEventListener(e.type, handler);
                    e.preventDefault();
                    e.stopPropagation();
                    dz.processQueue();
                }
          });
            this.on("queuecomplete", function(file) {
                document.getElementById("submit").click();
            });

  },
  autoProcessQueue: false,

</code>```

Title: why dropzone submits form twice

Body:
Hi I am trying to integrate my form with some other fields and dropzone I find that the controller is called twice not sure why.
Could anyone please help me

autoProcessQueue : false,
    uploadMultiple : true,
    maxFilesize : 256, // MB
    parallelUploads : 10,
    maxFiles : 10,
    addRemoveLinks : true,
    previewsContainer : ".dropzone-previews",

    //The setting up of the dropzone
    init : function() {

        var myDropzone = this;

        // first set autoProcessQueue = false
        $("form").one("submit", function(event) {
              myDropzone.processQueue();

        });

thanks
priya

Body:
Just try with the following code in the init function:

init: function() {
      dz = this;
            document.getElementById("submit").addEventListener("click", function handler(e) {
                if (dz.getAcceptedFiles().length > 0) {
                    e.currentTarget.removeEventListener(e.type, handler);
                    e.preventDefault();
                    e.stopPropagation();
                    dz.processQueue();
                }
          });
            this.on("queuecomplete", function(file) {
                document.getElementById("submit").click();
            });

  },
  autoProcessQueue: false,


问:
Why aren't I getting any definitions when I type "get-command -type cmdlet"?
This is my first day learning powershell so forgive me if this is a silly question...

But the instruction video I am watching shows the teacher typing in  "get-command -type cmdlet" to demonstrate how to get a list of all available cmdlets and their definitions. I'm getting the cmdlets, but my powershell is not listing the definitions. I'm attaching screenshots to show you the what he has and what I have. what changes do I have to make to get this fixed?

答:
The definition property may not be appearing becuse PowerShell is formatting it for your display. The definition is likely to be too long for your console display, so it will end with '...'.

Use the following to see all of the member properties available. Based on that, you can choose which properties you want to see.

```<code>Get-Command -Type Cmdlet | Format-List -Property Name, Definition
</code>```

If you want to see PowerShell code, this might be interesting.

```<code>Get-Command -Type Function |
    Where-Object { $_.Definition.Length -gt 0 } |
    Select-Object -Property Name,Definition |
    Format-List
</code>```

See all of the propety members available.

```<code>PS H:\> Get-Command -Type Cmdlet | Get-Member

   TypeName: System.Management.Automation.CmdletInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
HelpFile            Property       string HelpFile {get;}
ImplementingType    Property       type ImplementingType {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTypeName] OutputType {get;}
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.ParameterMetadata] Parameters {get;}
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.CommandParameterSetInfo] ParameterSets...
PSSnapIn            Property       System.Management.Automation.PSSnapInInfo PSSnapIn {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DLL                 ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference...
</code>```

Body:
The definition property may not be appearing becuse PowerShell is formatting it for your display. The definition is likely to be too long for your console display, so it will end with '...'.

Use the following to see all of the member properties available. Based on that, you can choose which properties you want to see.

Get-Command -Type Cmdlet | Format-List -Property Name, Definition

If you want to see PowerShell code, this might be interesting.

Get-Command -Type Function |
    Where-Object { $_.Definition.Length -gt 0 } |
    Select-Object -Property Name,Definition |
    Format-List

See all of the propety members available.

PS H:\> Get-Command -Type Cmdlet | Get-Member

   TypeName: System.Management.Automation.CmdletInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ResolveParameter    Method         System.Management.Automation.ParameterMetadata ResolveParameter(string name)
ToString            Method         string ToString()
CommandType         Property       System.Management.Automation.CommandTypes CommandType {get;}
DefaultParameterSet Property       string DefaultParameterSet {get;}
Definition          Property       string Definition {get;}
HelpFile            Property       string HelpFile {get;}
ImplementingType    Property       type ImplementingType {get;}
Module              Property       psmoduleinfo Module {get;}
ModuleName          Property       string ModuleName {get;}
Name                Property       string Name {get;}
Noun                Property       string Noun {get;}
Options             Property       System.Management.Automation.ScopedItemOptions Options {get;set;}
OutputType          Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.PSTypeName] OutputType {get;}
Parameters          Property       System.Collections.Generic.Dictionary[string,System.Management.Automation.ParameterMetadata] Parameters {get;}
ParameterSets       Property       System.Collections.ObjectModel.ReadOnlyCollection[System.Management.Automation.CommandParameterSetInfo] ParameterSets...
PSSnapIn            Property       System.Management.Automation.PSSnapInInfo PSSnapIn {get;}
RemotingCapability  Property       System.Management.Automation.RemotingCapability RemotingCapability {get;}
Source              Property       string Source {get;}
Verb                Property       string Verb {get;}
Version             Property       version Version {get;}
Visibility          Property       System.Management.Automation.SessionStateEntryVisibility Visibility {get;set;}
DLL                 ScriptProperty System.Object DLL {get=$this.ImplementingType.Assembly.Location;}
HelpUri             ScriptProperty System.Object HelpUri {get=$oldProgressPreference = $ProgressPreference...


问:
BouncingScrollPhysics not working with "shrinkWrap: true"
I have a ListView with shrinkWrap: true.

Also, I have applied BouncingScrollPhysics() to the ListView

The problem is bounce physics only works at the bottom of ListView. When I scroll to the top, it doesn't show the bounce effect.

答: I had the same problem, I just used physics: AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics())


问:
Will console.log()'ing type "any" variable cause error on Typescript?
I will console.log(variable: any) in Typescript, but I don't want it to cause an error, and I don't want to add try{}catch block everywhere. Will console.log(any) cause any type of error? Or will it print everything I give?</p>

```<code>public print(data:any){
    console.log(data);
}
</code>```

答:
No, it will not. Typescript is used to statically analyze code.

MDN words about console log (https://developer.mozilla.org/en-US/docs/Web/API/Console/log):

The Console method log() outputs a message to the web console. The
  message may be a single string (with optional substitution values), or
  it may be any one or more JavaScript objects.

Body:
I will console.log(variable: any) in Typescript, but I don't want it to cause an error, and I don't want to add try{}catch block everywhere. Will console.log(any) cause any type of error? Or will it print everything I give?

public print(data:any){
    console.log(data);
}