问:
foolbox and tf.keras (keras copy within tensorflow)
For foolbox, see here.

I'm new to tensorflow and according to this video and also this video it is recommended, that I use tf.keras for prototyping and »playing with« machine learning models, especially neural networks.
Consider this MWE (lenet5.h5 is a convolutional neural network in HDF5 file format, built and trained by tf.keras):

```<code>import numpy as np

import foolbox
import keras
import tensorflow as tf

#network = keras.models.load_model('lenet5.h5')
network = tf.keras.models.load_model('lenet5.h5')
with np.load('data/dataset/mnist_32x32x1.npz') as data:
    x_test = data['testing_x']
foolbox_model = foolbox.models.KerasModel(
    model = network,
    bounds = (0.0, 1.0),
)
criterion = foolbox.criteria.Misclassification()
attack = foolbox.attacks.GradientAttack(foolbox_model, criterion)
image = x_test[0]
adversarial = attack(image, label = 7)
print(np.argmax(network.predict(adversarial.reshape(1, 32, 32, 1)), axis = 1))
</code>```

If I comment in the first network = ... line and comment out the second one, the result of the above script is

```<code>> [3]
</code>```

whereas in the current state, the following exceptions occur:

```<code>.../.env/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64== np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
2018-06-19 23:36:34.601249: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Traceback (most recent call last):
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1322, in _do_call
    return fn(*args)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1307, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1409, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 19, in <module>
    adversarial = attack(image, label = 7)
File ".../.env/lib/python3.5/site-packages/foolbox/attacks/base.py", line 88, in wrapper
    a = Adversarial(model, criterion, input_or_adv, label)
File ".../.env/lib/python3.5/site-packages/foolbox/adversarial.py", line61, in __init__
    self.predictions(original_image)
File ".../.env/lib/python3.5/site-packages/foolbox/adversarial.py", line240, in predictions
    predictions = self.__model.predictions(image)
File ".../.env/lib/python3.5/site-packages/foolbox/models/base.py", line122, in predictions
    return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=0)
File ".../.env/lib/python3.5/site-packages/foolbox/models/keras.py", line 147, in batch_predictions
    predictions = self._batch_pred_fn([self._process_input(images)])
File ".../.env/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 2482, in __call__
    **self.session_kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 900, in run
    run_metadata_ptr)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1135, in _run
    feed_dict_tensor, options, run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1316, in _do_run
    run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1335, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]

Caused by op 'C1/bias/read', defined at:
File "main.py", line 9, in <module>
    network = tf.keras.models.load_model('lenet5.h5')
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/saving.py", line 241, in load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/saving.py", line 318, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/layers/serialization.py", line 63, in deserialize
    printable_module_name='layer')
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/utils/generic_utils.py", line 171, in deserialize_keras_object
    list(custom_objects.items())))
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/sequential.py", line 317, in from_config
    model.add(layer)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/sequential.py", line 164, in add
    layer(x)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/base_layer.py", line 314, in __call__
    output = super(Layer, self).__call__(inputs, *args, **kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/base.py", line 699, in __call__
    self.build(input_shapes)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/convolutional.py", line 152, in build
    dtype=self.dtype)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/base.py", line 546, in add_variable
    partitioner=partitioner)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/training/checkpointable.py", line 436, in _add_variable_with_custom_getter
    **kwargs_for_getter)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 1317, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 1079, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 425, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 394, in _true_getter
    use_resource=use_resource, constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 786, in _get_single_variable
    use_resource=use_resource)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2220, in variable
    use_resource=use_resource)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2210, in <lambda>
    previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2193, in default_variable_creator
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 235, in __init__
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 397, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 142, in identity
    return gen_array_ops.identity(input, name=name)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3187, in identity
    "Identity", input=input, name=name)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3392, in create_op
    op_def=op_def)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1718, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]
</code>```

(I replaced my project path by »...« and I'm working with a virtual environment located in .env).

So my question/issue is: How to use foolbox and tf.keras? I would like to avoid needing to learn (for now) the complex tensorflow graph structure and therefore it's not an option to use the native tensorflow api of foolbox. Also I'd like to avoid importing regular keras just for this single purpose – I wish to stay clean within tensorflow.

PS: Please create a »foolbox« tag.

答: In October '18, FoolBox implemented an alternative constructor from_keras within its TensorFlowModel module, suitable for the purpose described above.

Body:
For foolbox, see here.

I'm new to tensorflow and according to this video and also this video it is recommended, that I use tf.keras for prototyping and »playing with« machine learning models, especially neural networks.
Consider this MWE (lenet5.h5 is a convolutional neural network in HDF5 file format, built and trained by tf.keras):

import numpy as np

import foolbox
import keras
import tensorflow as tf

#network = keras.models.load_model('lenet5.h5')
network = tf.keras.models.load_model('lenet5.h5')
with np.load('data/dataset/mnist_32x32x1.npz') as data:
    x_test = data['testing_x']
foolbox_model = foolbox.models.KerasModel(
    model = network,
    bounds = (0.0, 1.0),
)
criterion = foolbox.criteria.Misclassification()
attack = foolbox.attacks.GradientAttack(foolbox_model, criterion)
image = x_test[0]
adversarial = attack(image, label = 7)
print(np.argmax(network.predict(adversarial.reshape(1, 32, 32, 1)), axis = 1))

If I comment in the first network = ... line and comment out the second one, the result of the above script is

> [3]

whereas in the current state, the following exceptions occur:

.../.env/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64== np.dtype(float).type`.
from ._conv import register_converters as _register_converters
Using TensorFlow backend.
2018-06-19 23:36:34.601249: I tensorflow/core/platform/cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
Traceback (most recent call last):
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1322, in _do_call
    return fn(*args)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1307, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1409, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "main.py", line 19, in <module>
    adversarial = attack(image, label = 7)
File ".../.env/lib/python3.5/site-packages/foolbox/attacks/base.py", line 88, in wrapper
    a = Adversarial(model, criterion, input_or_adv, label)
File ".../.env/lib/python3.5/site-packages/foolbox/adversarial.py", line61, in __init__
    self.predictions(original_image)
File ".../.env/lib/python3.5/site-packages/foolbox/adversarial.py", line240, in predictions
    predictions = self.__model.predictions(image)
File ".../.env/lib/python3.5/site-packages/foolbox/models/base.py", line122, in predictions
    return np.squeeze(self.batch_predictions(image[np.newaxis]), axis=0)
File ".../.env/lib/python3.5/site-packages/foolbox/models/keras.py", line 147, in batch_predictions
    predictions = self._batch_pred_fn([self._process_input(images)])
File ".../.env/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 2482, in __call__
    **self.session_kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 900, in run
    run_metadata_ptr)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1135, in _run
    feed_dict_tensor, options, run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1316, in _do_run
    run_metadata)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1335, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]

Caused by op 'C1/bias/read', defined at:
File "main.py", line 9, in <module>
    network = tf.keras.models.load_model('lenet5.h5')
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/saving.py", line 241, in load_model
    model = model_from_config(model_config, custom_objects=custom_objects)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/saving.py", line 318, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/layers/serialization.py", line 63, in deserialize
    printable_module_name='layer')
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/utils/generic_utils.py", line 171, in deserialize_keras_object
    list(custom_objects.items())))
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/sequential.py", line 317, in from_config
    model.add(layer)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/sequential.py", line 164, in add
    layer(x)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/keras/_impl/keras/engine/base_layer.py", line 314, in __call__
    output = super(Layer, self).__call__(inputs, *args, **kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/base.py", line 699, in __call__
    self.build(input_shapes)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/convolutional.py", line 152, in build
    dtype=self.dtype)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/layers/base.py", line 546, in add_variable
    partitioner=partitioner)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/training/checkpointable.py", line 436, in _add_variable_with_custom_getter
    **kwargs_for_getter)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 1317, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 1079, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 425, in get_variable
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 394, in _true_getter
    use_resource=use_resource, constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 786, in _get_single_variable
    use_resource=use_resource)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2220, in variable
    use_resource=use_resource)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2210, in <lambda>
    previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2193, in default_variable_creator
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 235, in __init__
    constraint=constraint)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 397, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 142, in identity
    return gen_array_ops.identity(input, name=name)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3187, in identity
    "Identity", input=input, name=name)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3392, in create_op
    op_def=op_def)
File ".../.env/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1718, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value C1/bias
        [[Node: C1/bias/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](C1/bias)]]

(I replaced my project path by »...« and I'm working with a virtual environment located in .env).

So my question/issue is: How to use foolbox and tf.keras? I would like to avoid needing to learn (for now) the complex tensorflow graph structure and therefore it's not an option to use the native tensorflow api of foolbox. Also I'd like to avoid importing regular keras just for this single purpose – I wish to stay clean within tensorflow.

PS: Please create a »foolbox« tag.


来源: stackexchange

问:
Cannot resolve symbol ViewModelProviders
I am working on Android ViewModel architecture component but I am getting the above mentioned error when trying to initialize a ViewModel in an AppCompatActivity.

```<code>import android.arch.lifecycle.ViewModelProviders;
ViewModelProviders.of(this).get(CounterViewModel.class);
</code>```

There are a few questions and articles related to this, and they pointed towards adding the lifecycle:extensions and lifecycle:viewmodel dependencies in the app gradle file, but I am still getting the error.

```<code>implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
</code>```

The package android.arch.lifecycle does not contain the class ViewModelProviders and it only has ViewModelProvider class.

What else needs to be added to access the ViewModelProviders class?

Edit :

Dependencies in app/build.gradle:

```<code>dependencies {
    implementation project(':lifecycle')
    implementation project(':base')
    implementation "android.arch.lifecycle:extensions:1.1.1"
    implementation "android.arch.lifecycle:viewmodel:1.1.1"
    annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
}
</code>```

答: If you are configuring in libary, you can modify the implementation to api

ContentLicense: CC BY-SA 4.0

Body:
I am working on Android ViewModel architecture component but I am getting the above mentioned error when trying to initialize a ViewModel in an AppCompatActivity.

import android.arch.lifecycle.ViewModelProviders;
ViewModelProviders.of(this).get(CounterViewModel.class);

There are a few questions and articles related to this, and they pointed towards adding the lifecycle:extensions and lifecycle:viewmodel dependencies in the app gradle file, but I am still getting the error.

implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

The package android.arch.lifecycle does not contain the class ViewModelProviders and it only has ViewModelProvider class.

What else needs to be added to access the ViewModelProviders class?

Edit :

Dependencies in app/build.gradle:

dependencies {
    implementation project(':lifecycle')
    implementation project(':base')
    implementation "android.arch.lifecycle:extensions:1.1.1"
    implementation "android.arch.lifecycle:viewmodel:1.1.1"
    annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
}


问:
Send multiple images in email using mail()
I stored the images in url format in database.now i want to send mail with multiple images using mail() in php</p>

```<code>$sql11 = "SELECT `photo_id`, `project_id`, `map_id`, `map_flag`, `user_id`, `photo_path`, `pdf_path`, `created_at`, `modified_at` FROM `photos` WHERE map_flag='Task' and map_id='$task_id'";
$rl    = $conn->query($sql11);
while ($res11 = mysqli_fetch_assoc($rl)) {
    $array[] = [$res11['photo_path']];
}
$str     = implode(',', $array);
$message = $message_content . "\n" . "\n" . "\n" . $message1 . "\n" . $message2 . "\n" . $message3 . "\n" . $message4 . "\n" . $message5 . "\n" . $message6 . "\n" . $array . "\n" . $message8 . "\n";
$from    = "123@test.com";
$headers = 'From: ' . $from . "\r\n";
$result  = mail($to, $subject, $message, $headers);
</code>```

答:
First off, you need to tell the email app that this is html. This can be done by adding the line

```<code>$headers .= "Content-type: text/html; charset=UTF-8";
</code>```

Next, what is photo_path? Does it also include the full url or a relative url? You need to set the full url i.e. http://example.com/{$res11['photo_path']}

Body:
I stored the images in url format in database.now i want to send mail with multiple images using mail() in php

$sql11 = "SELECT `photo_id`, `project_id`, `map_id`, `map_flag`, `user_id`, `photo_path`, `pdf_path`, `created_at`, `modified_at` FROM `photos` WHERE map_flag='Task' and map_id='$task_id'";
$rl    = $conn->query($sql11);
while ($res11 = mysqli_fetch_assoc($rl)) {
    $array[] = [$res11['photo_path']];
}
$str     = implode(',', $array);
$message = $message_content . "\n" . "\n" . "\n" . $message1 . "\n" . $message2 . "\n" . $message3 . "\n" . $message4 . "\n" . $message5 . "\n" . $message6 . "\n" . $array . "\n" . $message8 . "\n";
$from    = "123@test.com";
$headers = 'From: ' . $from . "\r\n";
$result  = mail($to, $subject, $message, $headers);

Body:
First off, you need to tell the email app that this is html. This can be done by adding the line

$headers .= "Content-type: text/html; charset=UTF-8";

Next, what is photo_path? Does it also include the full url or a relative url? You need to set the full url i.e. http://example.com/{$res11['photo_path']}


问:
PHP array to postgres array
Now php can't work directly wit Postgresql array. For example, php taking postgresql array like
    '{"foo","bar"}'

I need simple php function to create multidimensional postgresql array from php array.

I think that experimental pg_convert() isn't optimal because it needs of extra data to form simple array string for database output, maybe I misunderstood the idea of this function.

For example, I need to convert

```<code>$from=array(  array( "par_1_1","par_1_2" ), array( "array_2_1", "array_2_2" )  );
$to='{{"par_1_1","par_1_2"},{"par_2_1","par_2_2"}}';
</code>```

Can I use array_walk_recursive() to convert the deepest elements of array?

答:
Here's a simple function for converting a PHP array to PG array.</p>

```<code>function to_pg_array($set) {
    settype($set, 'array'); // can be called with a scalar or array
    $result = array();
    foreach ($set as $t) {
        if (is_array($t)) {
            $result[] = to_pg_array($t);
        } else {
            $t = str_replace('"', '\\"', $t); // escape double quote
            if (! is_numeric($t)) // quote only non-numeric values
                $t = '"' . $t . '"';
            $result[] = $t;
        }
    }
    return '{' . implode(",", $result) . '}'; // format
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP array to postgres array

Body:
Now php can't work directly wit Postgresql array. For example, php taking postgresql array like
    '{"foo","bar"}'

I need simple php function to create multidimensional postgresql array from php array.

I think that experimental pg_convert() isn't optimal because it needs of extra data to form simple array string for database output, maybe I misunderstood the idea of this function.

For example, I need to convert

$from=array(  array( "par_1_1","par_1_2" ), array( "array_2_1", "array_2_2" )  );
$to='{{"par_1_1","par_1_2"},{"par_2_1","par_2_2"}}';

Can I use array_walk_recursive() to convert the deepest elements of array?

Body:
Here's a simple function for converting a PHP array to PG array.

function to_pg_array($set) {
    settype($set, 'array'); // can be called with a scalar or array
    $result = array();
    foreach ($set as $t) {
        if (is_array($t)) {
            $result[] = to_pg_array($t);
        } else {
            $t = str_replace('"', '\\"', $t); // escape double quote
            if (! is_numeric($t)) // quote only non-numeric values
                $t = '"' . $t . '"';
            $result[] = $t;
        }
    }
    return '{' . implode(",", $result) . '}'; // format
}


问:
Javascript for loop stops before the end
I have a really simple home made API that reads the content of some files on the server, parse them and send their content in JSON.

My webpage calls the API using Ajax, reads the data and store them on custom objects. The problem is that, no matter of much files I have parsed in my JSON, only the first one is treated my the Javascript code.

```<code>runs = [];

function Solution(values) {
    this.number = values[0]
    this.weight = values[1]
    this.value = values[2]
    this.score = values[3]
}

function DateValue(date) {
    regex = new RegExp(/(\d{4})-(\d{1,2})-(\d{1,2})-(\d{1,2}):(\d{1,2}):(\d{1,2})-(\d{1,2})/)
    dateArray = date.split(regex)
    this.year = dateArray[1]
    this.month = dateArray[2]
    this.day = dateArray[3]
    this.hour = dateArray[4]
    this.minutes = dateArray[5]
    this.secondes = dateArray[6]
}

function Run(values) {
    this.algorithm = values["log"]["Algorithm used"]
    this.weight = values["log"]["Weight"]
    this.value = values["log"]["Value"]
    this.date = new DateValue(values["log"]["Date"])
    this.solutions = []
    for(i = 0; i < values["datas"].length; i++) {
        this.solutions.push(new Solution(values["datas"][i]))
    }
}

$.ajax({
    url: 'api.php', // the data sent by the API is a valid JSON
    dataType: 'json',
    success: function(data, status) {
        console.log(data);
        for(i = 0; i < data.length; i++) {
            console.log(data[i]);
            var run = new Run(data[i])
            runs.push(run);
        }
    }
});
</code>```

The console.log(data) before the for loop prints correctly all the datas recieved from the API, but the console.log(data[i]) prints only the first element of the array, and I can't understand why.

答:
You are looping using a single global indexing variable i in multiple places.

Your first loop calls Run, which runs another loop to completion incrementing the i variable.

Start your loops declaring a local i each time:

for(var i=0;...)

Body:
I have a really simple home made API that reads the content of some files on the server, parse them and send their content in JSON.

My webpage calls the API using Ajax, reads the data and store them on custom objects. The problem is that, no matter of much files I have parsed in my JSON, only the first one is treated my the Javascript code.

runs = [];

function Solution(values) {
    this.number = values[0]
    this.weight = values[1]
    this.value = values[2]
    this.score = values[3]
}

function DateValue(date) {
    regex = new RegExp(/(\d{4})-(\d{1,2})-(\d{1,2})-(\d{1,2}):(\d{1,2}):(\d{1,2})-(\d{1,2})/)
    dateArray = date.split(regex)
    this.year = dateArray[1]
    this.month = dateArray[2]
    this.day = dateArray[3]
    this.hour = dateArray[4]
    this.minutes = dateArray[5]
    this.secondes = dateArray[6]
}

function Run(values) {
    this.algorithm = values["log"]["Algorithm used"]
    this.weight = values["log"]["Weight"]
    this.value = values["log"]["Value"]
    this.date = new DateValue(values["log"]["Date"])
    this.solutions = []
    for(i = 0; i < values["datas"].length; i++) {
        this.solutions.push(new Solution(values["datas"][i]))
    }
}

$.ajax({
    url: 'api.php', // the data sent by the API is a valid JSON
    dataType: 'json',
    success: function(data, status) {
        console.log(data);
        for(i = 0; i < data.length; i++) {
            console.log(data[i]);
            var run = new Run(data[i])
            runs.push(run);
        }
    }
});

The console.log(data) before the for loop prints correctly all the datas recieved from the API, but the console.log(data[i]) prints only the first element of the array, and I can't understand why.


问:
Getting 3 full years in json format
What would be the best way to create a json object with a 3 full years.

For example:

```<code>{
    2017:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    },
    2018:{
        jan:[
                {day:'monday', timestamp:12512421},
                {day:'tuseday', timestamp:151512}
        ]...
    }
    2019:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    }
}
</code>```

I need to be able to display a week’s in the future. That is for example: what dates are in week 8 on the year 2019. I need some idea of where to start to start formulating the json object… or if it already exists in some kind of library.

But I’m not sure what would be the start to start trying out.

答:
function setYearObject(yearStart, yearEnd) {
    const obj = {};
    const start = new Date(yearStart, 0);
    const end = new Date(yearEnd, 0);
    const months = {
     Jan: [], Feb: [], Mar: [], Apr: [], May: [], Jun: [],
        Jul: [], Aug: [], Sep: [], Oct: [], Nov: [], Dec: []
    };

    while (yearStart < yearEnd) { obj[yearStart++] = months  }
    while (start < end) {
        const timeStamp = start.getTime()
        const parts = start.toDateString().split(" ");
        const year = start.getFullYear().toString()

        obj[year][parts[1]].push({ day: parts[0], timeStamp: timeStamp });
        start.setDate(start.getDate() + 1);
    }
    return obj;
}

console.log(setYearObject(2017, 2020))```

Title: Getting 3 full years in json format

Body:
What would be the best way to create a json object with a 3 full years.

For example:

{
    2017:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    },
    2018:{
        jan:[
                {day:'monday', timestamp:12512421},
                {day:'tuseday', timestamp:151512}
        ]...
    }
    2019:{
        jan:[
            {day:'monday', timestamp:12512421},
            {day:'tuseday', timestamp:151512}
        ]...
    }
}

I need to be able to display a week’s in the future. That is for example: what dates are in week 8 on the year 2019. I need some idea of where to start to start formulating the json object… or if it already exists in some kind of library.

But I’m not sure what would be the start to start trying out.


问:
How do I setup Django on Virtualhost?
How do I setup apache2 virtual host with Django app. Currently I am using Django by "python manage.py runserver". I need to host Django app remotely.</p>

答:
You need to edit /etc/apache2/sites-available/000-default.conf and replace the php based virtualhost configuration which points to /var/www/html  with the one that points to wsgi.py of your project.

Example Virtual Host Configuration (read more)

```<code>Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</code>```

Title: How do I setup Django on Virtualhost?

Body:
You need to edit /etc/apache2/sites-available/000-default.conf and replace the php based virtualhost configuration which points to /var/www/html  with the one that points to wsgi.py of your project.

Example Virtual Host Configuration (read more)

Alias /robots.txt /path/to/mysite.com/static/robots.txt
Alias /favicon.ico /path/to/mysite.com/static/favicon.ico

Alias /media/ /path/to/mysite.com/media/
Alias /static/ /path/to/mysite.com/static/

<Directory /path/to/mysite.com/static>
Require all granted
</Directory>

<Directory /path/to/mysite.com/media>
Require all granted
</Directory>

WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py

<Directory /path/to/mysite.com/mysite>
<Files wsgi.py>
Require all granted
</Files>
</Directory>


问:
Runing a "child" python file as regular user when main python file needs to be run as root
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

```<code>import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

chrometest.py (program that needs to be run as regular user)

```<code>import eel
eel.init('webfiles')
eel.start('index.html')
</code>```

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

答:
oh yes!!.. you can able to run a child python file as a regular python file.but u need to add this line in your parent python file.

```<code>import os
os.system("python  chrometest.py")
</code>```

by this line your parent python file can run your child python file.

Body:
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

chrometest.py (program that needs to be run as regular user)

import eel
eel.init('webfiles')
eel.start('index.html')

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

Body:
oh yes!!.. you can able to run a child python file as a regular python file.but u need to add this line in your parent python file.

import os
os.system("python  chrometest.py")

by this line your parent python file can run your child python file.


问:
Magento - Import pending orders through excel or csv files
Is it possible to import pending  orders through an Excel or CSV file in Magento? If yes, how can I do that?

Thanks.

答:
There seems to be an existing and dedicated module
 for this, I used Google to find this. There will probably be more!</p>


问:
Is it always necesarilly to write the try-catch() inside a method,is static void main() a method,yes static void main() is a method?
Why is the try-catch that is not inside a method, working?

```<code>package ro.ase.acs.main;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import ro.ase.acs.classes.Addition;
import ro.ase.acs.classes.Robot;
import ro.ase.acs.interfaces.BinaryOperation;
import ro.ase.acs.interfaces.DisplayService;

public class Main {

    public static void main(String[] args) {
        Robot robot = new Robot();
        robot.setName("Lego Mindstorms");
        robot.setAutonomy(2);
        robot.setProductionYear(2015);

        try(FileOutputStream fos = new FileOutputStream("robot.bin");
            DataOutputStream data = new DataOutputStream(fos)) {//baga in fisier datele setate mai sus;

            data.writeUTF(robot.getName());
            data.writeFloat(robot.getAutonomy());
            data.writeInt(robot.getProductionYear());

        } catch(IOException e) {
            e.printStackTrace();
        }

        Robot robot2 = new Robot();
        try(FileInputStream fis = new FileInputStream("robot.bin");//se citesc datele din fisier;se creeaza un al 2-lea obiect cu datele pe care le-am bagat anterior in fisier;
            DataInputStream data = new DataInputStream(fis)) {

            robot2.setName(data.readUTF());
            robot2.setAutonomy(data.readFloat());
            robot2.setProductionYear(data.readInt());

        } catch(IOException e) {
            e.printStackTrace();
        }

        System.out.println(robot2);

        try(FileOutputStream fos = new FileOutputStream("robot.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos)) {//ia toate datele ,atributele gasite -n obiectul dat,anterior, cand le-am setat la inceputul programului
            //le scrie byte cu byte in fisier
                oos.writeObject(robot);
        } catch(IOException e) {
            e.printStackTrace();
        }

        Robot robot3 = new Robot();
        try(FileInputStream fis = new FileInputStream("robot.dat");//se baga datele, luate anterior, in robot3;
            ObjectInputStream ois = new ObjectInputStream(fis)) {
                robot3 = (Robot)ois.readObject();
        } catch(IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(robot3);
        System.out.println(new Robot());

        BinaryOperation op = new Addition();
        op = new BinaryOperation() {

            @Override
            public double operation(int x, int y) {
                return x - y;
            }
        };

        op = (int a, int b) -> a * b;
        op = (a, b) -> a / b;
        op = (a, b) -> { return Math.pow(a, b); };
        double result = op.operation(2, 3);

        System.out.println(result);

        DisplayService ds = (m) -> System.out.println(m);
        ds = m -> { System.out.print("Message: "); System.out.println(m);};
        ds.display("Hello from the Lambda expression");
    }

}
</code>```

This is the code written by my teacher, I read that the try-catch() is working only when it is inside a method, but in the code above it is working without being inside a method.Is it enough to declare a new object before the try-catch and write the try without including it inside a method?

Yes, static void main() is a method, this is  the reason why we can write a try-catch statement inside a static void main(), without expecting errors.

答:
public static void main(String[] args) { ... } is a method, and the try-catch block is executed within this main method.

To answer your question in general: you can write your try-catch blocks in methods, or you can use static blocks (which will be executed before main method):

```<code>class ClassName {
    static {
        //try-catch here
    }
}
</code>```

However, you cannot write something like:

```<code>class ClassName {
    //try-catch here
}
</code>```

Body:
Why is the try-catch that is not inside a method, working?

package ro.ase.acs.main;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import ro.ase.acs.classes.Addition;
import ro.ase.acs.classes.Robot;
import ro.ase.acs.interfaces.BinaryOperation;
import ro.ase.acs.interfaces.DisplayService;

public class Main {

    public static void main(String[] args) {
        Robot robot = new Robot();
        robot.setName("Lego Mindstorms");
        robot.setAutonomy(2);
        robot.setProductionYear(2015);

        try(FileOutputStream fos = new FileOutputStream("robot.bin");
            DataOutputStream data = new DataOutputStream(fos)) {//baga in fisier datele setate mai sus;

            data.writeUTF(robot.getName());
            data.writeFloat(robot.getAutonomy());
            data.writeInt(robot.getProductionYear());

        } catch(IOException e) {
            e.printStackTrace();
        }

        Robot robot2 = new Robot();
        try(FileInputStream fis = new FileInputStream("robot.bin");//se citesc datele din fisier;se creeaza un al 2-lea obiect cu datele pe care le-am bagat anterior in fisier;
            DataInputStream data = new DataInputStream(fis)) {

            robot2.setName(data.readUTF());
            robot2.setAutonomy(data.readFloat());
            robot2.setProductionYear(data.readInt());

        } catch(IOException e) {
            e.printStackTrace();
        }

        System.out.println(robot2);

        try(FileOutputStream fos = new FileOutputStream("robot.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos)) {//ia toate datele ,atributele gasite -n obiectul dat,anterior, cand le-am setat la inceputul programului
            //le scrie byte cu byte in fisier
                oos.writeObject(robot);
        } catch(IOException e) {
            e.printStackTrace();
        }

        Robot robot3 = new Robot();
        try(FileInputStream fis = new FileInputStream("robot.dat");//se baga datele, luate anterior, in robot3;
            ObjectInputStream ois = new ObjectInputStream(fis)) {
                robot3 = (Robot)ois.readObject();
        } catch(IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(robot3);
        System.out.println(new Robot());

        BinaryOperation op = new Addition();
        op = new BinaryOperation() {

            @Override
            public double operation(int x, int y) {
                return x - y;
            }
        };

        op = (int a, int b) -> a * b;
        op = (a, b) -> a / b;
        op = (a, b) -> { return Math.pow(a, b); };
        double result = op.operation(2, 3);

        System.out.println(result);

        DisplayService ds = (m) -> System.out.println(m);
        ds = m -> { System.out.print("Message: "); System.out.println(m);};
        ds.display("Hello from the Lambda expression");
    }

}

This is the code written by my teacher, I read that the try-catch() is working only when it is inside a method, but in the code above it is working without being inside a method.Is it enough to declare a new object before the try-catch and write the try without including it inside a method?

Yes, static void main() is a method, this is  the reason why we can write a try-catch statement inside a static void main(), without expecting errors.

Body:
public static void main(String[] args) { ... } is a method, and the try-catch block is executed within this main method.

To answer your question in general: you can write your try-catch blocks in methods, or you can use static blocks (which will be executed before main method):

class ClassName {
    static {
        //try-catch here
    }
}

However, you cannot write something like:

class ClassName {
    //try-catch here
}


问:
Remove elements from Array of Array Swift
For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

```<code>struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}
</code>```

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type
i.e.

```<code>hashmap.buckets.flatMap{$0}.filter{$0.key != -1}
</code>```

is incorrect.

How can I remove all of the buckets with key -1?

答:
You can use removeAll where you filter with contains for the buckets

```<code>hashmap.buckets.removeAll { $0.contains { $0.key == -1 } }
</code>```

Body:
For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type
i.e.

hashmap.buckets.flatMap{$0}.filter{$0.key != -1}

is incorrect.

How can I remove all of the buckets with key -1?

Body:
You can use removeAll where you filter with contains for the buckets

hashmap.buckets.removeAll { $0.contains { $0.key == -1 } }


问:
Interpolation in angularjs

 {{link}}```

"Link" is the url gotten from the database. On click of link, I want the browser to open the link. The problem is that: lets assume the name of my website is "stackoverflow.com". If the link is "facebook.com", on click of this link, it will open "stackoverflow.com/facebook.com" which is not what I want. But if the link is "https://facebook.com", it will open "facebook.com", exactly what I want. The question is that: how can I make the browser open "facebook.com" whether the link is "facebook.com" or "https://facebook.com"

答:
You may use something like this :

```<code><a ng-href={{link}} target="_blank">{{link}}<a>
</code>```

And in your AngularJs controller you may apply a validation check like this :

```<code>if( link doesn't have http://){
    link = 'http://' + link;
}
</code>```

This way your link will always starts with http://

Title: Interpolation in angularjs

Body:
 {{link}}

"Link" is the url gotten from the database. On click of link, I want the browser to open the link. The problem is that: lets assume the name of my website is "stackoverflow.com". If the link is "facebook.com", on click of this link, it will open "stackoverflow.com/facebook.com" which is not what I want. But if the link is "https://facebook.com", it will open "facebook.com", exactly what I want. The question is that: how can I make the browser open "facebook.com" whether the link is "facebook.com" or "https://facebook.com"

Body:
You may use something like this :

<a ng-href={{link}} target="_blank">{{link}}<a>

And in your AngularJs controller you may apply a validation check like this :

if( link doesn't have http://){
    link = 'http://' + link;
}

This way your link will always starts with http://


问:
Random string generation with upper case letters and digits
How do I generate a string of size N, made of numbers and uppercase English letters such as:

6U1S75

4Z4UKK

U911K4

答:
Sometimes 0 (zero) & O (letter O) can be confusing. So I use </p>

```<code>import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')
</code>```

Body:
Sometimes 0 (zero) & O (letter O) can be confusing. So I use

import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')


问:
How can I get a user's media from Instagram without authenticating as a user?
I'm trying to put a user's recent Instagram media on a sidebar. I'm trying to use the Instagram API to fetch the media.

http://instagram.com/developer/endpoints/users/

The documentation says to GET https://api.instagram.com/v1/users/<user-id>/media/recent/, but it says to pass an OAuth access token. An access token represents the authorization to act on behalf of a user. I don't want users to log into Instagram to see this on the sidebar. They shouldn't even need to have an Instagram account.

For instance, I can go to http://instagram.com/thebrainscoop without being logged into Instagram and see photos. I want to do that through the API.

In the Instagram API, non-user-authenticated requests pass a client_id instead of an access_token. If I try that, though, I get:

```<code>{
  "meta":{
    "error_type":"OAuthParameterException",
    "code":400,
    "error_message":"\"access_token\" URL parameter missing. This OAuth request requires an \"access_token\" URL parameter."
  }
}
</code>```

So, is this not possible? Is there no way to fetch a user's latest (public) media without asking a user to log into an Instagram account through OAuth first?

答:
Here is a php script that downloads the images and creates an html file with links on the images. Credit 350D for php version, this is just elaborated..I would suggest putting this is a cron job and firing however often you need. Verified working as of May 2019.

```<code><?
$user = 'smena8m';
$igdata = file_get_contents('https://instagram.com/'.$user.'/');
preg_match('/_sharedData = ({.*);<\/script>/',$igdata,$matches);
$profile_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;
$html = '<div class="instagramBox" style="display:inline-grid;grid-template-columns:auto auto auto;">';
$i = 0;
$max = 9;
while($i<$max){
    $imglink = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->shortcode;
    $img = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->thumbnail_resources[0]->src;
    file_put_contents('ig'.$i.'.jpg',file_get_contents($img));
    $html .= '<a href="https://www.instagram.com/p/'.$imglink.'/" target="_blank"><img src="ig'.$i.'.jpg" /></a>';
    $i++;
}
$html .= '</div>';
$instagram = fopen('instagram.html','w');
fwrite($instagram,$html);
fclose($instagram);
?>
</code>```

Body:
I'm trying to put a user's recent Instagram media on a sidebar. I'm trying to use the Instagram API to fetch the media.

http://instagram.com/developer/endpoints/users/

The documentation says to GET https://api.instagram.com/v1/users/<user-id>/media/recent/, but it says to pass an OAuth access token. An access token represents the authorization to act on behalf of a user. I don't want users to log into Instagram to see this on the sidebar. They shouldn't even need to have an Instagram account.

For instance, I can go to http://instagram.com/thebrainscoop without being logged into Instagram and see photos. I want to do that through the API.

In the Instagram API, non-user-authenticated requests pass a client_id instead of an access_token. If I try that, though, I get:

{
  "meta":{
    "error_type":"OAuthParameterException",
    "code":400,
    "error_message":"\"access_token\" URL parameter missing. This OAuth request requires an \"access_token\" URL parameter."
  }
}

So, is this not possible? Is there no way to fetch a user's latest (public) media without asking a user to log into an Instagram account through OAuth first?

Body:
Here is a php script that downloads the images and creates an html file with links on the images. Credit 350D for php version, this is just elaborated..I would suggest putting this is a cron job and firing however often you need. Verified working as of May 2019.

<?
$user = 'smena8m';
$igdata = file_get_contents('https://instagram.com/'.$user.'/');
preg_match('/_sharedData = ({.*);<\/script>/',$igdata,$matches);
$profile_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;
$html = '<div class="instagramBox" style="display:inline-grid;grid-template-columns:auto auto auto;">';
$i = 0;
$max = 9;
while($i<$max){
    $imglink = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->shortcode;
    $img = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->thumbnail_resources[0]->src;
    file_put_contents('ig'.$i.'.jpg',file_get_contents($img));
    $html .= '<a href="https://www.instagram.com/p/'.$imglink.'/" target="_blank"><img src="ig'.$i.'.jpg" /></a>';
    $i++;
}
$html .= '</div>';
$instagram = fopen('instagram.html','w');
fwrite($instagram,$html);
fclose($instagram);
?>


问:
Dynamics NAV + BC Control Add-In not exposing methods and events
I have created a simple control add-in for Dynamics NAV/BC and I'm having some trouble with it.
I have done exactly the same (as far as I can tell) in this add-in, as I have done in previous add-ins I have created of the same type, which have worked just fine.

The problem is that when the add-in assembly is added to a page (personally I don't know much about this part, I'm just watching as it is being done), the events and methods of the add-in are supposed to appear (stub code should be generated), however this is not the case... Nothing happens.

When they try with a similar assembly (same framework, same kind of interface, same version of 'Microsoft.Dynamics.Framework.UI.Extensibility' assembly - in short a very much similar assembly) the code for the methods and events is generated as expected.

So my question is, obviously, why is it working for one assembly and not the another, when they are next to identical in the C# code?

Here is the code for the assembly not working.

```<code>using Microsoft.Dynamics.Framework.UI.Extensibility;

namespace Dynamics.NAV.CR
{
    [ControlAddInExport("Dynamics.NAV.CR")]
    public interface ICRAddIn
    {
        [ApplicationVisible]
        event ApplicationEventHandler AddInReady;

        [ApplicationVisible]
        event DataEventHandler ButtonClicked;

        [ApplicationVisible]
        event DataEventHandler ElementHtmlRetrieved;

        [ApplicationVisible]
        event DataEventHandler ElementTextRetrieved;

        [ApplicationVisible]
        void setElementHtml(string control_id, string html);

        [ApplicationVisible]
        void setElementText(string control_id, string text);

        [ApplicationVisible]
        void setElementCss(string control_id, string css);

        [ApplicationVisible]
        void addElementCssCls(string control_id, string cls);

        [ApplicationVisible]
        void removeElementCssCls(string control_id, string cls);

        [ApplicationVisible]
        void setElementProp(string control_id, string prop_name, string prop_value);
    }
}
</code>```

What am I missing?

The person deploying the assembly says he has made sure it's 'unblocked', so that shouldn't be the issue.

I forgot to add the code for the custom event handler - here it is.

```<code>namespace Dynamics.NAV.CR
{
    public delegate void DataEventHandler(object data);
}
</code>```

答:
Ok, it turns out that the apparent reason that things wasn't working out for me was due to the Dynamics NAV/BC UI extensibility assembly Microsoft.Dynamics.Framework.UI.Extensibility being of a different version than the target system, or at least that is what I believe was the reason.
I have tried many different things to tweak the project in order to make it work and it seems that changing this assembly did the trick.

I can't be a 100% sure though, since I have not been deploying my assembly to NAV personally and so I don't know whether or not the appropriate amount of service restarts, cache clearings and what ever else of odd required actions has taken place.

So until proof of something else being the cause to my problems emerge, I will assume that it was an assembly version mismatch that was the cause.

Body:
I have created a simple control add-in for Dynamics NAV/BC and I'm having some trouble with it.
I have done exactly the same (as far as I can tell) in this add-in, as I have done in previous add-ins I have created of the same type, which have worked just fine.

The problem is that when the add-in assembly is added to a page (personally I don't know much about this part, I'm just watching as it is being done), the events and methods of the add-in are supposed to appear (stub code should be generated), however this is not the case... Nothing happens.

When they try with a similar assembly (same framework, same kind of interface, same version of 'Microsoft.Dynamics.Framework.UI.Extensibility' assembly - in short a very much similar assembly) the code for the methods and events is generated as expected.

So my question is, obviously, why is it working for one assembly and not the another, when they are next to identical in the C# code?

Here is the code for the assembly not working.

using Microsoft.Dynamics.Framework.UI.Extensibility;

namespace Dynamics.NAV.CR
{
    [ControlAddInExport("Dynamics.NAV.CR")]
    public interface ICRAddIn
    {
        [ApplicationVisible]
        event ApplicationEventHandler AddInReady;

        [ApplicationVisible]
        event DataEventHandler ButtonClicked;

        [ApplicationVisible]
        event DataEventHandler ElementHtmlRetrieved;

        [ApplicationVisible]
        event DataEventHandler ElementTextRetrieved;

        [ApplicationVisible]
        void setElementHtml(string control_id, string html);

        [ApplicationVisible]
        void setElementText(string control_id, string text);

        [ApplicationVisible]
        void setElementCss(string control_id, string css);

        [ApplicationVisible]
        void addElementCssCls(string control_id, string cls);

        [ApplicationVisible]
        void removeElementCssCls(string control_id, string cls);

        [ApplicationVisible]
        void setElementProp(string control_id, string prop_name, string prop_value);
    }
}

What am I missing?

The person deploying the assembly says he has made sure it's 'unblocked', so that shouldn't be the issue.

I forgot to add the code for the custom event handler - here it is.

namespace Dynamics.NAV.CR
{
    public delegate void DataEventHandler(object data);
}


问:
How to change the value of input using inc and dec function in ionic 3
I'm getting the value from the rest-api in input field.

```<code><ion-input name="inpval"  type="tel" id="idvalue"  class="inputvalue" [value]="tms.orderitem_quantity" maxlength="2">  </ion-input>
</code>```

Now I need to change the value through increment and decrement function.

Note: value get from rest api in loop.

答:
```<code><ion-input name="inpval"  type="tel" id="idvalue"  class="inputvalue" [value]="tms.orderitem_quantity" maxlength="2">  </ion-input>
</code>```

Use ng-model to bind the value whenever you get from api after that with functions modify it

```<code><ion-input [(ngModel)]="inpval">  </ion-input>

after fetching data from api
this.inpval=xyz;

inc(){
//business logic
this.inpval=x;
}
dec(){
//business logic
this.inpval=x;
}

</code>```

Body:
I'm getting the value from the rest-api in input field.

<ion-input name="inpval"  type="tel" id="idvalue"  class="inputvalue" [value]="tms.orderitem_quantity" maxlength="2">  </ion-input>

Now I need to change the value through increment and decrement function.

Note: value get from rest api in loop.

Body:
<ion-input name="inpval"  type="tel" id="idvalue"  class="inputvalue" [value]="tms.orderitem_quantity" maxlength="2">  </ion-input>

Use ng-model to bind the value whenever you get from api after that with functions modify it

<ion-input [(ngModel)]="inpval">  </ion-input>

after fetching data from api
this.inpval=xyz;

inc(){
//business logic
this.inpval=x;
}
dec(){
//business logic
this.inpval=x;
}


问:
How to check which RecyclerView has been clicked
I have a view with two RecyclerViews. They have different ArrayLists, but the same kind of adapters. In the OnClick method in my activity, I want to get which of the Recyclers has been clicked, and then get the item selected.

I tried using view instanceof RecylcerView but that didn't do the trick.

答:
I finally managed to figure this out. It was more simple than most of the answers, as it's all solved in the activity onClick method:

```<code>public void onClick(View v){
    ViewParent parent = v.getParent();
        switch (((RecyclerView) parent).getId()) {
            case R.id.recycler_first:
            // Code
            break;
            case R.id.recycler_second:
            // Code
            break;
        }
}
</code>```

Body:
I finally managed to figure this out. It was more simple than most of the answers, as it's all solved in the activity onClick method:

public void onClick(View v){
    ViewParent parent = v.getParent();
        switch (((RecyclerView) parent).getId()) {
            case R.id.recycler_first:
            // Code
            break;
            case R.id.recycler_second:
            // Code
            break;
        }
}


问:
Hikvision python OpenCV
```<code>import numpy as np
import cv2
from hikvisionapi import Client

cap = cv2.VideoCapture()
#cap.open("rtsp://admin:DocoutBolivia@192.168.1.64:554/h264/ch0/sub")
cap.open("rtsp://admin:DocoutBolivia@192.168.1.64:554/Streaming/Channels/102/")
#cam = Client('http://192.168.1.64', 'admin', 'DocoutBolivia')

#rtsp://admin:password@192.168.1.64/h264/ch1/sub/

#response = cam.System.deviceInfo(method='get')
ret, frame = cap.read()
cv2.imwrite("holo.jpg", frame)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here

    # Display the resulting frame
    cv2.imshow('frame',frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

I have this code and it's connecting and showing well but it really slow there's another way for doing this? and have a bit less of delay? I want to make face recognition with my HikVision IP camera

答:
Trying to load the steam directly with Python will not get you anywhere.

The only way to get extremely low lantency is to make use of the .dll or .so files from the SDK provided by HikVision, and use ctypes to call the internal functions.

Below is a simple example I made before to access the NET_DVR_PTZControl_Other. It is a lot of work if you want to develop your own application with their SDK. I'd suggest you to request a sample python application from your vendor.

For example,

```<code>import os, ctypes
import cv2

def add_dll(path, dll_list):
    files = os.listdir(path)
    for file in files:
        if not os.path.isdir(path + file):
            if file.endswith(".dll"):
                dll_list.append(path + file)
        else:
            add_dll(path + file + "/", dll_list)

def callCpp(func_name, *args):
    for so_lib in so_list:
        try:
            lib = ctypes.cdll.LoadLibrary(so_lib)
            try:
                value = eval("lib.%s" % func_name)(*args)
                print("Success：" + str(value))
                return value
            except:
                continue
        except:
            print("Fail：" + so_lib)
            continue
    return False

def NET_DVR_PTZControl_Other(lUserID, lChannel, dwPTZCommand, dwStop):
    res = callCpp("NET_DVR_PTZControl_Other", lUserID, lChannel, dwPTZCommand, dwStop)
    if res:
        print("Control Success")
    else:
        print("Control Fail: " + str(callCpp("NET_DVR_GetLastError")))
</code>```

Get Steam Example

```<code>class NET_DVR_JPEGPARA(ctypes.Structure):
    _fields_ = [
        ("wPicSize", ctypes.c_ushort), # WORD
        ("wPicQuality", ctypes.c_ushort)] # WORD

def NET_DVR_CaptureJPEGPicture():
    sJpegPicFileName = bytes("pytest.jpg", "ascii")
    lpJpegPara = NET_DVR_JPEGPARA()
    lpJpegPara.wPicSize = 2
    lpJpegPara.wPicQuality = 1
    res = callCpp("NET_DVR_CaptureJPEGPicture", lUserID, lChannel, ctypes.byref(lpJpegPara), sJpegPicFileName)
    if res == False:
        error_info = callCpp("NET_DVR_GetLastError")
        print("Success：" + str(error_info))
    else:
        print("Grab stream fail")
</code>```

Title: Hikvision python OpenCV

Body:
import numpy as np
import cv2
from hikvisionapi import Client

cap = cv2.VideoCapture()
#cap.open("rtsp://admin:DocoutBolivia@192.168.1.64:554/h264/ch0/sub")
cap.open("rtsp://admin:DocoutBolivia@192.168.1.64:554/Streaming/Channels/102/")
#cam = Client('http://192.168.1.64', 'admin', 'DocoutBolivia')

#rtsp://admin:password@192.168.1.64/h264/ch1/sub/

#response = cam.System.deviceInfo(method='get')
ret, frame = cap.read()
cv2.imwrite("holo.jpg", frame)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here

    # Display the resulting frame
    cv2.imshow('frame',frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

I have this code and it's connecting and showing well but it really slow there's another way for doing this? and have a bit less of delay? I want to make face recognition with my HikVision IP camera

Body:
Trying to load the steam directly with Python will not get you anywhere.

The only way to get extremely low lantency is to make use of the .dll or .so files from the SDK provided by HikVision, and use ctypes to call the internal functions.

Below is a simple example I made before to access the NET_DVR_PTZControl_Other. It is a lot of work if you want to develop your own application with their SDK. I'd suggest you to request a sample python application from your vendor.

For example,

import os, ctypes
import cv2

def add_dll(path, dll_list):
    files = os.listdir(path)
    for file in files:
        if not os.path.isdir(path + file):
            if file.endswith(".dll"):
                dll_list.append(path + file)
        else:
            add_dll(path + file + "/", dll_list)

def callCpp(func_name, *args):
    for so_lib in so_list:
        try:
            lib = ctypes.cdll.LoadLibrary(so_lib)
            try:
                value = eval("lib.%s" % func_name)(*args)
                print("Success：" + str(value))
                return value
            except:
                continue
        except:
            print("Fail：" + so_lib)
            continue
    return False

def NET_DVR_PTZControl_Other(lUserID, lChannel, dwPTZCommand, dwStop):
    res = callCpp("NET_DVR_PTZControl_Other", lUserID, lChannel, dwPTZCommand, dwStop)
    if res:
        print("Control Success")
    else:
        print("Control Fail: " + str(callCpp("NET_DVR_GetLastError")))

Get Steam Example

class NET_DVR_JPEGPARA(ctypes.Structure):
    _fields_ = [
        ("wPicSize", ctypes.c_ushort), # WORD
        ("wPicQuality", ctypes.c_ushort)] # WORD

def NET_DVR_CaptureJPEGPicture():
    sJpegPicFileName = bytes("pytest.jpg", "ascii")
    lpJpegPara = NET_DVR_JPEGPARA()
    lpJpegPara.wPicSize = 2
    lpJpegPara.wPicQuality = 1
    res = callCpp("NET_DVR_CaptureJPEGPicture", lUserID, lChannel, ctypes.byref(lpJpegPara), sJpegPicFileName)
    if res == False:
        error_info = callCpp("NET_DVR_GetLastError")
        print("Success：" + str(error_info))
    else:
        print("Grab stream fail")


问:
Uncaught TypeError: Cannot set property 'value' of null after the page loads
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

```<code>var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '<tr><td  align="right"><label for="P'+app_page_id+'_VALUE_'+key+'">';
            textArea += '<span class="optional">Name '+languages[key][0]+': </span></label></td>';
            textArea += '<td  align="left" valign="middle">';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '</td></tr>';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});
</code>```

答:
Have you checked the generated HTML or is it impossible to provide such example?

Also I've noticed that you use var way more than you should for your variables. Have a quick read about when to use what here or here.

Body:
I know this has been asked so many times, but i couldn't find the answer for my scenerio. Below is my code. I'm getting this error in the last line inside findPattern function. But i have that ID created inside createMyArea as textArea += 'id="P'+app_page_id+'_VALUE'+key+'". But why this is not finding the ID? Please let me know what i'm doing wrong here. I'm loading this after the page loads

var app_page_id         = 40;
var app_pattern_page_id     = 32;
var app_id;
var checksum;
var lang;

$(document).ready(function() {
    app_id = $("#pFlowId").val();
    checksum = $("#pInstance").val();

    createMyFlow();

    function createMyFlow(){
        var result = new htmldb_Get(null, $v('pFlowId'), 'APPLICATION_PROCESS='+getAllLanguagesProc,  $v('pFlowStepId'));
        lang = jQuery.parseJSON(result.get()).lang;
        createMyArea();
        result = loadDataFromMyOra();
        if(result !== null)
            findPattern(result);
    }

    function createMyArea(){
        var textArea;
        for ( var key in lang){
            textArea = '
';
            textArea += 'Name '+languages[key][0]+': 	';
            textArea += '';
            textArea += '<input type="hidden" name="p_arg_names" />';
            textArea += '<fieldset id="P'+app_page_id+'_VALUE_fieldset_'+key+'" class="textarea" tabindex="-1">';
            textArea += '<input name="p_t04" type="text" maxlength="50" size="32" value=""';
            textArea += 'id="P'+app_page_id+'_VALUE'+key+'" required="" class="text_field"></fieldset>'
            textArea += '
';
        $('.formlayout').append(textArea);
        }
    }

    function findPattern(patterns)
    {
        var item = "";
        for ( var key in patterns){
            item = patterns[key]+"";
            item = item.replace(/,/g,",");
            item = item.replace(/“/g,'"')
            document.getElementById("P"+app_page_id+"_VALUE"+key).value = item;   //error here
        }
    }
});


问:
Query with optional arguments using PonyORM
I'm building an API for a library of teambuilding games. The games have defined properties like type, size and length that I'm storing as many-to-many relationships. The model looks like this:

```<code>class Game(db.Entity):
    game_type = Set('Type')
    game_length = Set('Length')
    group_size = Set('GroupSize')
    ...

class Type(db.Entity):  # similar for Length, GroupSize
    game = Set(Game)
    short = Required(str)
    full = Required(str)
</code>```

They are populated with different types/lengths/size values and then assigned to the different games. This works fine.

I had a hard time figuring out how to let users of the database query for e.g. two of these with the third not given. For example, I want all games with type=race AND size=medium but length=None.

I had built this before in SQL with subqueries and empty strings. This was my first working try with PonyORM:

```<code>def get_all_games(**kwargs):
    game_type = kwargs.get('game_type', None)
    group_size = kwargs.get('group_size', None)
    game_length = kwargs.get('game_length', None)

    query = select((g, gt, gs, gl) for g in Game
                                     for gt in g.game_type
                                       for gs in g.group_size
                                         for gl in g.game_length)

    if game_type:
        query = query.filter(lambda g, gt, gs, gl: gt.short == game_type)
    if group_size:
        query = query.filter(lambda g, gt, gs, gl: gs.short == group_size)
    if game_length:
        query = query.filter(lambda g, gt, gs, gl: gl.short == game_length)

    query = select(g for (g, gt, gs, gl) in query)

    result = []

    for g in query:
        this_game = get_game(g)
        result.append(this_game)

    return result
</code>```

It seems overly complicated to me. Is there a way to do this without tuples packing and unpacking? Maybe with using the variables right away in the query without the if statements?

答:
You can use exists or in in filter. Also you can use attribute lifting to simplify complex joins:

query = Game.select()

if game_length:
    # example with exists
    query = query.filter(lambda g: exists(
        gl for gl in g.game_length
        if gl.min <= game_length and gl.max >= game_length))

if group_size:
    # example with in
    query = query.filter(lambda g: group_size in (
        gs.value for gs in g.group_sizes))

if game_type:
    # example with attribute lifting
    query = query.filter(lambda g: game_type in g.game_types.short)
```

Body:
I'm building an API for a library of teambuilding games. The games have defined properties like type, size and length that I'm storing as many-to-many relationships. The model looks like this:

class Game(db.Entity):
    game_type = Set('Type')
    game_length = Set('Length')
    group_size = Set('GroupSize')
    ...

class Type(db.Entity):  # similar for Length, GroupSize
    game = Set(Game)
    short = Required(str)
    full = Required(str)

They are populated with different types/lengths/size values and then assigned to the different games. This works fine.

I had a hard time figuring out how to let users of the database query for e.g. two of these with the third not given. For example, I want all games with type=race AND size=medium but length=None.

I had built this before in SQL with subqueries and empty strings. This was my first working try with PonyORM:

def get_all_games(**kwargs):
    game_type = kwargs.get('game_type', None)
    group_size = kwargs.get('group_size', None)
    game_length = kwargs.get('game_length', None)

    query = select((g, gt, gs, gl) for g in Game
                                     for gt in g.game_type
                                       for gs in g.group_size
                                         for gl in g.game_length)

    if game_type:
        query = query.filter(lambda g, gt, gs, gl: gt.short == game_type)
    if group_size:
        query = query.filter(lambda g, gt, gs, gl: gs.short == group_size)
    if game_length:
        query = query.filter(lambda g, gt, gs, gl: gl.short == game_length)

    query = select(g for (g, gt, gs, gl) in query)

    result = []

    for g in query:
        this_game = get_game(g)
        result.append(this_game)

    return result

It seems overly complicated to me. Is there a way to do this without tuples packing and unpacking? Maybe with using the variables right away in the query without the if statements?


问:
How to select only certain tag and text using xpath?
For example, html block:

```<code><p><b>text1</b> (<span><a href="#1">asdf</a>text2</span>)</p>
</code>```

I need to select all tags "a" and all the rest must be the plain text just like we see in browser:

```<code>result = ["text1", " (", <tag_a>, "text2", ")"]
</code>```

or something like that.

Tried:

```<code>hxs.select('.//a|text()')
</code>```

in this case it finds all tags "a" but text is returned only from direct children.

At the same time:

```<code>hxs.select('.//text()|a')
</code>```

gets all texts, but tags "a" only from direct children.

UPDATE

```<code>    elements = []
    for i in hxs.select('.//node()'):
        try:
            tag_name = i.select('name()').extract()[0]
        except TypeError:
            tag_name = '_text'

        if tag_name == 'a':
            elements.append(i)
        elif tag_name == '_text':
            elements.append(i.extract())
</code>```

is there a better way?

答: It looks to me as if you are stepping beyond XPath territory. XPath is good at selecting things from the input but not at constructing output. It was designed, of course, for use with XSLT where XSLT instructions handle the output side. I'm not sure what the Python equivalent would be.</p>

Body:
For example, html block:

text1 (asdftext2)

I need to select all tags "a" and all the rest must be the plain text just like we see in browser:

result = ["text1", " (", <tag_a>, "text2", ")"]

or something like that.

Tried:

hxs.select('.//a|text()')

in this case it finds all tags "a" but text is returned only from direct children.

At the same time:

hxs.select('.//text()|a')

gets all texts, but tags "a" only from direct children.

UPDATE

    elements = []
    for i in hxs.select('.//node()'):
        try:
            tag_name = i.select('name()').extract()[0]
        except TypeError:
            tag_name = '_text'

        if tag_name == 'a':
            elements.append(i)
        elif tag_name == '_text':
            elements.append(i.extract())

is there a better way?


问:
DBeaver will not allow me to join tables or run window functions
I'm using DBeaver PostgreSQL and I'm trying to join two CSV files but I get an error stating, "SQL Error: Syntax error: JOIN not supported". In addition, I am unable to run window functions.

SQL Error: Syntax error: JOIN not support

SQL Window Function Error:

答:
DBeaver's CSV driver doesn't support joins. You should use 3rd party jdbc driver for this.

Try this one

UPDATE:

The above driver doesn't work.
You should use CData driver, it has a trial version (download).

Here is installation steps.
This one definitely supports join, as it specified here.


问:
c++ Question with displaying text between two array variables
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

```<code>#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}
</code>```

I'm not sure if that's the best way to do it, any tips would be appreciated.

答:
Firstly i++ and ++i are different.

i++ increments after returning the value and

++i increments before returning the value of the result.

It would be more readable if you incremented your i in the for loop by two and then not have a side effect when asking for the array value. And of course you need to check if i is valid at this point

```<code>for(int i=0; i < players-1; i += 2)
{
    // check if valid.
    // with odd numbers of players, the last remaining player will be dropped.
    cout << pNames[i]<<" vs " << pNames[i+1]; // no side effect.
                                                  // In a for loop
                                                  // all increments should happen in
                                                  // the loop header.
}
</code>```

Body:
I always seem to have this problem when I want to display two variables of an array in one iteration of a loop, I'm wondering if there is a nicer way of displaying the array.

The code works if I change ++i to i+1 but I'm wondering why that happens, and I'm wondering if there's a smarter way to do what I want. The error says unsequenced modification and access to 'i' [-Wunsequenced]

#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    int players = 0,rounds=0;
    bool winnerFound=false;
    cout << "Welcome to my tournament match maker\n";
    cout << "Enter the number of participants in the tournament: ";
    cin >> players;
    rounds=players/2;
    string *pNames = new string[players]; //dynamically allocate
    for (int i = 0;i < players;i++)
    {
        cout << "Enter the name of player " << i + 1<<":";
        cin >> pNames[i];
    }
        random_shuffle(&pNames[0],&pNames[players]);
        for(int i=0;i<rounds;i++)
        {
           cout<<pNames[i]<<" vs "<<pNames[++i]; //
        }
        return 0;
}

I'm not sure if that's the best way to do it, any tips would be appreciated.

Body:
Firstly i++ and ++i are different.

i++ increments after returning the value and

++i increments before returning the value of the result.

It would be more readable if you incremented your i in the for loop by two and then not have a side effect when asking for the array value. And of course you need to check if i is valid at this point

for(int i=0; i < players-1; i += 2)
{
    // check if valid.
    // with odd numbers of players, the last remaining player will be dropped.
    cout << pNames[i]<<" vs " << pNames[i+1]; // no side effect.
                                                  // In a for loop
                                                  // all increments should happen in
                                                  // the loop header.
}


问:
authentification provider linux like ActiveDirectory
I'm looking for some analog of ActiveDirectory for Linux operating systems.
Is there any one?</p>

答: Search for "LDAP" and "Kerberos".</p>

Body: Search for "LDAP" and "Kerberos".


问:
Padding dublicate in scrolling div, works in edge but not in chrome
I use padding-bottom in my project to get an aspect ratio, but the padding-bottom duplicate itself inside the overflow works in edge, but not in chrome.
What can I do to fix the problem and so it works in chrome to? :)

Link to codepen: https://codepen.io/mullermeck/pen/byKeWX

 .scroll {
    width: 50%;
    height: 0;
    padding-bottom: 300px;
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scroll">
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
  <div class="test1"></div>
</div></code>```

I have done research but haven't found any answers to it...
this is also my first post on here so it may be wrong

答:
padding bottom is not proper solution for it.. maybe below css may help you</p>

```<code>.scroll {
    width: 50%;
    height:300px;
    background-color: green;
    overflow: auto;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}
</code>```

Body:
I use padding-bottom in my project to get an aspect ratio, but the padding-bottom duplicate itself inside the overflow works in edge, but not in chrome.
What can I do to fix the problem and so it works in chrome to? :)

Link to codepen: https://codepen.io/mullermeck/pen/byKeWX

 .scroll {
    width: 50%;
    height: 0;
    padding-bottom: 300px;
    background-color: green;
    overflow-y: scroll;
    overflow-x: hidden;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}

I have done research but haven't found any answers to it...
this is also my first post on here so it may be wrong

Body:
padding bottom is not proper solution for it.. maybe below css may help you

.scroll {
    width: 50%;
    height:300px;
    background-color: green;
    overflow: auto;
    white-space: nowrap;
}
.test1{
    height: 0;
    width: 31.333%;
    padding-bottom: 31.333%;
    top: 0;
    background-color: deeppink;
    margin: 1% 1% 1% 1%;
    float: left;
    object-fit: cover;
}


问:
How to get the custom post type id
I have a product page which is a custom post type, now i want the category id of that specific page and place it in the post loop. And create a slick slider with it.

this is what i came up with.

single-product page

```<code><section class="product">
    <div class="productslider">
        <?php
        global $post;
        $Taxonomy = get_object_taxonomies('producten');

        if (count($Taxonomy) > 0) {
            foreach ($Taxonomy as $tax) {
                $args = array(
                    'taxonomy' => $tax,
                );

                $cats = get_categories($args);

                $cats = $cats[0]->term_id;
            }
        }

        $args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cats);

        $posts = get_posts($args);
        if ($posts) :
            foreach ($posts as $post) :
                setup_postdata($post); ?>
                <div class="productslider__slide">
                    <?php echo get_the_post_thumbnail(); ?>
                    <p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
                </div>

            <?php endforeach;
        wp_reset_postdata();
    endif; ?>
    </div>
</section>
</code>```

slick

```<code>$('.productslider').slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 2000,
    arrows: false,
    dots: true,
    centerMode: true,
});
</code>```

is this a good solution?
it seems like i am getting the same ids on every page

答:
it shows you the same ids, as you are getting the same Id's from the loop,

here is your code

$cats = $cats[0]->term_id;

above line only gets the first ID from the loop, and you are using this category id on the get_posts() that's why you will get the same id's every time.

try modifying this code:

```<code>$cat_array   = array();
$cats        = get_categories($args);
$cat_array[] = $cats->term_id;

$args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cat_array);
</code>```

Hope it will help you. :)

Title: How to get the custom post type id

Body:
I have a product page which is a custom post type, now i want the category id of that specific page and place it in the post loop. And create a slick slider with it.

this is what i came up with.

single-product page

        <?php
        global $post;
        $Taxonomy = get_object_taxonomies('producten');

        if (count($Taxonomy) > 0) {
            foreach ($Taxonomy as $tax) {
                $args = array(
                    'taxonomy' => $tax,
                );

                $cats = get_categories($args);

                $cats = $cats[0]->term_id;
            }
        }

        $args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cats);

        $posts = get_posts($args);
        if ($posts) :
            foreach ($posts as $post) :
                setup_postdata($post); ?>

                    <?php echo get_the_post_thumbnail(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

            <?php endforeach;
        wp_reset_postdata();
    endif; ?>

slick

$('.productslider').slick({
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 2000,
    arrows: false,
    dots: true,
    centerMode: true,
});

is this a good solution?
it seems like i am getting the same ids on every page

Body:
it shows you the same ids, as you are getting the same Id's from the loop,

here is your code

$cats = $cats[0]->term_id;

above line only gets the first ID from the loop, and you are using this category id on the get_posts() that's why you will get the same id's every time.

try modifying this code:

$cat_array   = array();
$cats        = get_categories($args);
$cat_array[] = $cats->term_id;

$args = array('posts_per_page' => 5, 'post_type' => 'producten', 'category' =>  $cat_array);

Hope it will help you. :)


问:
How to properly add an object to a list when the list is a custom class object?
I get a null reference exception when I try to add a region to the list and have no idea what I'm doing wrong. I simply can't figure it and I've done this a million times.</p>

```<code>public List<Region> regions;

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}
</code>```

答:
You just did not instanciate your list of Region (regions), so it is null. Look at the new List<Region>() part :

```<code>public List<Region> regions = new List<Region>();

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}
</code>```

Body:
I get a null reference exception when I try to add a region to the list and have no idea what I'm doing wrong. I simply can't figure it and I've done this a million times.

public List<Region> regions;

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}

Body:
You just did not instanciate your list of Region (regions), so it is null. Look at the new List<Region>() part :

public List<Region> regions = new List<Region>();

public class Region
{
    public int x_size;
    public int y_size;

    public enum terrain
    {
        desert,
        lowlands,
        crater,
        city
    };

    public terrain ground;
}

private void NewRegion()
{
    Region thisRegion = new Region();
    thisRegion.x_size = Random.Range(25, 50);
    thisRegion.y_size = Random.Range(25, 50);
    thisRegion.ground = Region.terrain.desert;
    regions.Add(thisRegion);
}


问:
Keep background color after selection when in focus Microsoft Edge
I have a select form in Bootstrap 4 with dark background, when I select an option I want the background after selection to stay dark. My example works in Chrome and Firefox. But in IE and Edge the background stays white while in focus. Check my jsfiddle, any ideas?

```<code>.form-control:focus {
  background-color: #121212;
  border-color: #121212;
  outline: 0;
  box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
}
</code>```

https://jsfiddle.net/cd1eyqvr/3/

答:
Keep the .form-control:focus part and add this in your css:

```<code>.form-control:focus::-ms-value {
        background-color: #242424 !important;
        border-color: #121212 !important;
        color: #ffffff !important;
        outline: 0 !important;
        box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
    }
</code>```

This part will work in IE11 and Edge.

You can refer to the demo I made: https://jsfiddle.net/yuzhou0602/ofwvuzyr/4/

Body:
I have a select form in Bootstrap 4 with dark background, when I select an option I want the background after selection to stay dark. My example works in Chrome and Firefox. But in IE and Edge the background stays white while in focus. Check my jsfiddle, any ideas?

.form-control:focus {
  background-color: #121212;
  border-color: #121212;
  outline: 0;
  box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
}

https://jsfiddle.net/cd1eyqvr/3/

Body:
Keep the .form-control:focus part and add this in your css:

.form-control:focus::-ms-value {
        background-color: #242424 !important;
        border-color: #121212 !important;
        color: #ffffff !important;
        outline: 0 !important;
        box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
    }

This part will work in IE11 and Edge.

You can refer to the demo I made: https://jsfiddle.net/yuzhou0602/ofwvuzyr/4/


问:
Use Android style Attributes in own Layout
I want to use this style, which is an Android Build in Style Attribute, but it won't compile. I' am missing some kind of Import?

```<code>?android:attr/listItemFirstLineStyle

<TextView
      android:id="@+id/text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1" android:layout_gravity="left|center_vertical" style="?android:attr/listItemFirstLineStyle" android:layout_marginLeft="10dip"/>`
</code>```

thx

答:
You can't access all build in styles in your own projects. When you type so far in Eclipse

```<code>style="@android:style/"
</code>```

and hit ctrl + enter, intellisense should give you an overview of what you can use. There are underscores in the style names, replace them by '.'...

Body:
I want to use this style, which is an Android Build in Style Attribute, but it won't compile. I' am missing some kind of Import?

?android:attr/listItemFirstLineStyle

<TextView
      android:id="@+id/text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1" android:layout_gravity="left|center_vertical" style="?android:attr/listItemFirstLineStyle" android:layout_marginLeft="10dip"/>`

thx

Body:
You can't access all build in styles in your own projects. When you type so far in Eclipse

style="@android:style/"

and hit ctrl + enter, intellisense should give you an overview of what you can use. There are underscores in the style names, replace them by '.'...