问:
Siamese neural network with two pre-trained ResNet 50 - strange behavior while testing model
I built siamese neural network, using Keras lib for it.
My model has two inputs with shape (64,64,3), two pre-trained ResNet-50.
Loss function is binary cross entropy.

The model is based on this paper a link

During train I have very good trait/val accuracy, about 0.99/0.98, and low loss 0.01/0.05.

But when I test my saved model, I get bad results. The model can't recognize even two the same pictures.

Also I noticed strange behavior:
the greater the number of epochs the result is worse.
For example, comparing two identical images, trained model with 10 epoch  gives prediction:
"8.jpg": 0.5180479884147644
but the same model trained with 100 epoch gives
"8.jpg": 5.579867080537926E-13
However for 100 epoch I have better train results.

I've tried different model for CNN: ResNet18, different input shapes, like (224,224,3) or (128,128,3).

Also I've triad use not pre-train model, only ResNet50/ResNet18 without pre-trained weights. But I have the same bad results while testing real model.

My code is

```<code>def create_base_model(image_shape, dropout_rate, suffix=''):
    I1 = Input(shape=image_shape)
    model = ResNet50(include_top=False, weights='imagenet', input_tensor=I1, pooling=None)
    model.layers.pop()
    model.outputs = [model.layers[-1].output]
    model.layers[-1].outbound_nodes = []

    for layer in model.layers:
        layer.name = layer.name + str(suffix)
        layer.trainable = False

    flatten_name = 'flatten' + str(suffix)

    x = model.output
    x = Flatten(name=flatten_name)(x)
    x = Dense(1024, activation='relu')(x)
    x = Dropout(dropout_rate)(x)
    x = Dense(512, activation='relu')(x)
    x = Dropout(dropout_rate)(x)

    return x, model.input

def create_siamese_model(image_shape, dropout_rate):

    output_left, input_left = create_base_model(image_shape, dropout_rate)
    output_right, input_right = create_base_model(image_shape, dropout_rate, suffix="_2")

    L1_layer = Lambda(lambda tensors: tf.abs(tensors[0] - tensors[1]))
    L1_distance = L1_layer([output_left, output_right])
    L1_prediction = Dense(1, use_bias=True,
                          activation='sigmoid',
                          kernel_initializer=RandomNormal(mean=0.0, stddev=0.001),
                          name='weighted-average')(L1_distance)

    prediction = Dropout(0.2)(L1_prediction)

    siamese_model = Model(inputs=[input_left, input_right], outputs=prediction)

    return siamese_model

siamese_model = create_siamese_model(image_shape=(64, 64, 3),
                                         dropout_rate=0.2)

siamese_model.compile(loss='binary_crossentropy',
                      optimizer=Adam(lr=0.0001),
                      metrics=['binary_crossentropy', 'acc'])
siamese_model.fit_generator(train_gen,
                            steps_per_epoch=1000,
                            epochs=10,
                            verbose=1,
                            callbacks=[checkpoint, tensor_board_callback, lr_reducer, early_stopper, csv_logger],
                            validation_data=validation_data,
                            max_q_size=3)

siamese_model.save('siamese_model.h5')

# and the my prediction
siamese_net = load_model('siamese_model.h5', custom_objects={"tf": tf})

X_1 = [image, ] * len(markers)
batch = [markers, X_1]
result = siamese_net.predict_on_batch(batch)

# I've tried also to check identical images
markers = [image]
X_1 = [image, ] * len(markers)
batch = [markers, X_1]
result = siamese_net.predict_on_batch(batch)
</code>```

I have some doubts about my prediction method.
Could someone please help me to find what is wrong with predictions?

答:
What you are getting is expected. I'm not sure what you mean by

Also I noticed strange behavior: the greater the number of epochs the result is worse.

But the results you shown are valid and expected. Let's start with what the model is outputting. Your model output is (normalized)distance between the first and second inputs. If the inputs are similar, then the distance should be close to zero. As number of training step increases the model learns to identify the inputs, i.e if the inputs are similar the model learns to output values close to zero, and if the inputs are different the model learns to output values close to one. So,

... trained model with 10 epoch gives prediction: "8.jpg": 0.5180479884147644 but the same model trained with 100 epoch gives "8.jpg": 5.579867080537926E-13 However for 100 epoch I have better train results.

, confirms that the model has learned that the two inputs are similar and outputs 5.579867080537926E-13 ~ 0(approximately close to 0).

Although the model is performing well, there is one issue I've observed in the model definition:- The output layer is dropout layer. Dropout is not valid output layer. What you are doing by this setting is, randomly with probability 0.2 you are setting the output of the model to be zero.

Let's assume the target variable has 1(the two inputs are different), and model has learnt to identify the images correctly and outputs value close to 1 before the dropout layer. Let's further assume that the dropout layer has decided to set the output to be zero. So the model output will be zero. Even though the layers before dropout layer have performed well, because of the dropout layer, they will be penalized. If this is not what you are looking then remove the last dropout layer.

L1_prediction = Dense(1, use_bias=True,
                    activation='sigmoid',
                    kernel_initializer=RandomNormal(mean=0.0, stddev=0.001),
                    name='weighted-average')(L1_distance)

siamese_model = Model(inputs=[input_left, input_right], outputs=L1_prediction)
```

However, sometimes this behavior is needed if one want to add noise to the model. This has the same effect with randomly altering the target variable when the value is 1.

Body:
I built siamese neural network, using Keras lib for it.
My model has two inputs with shape (64,64,3), two pre-trained ResNet-50.
Loss function is binary cross entropy.

The model is based on this paper a link

During train I have very good trait/val accuracy, about 0.99/0.98, and low loss 0.01/0.05.

But when I test my saved model, I get bad results. The model can't recognize even two the same pictures.

Also I noticed strange behavior:
the greater the number of epochs the result is worse.
For example, comparing two identical images, trained model with 10 epoch  gives prediction:
"8.jpg": 0.5180479884147644
but the same model trained with 100 epoch gives
"8.jpg": 5.579867080537926E-13
However for 100 epoch I have better train results.

I've tried different model for CNN: ResNet18, different input shapes, like (224,224,3) or (128,128,3).

Also I've triad use not pre-train model, only ResNet50/ResNet18 without pre-trained weights. But I have the same bad results while testing real model.

My code is

def create_base_model(image_shape, dropout_rate, suffix=''):
    I1 = Input(shape=image_shape)
    model = ResNet50(include_top=False, weights='imagenet', input_tensor=I1, pooling=None)
    model.layers.pop()
    model.outputs = [model.layers[-1].output]
    model.layers[-1].outbound_nodes = []

    for layer in model.layers:
        layer.name = layer.name + str(suffix)
        layer.trainable = False

    flatten_name = 'flatten' + str(suffix)

    x = model.output
    x = Flatten(name=flatten_name)(x)
    x = Dense(1024, activation='relu')(x)
    x = Dropout(dropout_rate)(x)
    x = Dense(512, activation='relu')(x)
    x = Dropout(dropout_rate)(x)

    return x, model.input

def create_siamese_model(image_shape, dropout_rate):

    output_left, input_left = create_base_model(image_shape, dropout_rate)
    output_right, input_right = create_base_model(image_shape, dropout_rate, suffix="_2")

    L1_layer = Lambda(lambda tensors: tf.abs(tensors[0] - tensors[1]))
    L1_distance = L1_layer([output_left, output_right])
    L1_prediction = Dense(1, use_bias=True,
                          activation='sigmoid',
                          kernel_initializer=RandomNormal(mean=0.0, stddev=0.001),
                          name='weighted-average')(L1_distance)

    prediction = Dropout(0.2)(L1_prediction)

    siamese_model = Model(inputs=[input_left, input_right], outputs=prediction)

    return siamese_model

siamese_model = create_siamese_model(image_shape=(64, 64, 3),
                                         dropout_rate=0.2)

siamese_model.compile(loss='binary_crossentropy',
                      optimizer=Adam(lr=0.0001),
                      metrics=['binary_crossentropy', 'acc'])
siamese_model.fit_generator(train_gen,
                            steps_per_epoch=1000,
                            epochs=10,
                            verbose=1,
                            callbacks=[checkpoint, tensor_board_callback, lr_reducer, early_stopper, csv_logger],
                            validation_data=validation_data,
                            max_q_size=3)

siamese_model.save('siamese_model.h5')

# and the my prediction
siamese_net = load_model('siamese_model.h5', custom_objects={"tf": tf})

X_1 = [image, ] * len(markers)
batch = [markers, X_1]
result = siamese_net.predict_on_batch(batch)

# I've tried also to check identical images
markers = [image]
X_1 = [image, ] * len(markers)
batch = [markers, X_1]
result = siamese_net.predict_on_batch(batch)

I have some doubts about my prediction method.
Could someone please help me to find what is wrong with predictions?

Body:
What you are getting is expected. I'm not sure what you mean by

Also I noticed strange behavior: the greater the number of epochs the result is worse.

But the results you shown are valid and expected. Let's start with what the model is outputting. Your model output is (normalized)distance between the first and second inputs. If the inputs are similar, then the distance should be close to zero. As number of training step increases the model learns to identify the inputs, i.e if the inputs are similar the model learns to output values close to zero, and if the inputs are different the model learns to output values close to one. So,

... trained model with 10 epoch gives prediction: "8.jpg": 0.5180479884147644 but the same model trained with 100 epoch gives "8.jpg": 5.579867080537926E-13 However for 100 epoch I have better train results.

, confirms that the model has learned that the two inputs are similar and outputs 5.579867080537926E-13 ~ 0(approximately close to 0).

Although the model is performing well, there is one issue I've observed in the model definition:- The output layer is dropout layer. Dropout is not valid output layer. What you are doing by this setting is, randomly with probability 0.2 you are setting the output of the model to be zero.

Let's assume the target variable has 1(the two inputs are different), and model has learnt to identify the images correctly and outputs value close to 1 before the dropout layer. Let's further assume that the dropout layer has decided to set the output to be zero. So the model output will be zero. Even though the layers before dropout layer have performed well, because of the dropout layer, they will be penalized. If this is not what you are looking then remove the last dropout layer.

L1_prediction = Dense(1, use_bias=True,
                    activation='sigmoid',
                    kernel_initializer=RandomNormal(mean=0.0, stddev=0.001),
                    name='weighted-average')(L1_distance)

siamese_model = Model(inputs=[input_left, input_right], outputs=L1_prediction)

However, sometimes this behavior is needed if one want to add noise to the model. This has the same effect with randomly altering the target variable when the value is 1.


来源: stackexchange

问:
How to retain a row value of other columns in Groupby?
I have a dataframe:

```<code>df = pd.DataFrame()
df['bird'] = ['shikra','shikra','eagle','eagle','eagle','crow','sparrow','sparrow']
df['bird2'] = [1,1,2,2,2,3,4,4]
df['n'] = ['a','b','c','d','e','f','g','h']
df['range'] = [1400,1600,np.nan,2800,3300,np.nan,800,600]

    bird    bird2   n   range
0   shikra  1   a   1400.0
1   shikra  1   b   1600.0
2   eagle   2   c   NaN
3   eagle   2   d   2800.0
4   eagle   2   e   3300.0
5   crow    3   f   NaN
6   sparrow 4   g   800.0
7   sparrow 4   h   600.0
</code>```

I want to find top 2 birds with max range from about data.

I used groupby operation as below:

```<code>df.groupby(['bird','bird2']).agg({'range':'max', 'n':'first'}).reset_index().sort_values('range', ascending=False).head(2)
</code>```

which gives output as:

```<code>    bird    bird2   range   n
1   eagle   2      3300.0   c
2   shikra  1      1600.0   a
</code>```

Only problem with above output is column n. As I have selected first in agg it's giving 1st value for corresponding groupby value but actually what I want is value of n which is related to maximum range.

How can I select the value from n column where range is max

Expected Output:

```<code>    bird    bird2   range   n
1   eagle   2      3300.0   e
2   shikra  1      1600.0   b
</code>```

答:
You can also directly use the max function:

```<code>df.groupby(['bird','bird2']).max().reset_index().sort_values('range', ascending=False).head(2)

    bird    bird2   n   range
1   eagle   2       e   3300.0
2   shikra  1       b   1600.0
</code>```

As jezreal mentions, max will also find the maximum string, f in your case. But when you sort it by range, it falls into place.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe:

df = pd.DataFrame()
df['bird'] = ['shikra','shikra','eagle','eagle','eagle','crow','sparrow','sparrow']
df['bird2'] = [1,1,2,2,2,3,4,4]
df['n'] = ['a','b','c','d','e','f','g','h']
df['range'] = [1400,1600,np.nan,2800,3300,np.nan,800,600]

    bird    bird2   n   range
0   shikra  1   a   1400.0
1   shikra  1   b   1600.0
2   eagle   2   c   NaN
3   eagle   2   d   2800.0
4   eagle   2   e   3300.0
5   crow    3   f   NaN
6   sparrow 4   g   800.0
7   sparrow 4   h   600.0

I want to find top 2 birds with max range from about data.

I used groupby operation as below:

df.groupby(['bird','bird2']).agg({'range':'max', 'n':'first'}).reset_index().sort_values('range', ascending=False).head(2)

which gives output as:

    bird    bird2   range   n
1   eagle   2      3300.0   c
2   shikra  1      1600.0   a

Only problem with above output is column n. As I have selected first in agg it's giving 1st value for corresponding groupby value but actually what I want is value of n which is related to maximum range.

How can I select the value from n column where range is max

Expected Output:

    bird    bird2   range   n
1   eagle   2      3300.0   e
2   shikra  1      1600.0   b

Body:
You can also directly use the max function:

df.groupby(['bird','bird2']).max().reset_index().sort_values('range', ascending=False).head(2)

    bird    bird2   n   range
1   eagle   2       e   3300.0
2   shikra  1       b   1600.0

As jezreal mentions, max will also find the maximum string, f in your case. But when you sort it by range, it falls into place.


问:
WordPress - Several Menulinks to same URL active
Im designing a big Dropdown-Menu with 2 Sub-Levels in the Divi WordPress Theme, where several menu-links are individual-links pointing to the same Page (the customer wants this). Now all of those links get an active class by default in WordPress once any link is clicked.
Is there an easy way around this without using jQuery?

I tried solving this using CSS, but I think Im missing something really basic in the WordPress settings.

答: Do you have a URL we can take a look at?</p>


问:
write firebase data when user is not connected to internet
I want to update Firebase database when user is not connected to internet. It is like you are in the app and you close the internet connection now you close the application. So I am using LifeCycleObserver to detect whether the app is in foreground or in background. I want to set user status offline when onStop called in my Application class. When the internet connection is ON its working perfectly.

I have tried OnDisconnect().setValue(-) but its not working. Can anyone help me to solve this problem?

```<code>userDatabase.child(AppConstants.USER_IS_ONLINE).onDisconnect().setValue(status,object :  DatabaseReference.CompletionListener{
            override fun onComplete(p0: DatabaseError?, p1: DatabaseReference) {
                Log.d("Success","YES")
            }

        })
</code>```

答:
I want to update firebase database when user is not connected to internet.

There is no way you can do this. Since there is no internet connection between user's device and Firebase servers, you cannot update anything. The internet connection is mandatory in order to reach Firebase back-end.

There are two ways the user can get disconnected from the Firebase database. For that, please see Frank van Puffelen's answer from the following post:

How to make user presence mechanism using Firebase?

Body:
I want to update Firebase database when user is not connected to internet. It is like you are in the app and you close the internet connection now you close the application. So I am using LifeCycleObserver to detect whether the app is in foreground or in background. I want to set user status offline when onStop called in my Application class. When the internet connection is ON its working perfectly.

I have tried OnDisconnect().setValue(-) but its not working. Can anyone help me to solve this problem?

userDatabase.child(AppConstants.USER_IS_ONLINE).onDisconnect().setValue(status,object :  DatabaseReference.CompletionListener{
            override fun onComplete(p0: DatabaseError?, p1: DatabaseReference) {
                Log.d("Success","YES")
            }

        })


问:
Multiprocessing.Queue with hugh data causes _wait_for_tstate_lock
An Exception is raised in threading._wait_for_tstate_lock when I transfere hugh data between a Process and a Thread via multiprocessing.Queue.

My minimal working example looks a bit complex first - sorry. I will explain. The original application loads a lot of (not so important) files into RAM. This is done in a separate process to save ressources. The main gui thread shouldn't freez.

The GUI start a separate Thread to prevent the gui event loop from freezing.

This separate Thread then starts one Process which should does the work.

a) This Thread instanciates a multiprocess.Queue (be aware that this is a multiprocessing and not threading!)

b) This is givin to the Process for sharing data from Process back to the Thread.

The Process does some work (3 steps) and .put() the result into the multiprocessing.Queue.

When the Process ends the Thread takes over again and collect the data from the Queue, store it to its own attribute MyThread.result.

The Thread tells the GUI main loop/thread to call a callback function if it has time for.

The callback function (MyWindow::callback_thread_finished()) get the results from MyWindow.thread.result.

The problem is if the data put to the Queue is to big something happen I don't understand - the MyThread never ends. I have to cancle the application via Strg+C.

I got some hints from the docs. But my problem is I did not fully understand the documentation. But I have the feeling that the key of my problems can be found there.
Please see the two red boxex in "Pipes and Queues" (Python 3.5 docs).
That is the full output

```<code>MyWindow::do_start()
Running MyThread...
Running MyProcess...
MyProcess stoppd.
^CProcess MyProcess-1:
Exception ignored in: <module 'threading' from '/usr/lib/python3.5/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 1288, in _shutdown
    t.join()
  File "/usr/lib/python3.5/threading.py", line 1054, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
Traceback (most recent call last):
  File "/usr/lib/python3.5/multiprocessing/process.py", line 252, in _bootstrap
    util._exit_function()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 314, in _exit_function
    _run_finalizers()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 254, in _run_finalizers
    finalizer()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 186, in __call__
    res = self._callback(*self._args, **self._kwargs)
  File "/usr/lib/python3.5/multiprocessing/queues.py", line 198, in _finalize_join
    thread.join()
  File "/usr/lib/python3.5/threading.py", line 1054, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
</code>```

This is the minimal working example

```<code>#!/usr/bin/env python3

import multiprocessing
import threading
import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib

class MyThread (threading.Thread):
    """This thread just starts the process."""
    def __init__(self, callback):
        threading.Thread.__init__(self)
        self._callback = callback

    def run(self):
        print('Running MyThread...')
        self.result = []

        queue = multiprocessing.Queue()
        process = MyProcess(queue)
        process.start()
        process.join()

        while not queue.empty():
            process_result = queue.get()
            self.result.append(process_result)
        print('MyThread stoppd.')
        GLib.idle_add(self._callback)

class MyProcess (multiprocessing.Process):
    def __init__(self, queue):
        multiprocessing.Process.__init__(self)
        self.queue = queue

    def run(self):
        print('Running MyProcess...')
        for i in range(3):
            self.queue.put((i, 'x'*102048))
        print('MyProcess stoppd.')

class MyWindow (Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect('destroy', Gtk.main_quit)
        GLib.timeout_add(2000, self.do_start)

    def do_start(self):
        print('MyWindow::do_start()')
        # The process need to be started from a separate thread
        # to prevent the main thread (which is the gui main loop)
        # from freezing while waiting for the process result.
        self.thread = MyThread(self.callback_thread_finished)
        self.thread.start()

    def callback_thread_finished(self):
        result = self.thread.result
        for r in result:
            print('{} {}...'.format(r[0], r[1][:10]))

if __name__ == '__main__':
    win = MyWindow()
    win.show_all()
    Gtk.main()
</code>```

Possible duplicate but quite different and IMO without an answer for my situation: Thread._wait_for_tstate_lock() never returns.

Workaround

Using a Manager by modifing line 22 to queue = multiprocessing.Manager().Queue() solve the problem. But I don't know why. My intention of this question is to understand the things behind and not only to make my code work. Even I don't really know what a Manager() is and if it has other (problem causing) implications.

答:
According to the second warning box in the documentation you are linking to you can get a deadlock when you join a process before processing all items in the queue.  So starting the process and immediately joining it and then processing the items in the queue is the wrong order of steps.  You have to start the process, then receive the items, and then only when all items are received you can call the join method.  Define some sentinel value to signal that the process is finished sending data through the queue. None for example if that can't be a regular value you expect from the process.

```<code>class MyThread(threading.Thread):
    """This thread just starts the process."""

    def __init__(self, callback):
        threading.Thread.__init__(self)
        self._callback = callback
        self.result = []

    def run(self):
        print('Running MyThread...')
        queue = multiprocessing.Queue()
        process = MyProcess(queue)
        process.start()
        while True:
            process_result = queue.get()
            if process_result is None:
                break
            self.result.append(process_result)
        process.join()
        print('MyThread stoppd.')
        GLib.idle_add(self._callback)

class MyProcess(multiprocessing.Process):

    def __init__(self, queue):
        multiprocessing.Process.__init__(self)
        self.queue = queue

    def run(self):
        print('Running MyProcess...')
        for i in range(3):
            self.queue.put((i, 'x' * 102048))
        self.queue.put(None)
        print('MyProcess stoppd.')
</code>```

Body:
An Exception is raised in threading._wait_for_tstate_lock when I transfere hugh data between a Process and a Thread via multiprocessing.Queue.

My minimal working example looks a bit complex first - sorry. I will explain. The original application loads a lot of (not so important) files into RAM. This is done in a separate process to save ressources. The main gui thread shouldn't freez.

The GUI start a separate Thread to prevent the gui event loop from freezing.

This separate Thread then starts one Process which should does the work.

a) This Thread instanciates a multiprocess.Queue (be aware that this is a multiprocessing and not threading!)

b) This is givin to the Process for sharing data from Process back to the Thread.

The Process does some work (3 steps) and .put() the result into the multiprocessing.Queue.

When the Process ends the Thread takes over again and collect the data from the Queue, store it to its own attribute MyThread.result.

The Thread tells the GUI main loop/thread to call a callback function if it has time for.

The callback function (MyWindow::callback_thread_finished()) get the results from MyWindow.thread.result.

The problem is if the data put to the Queue is to big something happen I don't understand - the MyThread never ends. I have to cancle the application via Strg+C.

I got some hints from the docs. But my problem is I did not fully understand the documentation. But I have the feeling that the key of my problems can be found there.
Please see the two red boxex in "Pipes and Queues" (Python 3.5 docs).
That is the full output

MyWindow::do_start()
Running MyThread...
Running MyProcess...
MyProcess stoppd.
^CProcess MyProcess-1:
Exception ignored in: <module 'threading' from '/usr/lib/python3.5/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 1288, in _shutdown
    t.join()
  File "/usr/lib/python3.5/threading.py", line 1054, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt
Traceback (most recent call last):
  File "/usr/lib/python3.5/multiprocessing/process.py", line 252, in _bootstrap
    util._exit_function()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 314, in _exit_function
    _run_finalizers()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 254, in _run_finalizers
    finalizer()
  File "/usr/lib/python3.5/multiprocessing/util.py", line 186, in __call__
    res = self._callback(*self._args, **self._kwargs)
  File "/usr/lib/python3.5/multiprocessing/queues.py", line 198, in _finalize_join
    thread.join()
  File "/usr/lib/python3.5/threading.py", line 1054, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt

This is the minimal working example

#!/usr/bin/env python3

import multiprocessing
import threading
import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib

class MyThread (threading.Thread):
    """This thread just starts the process."""
    def __init__(self, callback):
        threading.Thread.__init__(self)
        self._callback = callback

    def run(self):
        print('Running MyThread...')
        self.result = []

        queue = multiprocessing.Queue()
        process = MyProcess(queue)
        process.start()
        process.join()

        while not queue.empty():
            process_result = queue.get()
            self.result.append(process_result)
        print('MyThread stoppd.')
        GLib.idle_add(self._callback)

class MyProcess (multiprocessing.Process):
    def __init__(self, queue):
        multiprocessing.Process.__init__(self)
        self.queue = queue

    def run(self):
        print('Running MyProcess...')
        for i in range(3):
            self.queue.put((i, 'x'*102048))
        print('MyProcess stoppd.')

class MyWindow (Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.connect('destroy', Gtk.main_quit)
        GLib.timeout_add(2000, self.do_start)

    def do_start(self):
        print('MyWindow::do_start()')
        # The process need to be started from a separate thread
        # to prevent the main thread (which is the gui main loop)
        # from freezing while waiting for the process result.
        self.thread = MyThread(self.callback_thread_finished)
        self.thread.start()

    def callback_thread_finished(self):
        result = self.thread.result
        for r in result:
            print('{} {}...'.format(r[0], r[1][:10]))

if __name__ == '__main__':
    win = MyWindow()
    win.show_all()
    Gtk.main()

Possible duplicate but quite different and IMO without an answer for my situation: Thread._wait_for_tstate_lock() never returns.

Workaround

Using a Manager by modifing line 22 to queue = multiprocessing.Manager().Queue() solve the problem. But I don't know why. My intention of this question is to understand the things behind and not only to make my code work. Even I don't really know what a Manager() is and if it has other (problem causing) implications.

Body:
According to the second warning box in the documentation you are linking to you can get a deadlock when you join a process before processing all items in the queue.  So starting the process and immediately joining it and then processing the items in the queue is the wrong order of steps.  You have to start the process, then receive the items, and then only when all items are received you can call the join method.  Define some sentinel value to signal that the process is finished sending data through the queue. None for example if that can't be a regular value you expect from the process.

class MyThread(threading.Thread):
    """This thread just starts the process."""

    def __init__(self, callback):
        threading.Thread.__init__(self)
        self._callback = callback
        self.result = []

    def run(self):
        print('Running MyThread...')
        queue = multiprocessing.Queue()
        process = MyProcess(queue)
        process.start()
        while True:
            process_result = queue.get()
            if process_result is None:
                break
            self.result.append(process_result)
        process.join()
        print('MyThread stoppd.')
        GLib.idle_add(self._callback)

class MyProcess(multiprocessing.Process):

    def __init__(self, queue):
        multiprocessing.Process.__init__(self)
        self.queue = queue

    def run(self):
        print('Running MyProcess...')
        for i in range(3):
            self.queue.put((i, 'x' * 102048))
        self.queue.put(None)
        print('MyProcess stoppd.')


问:
Issue: Jsoup to parse string with < followed by word
I'm using Jsoup to parse the string which contains substring starts with < followed by a word to get the text but not getting text correctly

```<code>String input ="<p>testing with less than <string</p>";

String s = Jsoup.parse(input).text();
</code>```

After extracting attribute text "testing with less than" is the result instead of testing with less than <string

答:
```<code>String input = "<p>testing with less than <string</p>";
System.out.println(input);
</code>```

Output:

```<code><p>testing with less than <string</p>
</code>```

If we print the input we will get the entire string as shown.

```<code>String s1 = Jsoup.parse(input).text();
System.out.println(s1);// when we use method text()
</code>```

Output:

```<code>testing with less than
</code>```

If we use the jsoup text() method, we get the plain text without HTML tags.

But still, we are not getting the entire input String because of the char "<".

the reason is justified in the following ex.

```<code>String s2 = Jsoup.parse(input).html();
System.out.println(s2);// when we use method html()
</code>```

Output:

```<code> <html>
 <head></head>
 <body>
 <p>testing with less than
 <string></string> //the end tag is auto generated by the method
 </p>
 </body>
 </html>
</code>```

If we use the jsoup html() method, we get the entire formatted HTML code.

here we can clearly see that the word which is written after the char "<" in-between another HTML tag is automatically converted into an HTML tag.
(if we only write a start tag the end tag is automatically created whether it is valid or not)

this is the reason we are not getting entire input as shown in the first example

Body:
I'm using Jsoup to parse the string which contains substring starts with < followed by a word to get the text but not getting text correctly

String input ="
testing with less than <string
";

String s = Jsoup.parse(input).text();

After extracting attribute text "testing with less than" is the result instead of testing with less than <string

Body:
String input = "<p>testing with less than <string</p>";
System.out.println(input);

Output:

<p>testing with less than <string</p>

If we print the input we will get the entire string as shown.

String s1 = Jsoup.parse(input).text();
System.out.println(s1);// when we use method text()

Output:

testing with less than

If we use the jsoup text() method, we get the plain text without HTML tags.

But still, we are not getting the entire input String because of the char "<".

the reason is justified in the following ex.

String s2 = Jsoup.parse(input).html();
System.out.println(s2);// when we use method html()

Output:

 <html>
 <head></head>
 <body>
 <p>testing with less than
 <string></string> //the end tag is auto generated by the method
 </p>
 </body>
 </html>

If we use the jsoup html() method, we get the entire formatted HTML code.

here we can clearly see that the word which is written after the char "<" in-between another HTML tag is automatically converted into an HTML tag.
(if we only write a start tag the end tag is automatically created whether it is valid or not)

this is the reason we are not getting entire input as shown in the first example


问:
Proper formating of JSON using powershell
I have a following file in JSON format:

Before ConvertTo-JSON:

```<code>[
    {
        "Yura": {
            "Cashier": {
                "branch": "release/Retail-v4.0",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Apr 18 2018 07:45:05",
                "deployed_by": "anonymous",
                "host": "cashier2-retail4.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "Cashier",
                "publish_profile": "cashier2.retail.dev.pubxml"
            },
            "ContentManager": {
                "branch": "release/Retail-v3.31.1",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Jan 17 2018 11:59:24",
                "deployed_by": "anonymous",
                "host": "contentmanager2-retail3.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "ContentManager",
                "publish_profile": "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
            }
        }
    }
]
</code>```

after using this code for manipulation with data:

```<code>$json = Get-Content 'D:\script\test.json'  -encoding utf8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'
</code>```

I save JSON into another file:

```<code>$json | convertto-json | set-content "D:\script\test1.json" -encoding utf8
</code>```

Problem is, that after saving file, format become broken:

```<code>{
    "Yura":  {
                 "Cashier":  {
                                 "branch":  "release/Retail-v4.0",
                                 "configuration":  "RetailDemo Debug",
                                 "datetime_deployed":  "Apr 18 2018 07:45:05",
                                 "deployed_by":  "anonymous",
                                 "host":  "cashier2-retail4.testing.aws.com",
                                 "job":  "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                                 "lineserver":  "",
                                 "messagebus":  "",
                                 "product":  "Cashier",
                                 "publish_profile":  "cashier2.retail.dev.pubxml"
                             },
                 "ContentManager":  {
                                        "branch":  "test",
                                        "configuration":  "RetailDemo Debug",
                                        "datetime_deployed":  "Jan 17 2018 11:59:24",
                                        "deployed_by":  "anonymous",
                                        "host":  "contentmanager2-retail3.testing.aws.com",
                                        "job":  "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                                        "lineserver":  "",
                                        "messagebus":  "",
                                        "product":  "ContentManager",
                                        "publish_profile":  "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
                                    }
             }
}
</code>```

My question is - how to preserve source formatting in PowerShell?

答:
If the whole is an array and the element is a single json file, it is awkward.

If you use a pipeline, it is not treated as an array.

```<code>$json | ConvertTo-Json -Depth 10 # bad
</code>```

and since it is not a normal array, so just passing it as a parameter won't work.

```<code>ConvertTo-Json $json -Depth 10  # bad
</code>```

It works well if you re-create the array.

```<code>ConvertTo-Json @($json) -Depth 10  # good
</code>```

Body:
I have a following file in JSON format:

Before ConvertTo-JSON:

[
    {
        "Yura": {
            "Cashier": {
                "branch": "release/Retail-v4.0",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Apr 18 2018 07:45:05",
                "deployed_by": "anonymous",
                "host": "cashier2-retail4.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "Cashier",
                "publish_profile": "cashier2.retail.dev.pubxml"
            },
            "ContentManager": {
                "branch": "release/Retail-v3.31.1",
                "configuration": "RetailDemo Debug",
                "datetime_deployed": "Jan 17 2018 11:59:24",
                "deployed_by": "anonymous",
                "host": "contentmanager2-retail3.testing.aws.com",
                "job": "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                "lineserver": "",
                "messagebus": "",
                "product": "ContentManager",
                "publish_profile": "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
            }
        }
    }
]

after using this code for manipulation with data:

$json = Get-Content 'D:\script\test.json'  -encoding utf8 | ConvertFrom-Json
$json.yura.ContentManager.branch = 'test'

I save JSON into another file:

$json | convertto-json | set-content "D:\script\test1.json" -encoding utf8

Problem is, that after saving file, format become broken:

{
    "Yura":  {
                 "Cashier":  {
                                 "branch":  "release/Retail-v4.0",
                                 "configuration":  "RetailDemo Debug",
                                 "datetime_deployed":  "Apr 18 2018 07:45:05",
                                 "deployed_by":  "anonymous",
                                 "host":  "cashier2-retail4.testing.aws.com",
                                 "job":  "http://jenkins-testing.aws.com:8080/job/CashierDeployment",
                                 "lineserver":  "",
                                 "messagebus":  "",
                                 "product":  "Cashier",
                                 "publish_profile":  "cashier2.retail.dev.pubxml"
                             },
                 "ContentManager":  {
                                        "branch":  "test",
                                        "configuration":  "RetailDemo Debug",
                                        "datetime_deployed":  "Jan 17 2018 11:59:24",
                                        "deployed_by":  "anonymous",
                                        "host":  "contentmanager2-retail3.testing.aws.com",
                                        "job":  "http://jenkins-testing.aws.com:8080/job/ContentManagerDeployment",
                                        "lineserver":  "",
                                        "messagebus":  "",
                                        "product":  "ContentManager",
                                        "publish_profile":  "..\\ContentManager.PublishProfiles\\contentmanager2.retail5.dev.pubxml"
                                    }
             }
}

My question is - how to preserve source formatting in PowerShell?

Body:
If the whole is an array and the element is a single json file, it is awkward.

If you use a pipeline, it is not treated as an array.

$json | ConvertTo-Json -Depth 10 # bad

and since it is not a normal array, so just passing it as a parameter won't work.

ConvertTo-Json $json -Depth 10  # bad

It works well if you re-create the array.

ConvertTo-Json @($json) -Depth 10  # good


问:
First time return undefined and second the correct result, how can i fix it?
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

```<code>getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}
</code>```

and on my component :

```<code> credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);
</code>```

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

答:
This is because javascript is a asynchronous so it will not wait for api call completion.
In your code you log the User outside the subscription scope if you log inside the subscription you will get the user data first time of the call.
There is nothing wrong with your code.

For making a javascript synchronous you can implement the async await

```<code>async callerFunction() {
   await this.credenzialiConfronto();
   console.log(this.User);
}

credenzialiConfronto() {
return new promise ((resolve, reject) => {
  this.cred.getLogin(this.loginForm.get("username").value,
   this.loginForm.get("psw").value).subscribe((res => {
   this.User = res;
   resolve();
}));
})

</code>```

Body:
i have an issue with call on a webservice by using Angular 7. The call is made on this way on my service :

getLogin(usr: String, pwd: String) {
    return this.http.post("the url of webservice", { username: usr, password: pwd
    });
}

and on my component :

 credenzialiConfronto() {
this.cred.getLogin(this.loginForm.get("username").value, this.loginForm.get("psw").value).subscribe((res => {
  this.User = res;
}));

console.log(this.User);

why it returns undefined the first time and the second time not?

EDIT :

on my component i try this now but not work :

https://imgur.com/a/LJ5o4HW

and on my service :

https://imgur.com/gUe3sh5

Body:
This is because javascript is a asynchronous so it will not wait for api call completion.
In your code you log the User outside the subscription scope if you log inside the subscription you will get the user data first time of the call.
There is nothing wrong with your code.

For making a javascript synchronous you can implement the async await

async callerFunction() {
   await this.credenzialiConfronto();
   console.log(this.User);
}

credenzialiConfronto() {
return new promise ((resolve, reject) => {
  this.cred.getLogin(this.loginForm.get("username").value,
   this.loginForm.get("psw").value).subscribe((res => {
   this.User = res;
   resolve();
}));
})


问:
Installing ruby-debug19 locally
I'm currently running Ruby 1.9.2p0 on a Windows XP 32-bit machine.  Ever since we've upgraded to Ruby 1.9, I cannot get any form of debugging to work at all.  I've been told that you need the new ruby-debug19 gem in order to get things running.  Problem is, my company's proxy prevents the gem dependency manager from connecting external repositories.  That's ok, I'll just download the gem myself and install it locally.  The results:

```<code>ERROR:  Error installing ruby-debug19-0.11.6.gem:
    ERROR: Failed to build gem native extension.

C:/Ruby192/bin/ruby.exe extconf.rb --with-ruby-include=C:\Ruby192\include
checking for vm_core.h... no
checking for vm_core.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=C:/Ruby192/bin/ruby
    --with-ruby-dir
    --without-ruby-dir
    --with-ruby-include=${ruby-dir}/include
    --with-ruby-lib
    --without-ruby-lib=${ruby-dir}/lib
C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `initialize': A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. - connect(2) (Errno::ETIMEDOUT)
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `open'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
    from C:/Ruby192/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
    from C:/Ruby192/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `connect'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:626:in `start'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:1160:in `request'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:239:in `block in read'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:286:in `connect'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:234:in `read'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:128:in `download'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/ruby_core_source.rb:55:in `block in create_makefile_with_core'
    from C:/Ruby192/lib/ruby/1.9.1/tempfile.rb:320:in `open'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/ruby_core_source.rb:51:in `create_makefile_with_core'
    from extconf.rb:20:in `<main>'
Requesting http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.2-p0.tar.gz

Gem files will remain installed in C:/Ruby192/lib/ruby/gems/1.9.1/gems/linecache19-0.5.11 for inspection.
Results logged to C:/Ruby192/lib/ruby/gems/1.9.1/gems/linecache19-0.5.11/ext/trace_nums/gem_make.out
</code>```

Perhaps I'm making unreasonable assumptions as I am fairly new to Ruby but it does look like the installation script is attempting to connect an external repository to grab something.  If so, this is absurd, why would I locally install a gem if I was able to do so with the manager automatically?  Does anybody know a way that I can install a debugger in a purely local, offline fashion?  I appreciate any help.

答:
If your using RVM,

you might consider having a look at this URL:- http://isitruby19.com/linecache19 .

Worked for me..

Also,

at a stage, I had to even manually download the gems and use gem install with the "-l" command, to get things working.. The commands for the same are..

```<code>mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ gem install ruby-debug19-0.11.6.gem -l -- --with-ruby-include=$rvm_path/src/ruby-1.9.2-p180/
Building native extensions.  This could take a while...
Successfully installed linecache19-0.5.12
Successfully installed ruby-debug19-0.11.6
2 gems installed
Installing ri documentation for linecache19-0.5.12...
Installing ri documentation for ruby-debug19-0.11.6...
Installing RDoc documentation for linecache19-0.5.12...
Installing RDoc documentation for ruby-debug19-0.11.6...
mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ ls

mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ gem install ruby-debug-base19-0.11.25.gem -l -- --with-ruby-include=$rvm_path/src/ruby-1.9.2-p180/.
Building native extensions.  This could take a while...
Successfully installed ruby-debug-base19-0.11.25
1 gem installed
Installing ri documentation for ruby-debug-base19-0.11.25...
Installing RDoc documentation for ruby-debug-base19-0.11.25...
mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$
</code>```

Change appropriately based on your Ruby version( 136, or 180 or.. ). I have just added a similar installation wrt another gem ruby-debug-base19-0.11.25 , for reference.

ContentLicense: CC BY-SA 2.5

Title: Installing ruby-debug19 locally

Body:
I'm currently running Ruby 1.9.2p0 on a Windows XP 32-bit machine.  Ever since we've upgraded to Ruby 1.9, I cannot get any form of debugging to work at all.  I've been told that you need the new ruby-debug19 gem in order to get things running.  Problem is, my company's proxy prevents the gem dependency manager from connecting external repositories.  That's ok, I'll just download the gem myself and install it locally.  The results:

ERROR:  Error installing ruby-debug19-0.11.6.gem:
    ERROR: Failed to build gem native extension.

C:/Ruby192/bin/ruby.exe extconf.rb --with-ruby-include=C:\Ruby192\include
checking for vm_core.h... no
checking for vm_core.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=C:/Ruby192/bin/ruby
    --with-ruby-dir
    --without-ruby-dir
    --with-ruby-include=${ruby-dir}/include
    --with-ruby-lib
    --without-ruby-lib=${ruby-dir}/lib
C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `initialize': A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. - connect(2) (Errno::ETIMEDOUT)
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `open'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
    from C:/Ruby192/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
    from C:/Ruby192/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:644:in `connect'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:626:in `start'
    from C:/Ruby192/lib/ruby/1.9.1/net/http.rb:1160:in `request'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:239:in `block in read'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:286:in `connect'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:234:in `read'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/contrib/uri_ext.rb:128:in `download'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/ruby_core_source.rb:55:in `block in create_makefile_with_core'
    from C:/Ruby192/lib/ruby/1.9.1/tempfile.rb:320:in `open'
    from C:/Ruby192/lib/ruby/gems/1.9.1/gems/ruby_core_source-0.1.4/lib/ruby_core_source.rb:51:in `create_makefile_with_core'
    from extconf.rb:20:in `'
Requesting http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.2-p0.tar.gz

Gem files will remain installed in C:/Ruby192/lib/ruby/gems/1.9.1/gems/linecache19-0.5.11 for inspection.
Results logged to C:/Ruby192/lib/ruby/gems/1.9.1/gems/linecache19-0.5.11/ext/trace_nums/gem_make.out

Perhaps I'm making unreasonable assumptions as I am fairly new to Ruby but it does look like the installation script is attempting to connect an external repository to grab something.  If so, this is absurd, why would I locally install a gem if I was able to do so with the manager automatically?  Does anybody know a way that I can install a debugger in a purely local, offline fashion?  I appreciate any help.

Body:
If your using RVM,

you might consider having a look at this URL:- http://isitruby19.com/linecache19 .

Worked for me..

Also,

at a stage, I had to even manually download the gems and use gem install with the "-l" command, to get things working.. The commands for the same are..

mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ gem install ruby-debug19-0.11.6.gem -l -- --with-ruby-include=$rvm_path/src/ruby-1.9.2-p180/
Building native extensions.  This could take a while...
Successfully installed linecache19-0.5.12
Successfully installed ruby-debug19-0.11.6
2 gems installed
Installing ri documentation for linecache19-0.5.12...
Installing ri documentation for ruby-debug19-0.11.6...
Installing RDoc documentation for linecache19-0.5.12...
Installing RDoc documentation for ruby-debug19-0.11.6...
mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ ls

mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$ gem install ruby-debug-base19-0.11.25.gem -l -- --with-ruby-include=$rvm_path/src/ruby-1.9.2-p180/.
Building native extensions.  This could take a while...
Successfully installed ruby-debug-base19-0.11.25
1 gem installed
Installing ri documentation for ruby-debug-base19-0.11.25...
Installing RDoc documentation for ruby-debug-base19-0.11.25...
mohnish@mohnish-desktop:~/Downloads/Diaspora_new_gems/mar10$

Change appropriately based on your Ruby version( 136, or 180 or.. ). I have just added a similar installation wrt another gem ruby-debug-base19-0.11.25 , for reference.

ContentLicense: CC BY-SA 3.0


问:
How to connect to on-premise Oracle-db using Azure Functions?
I'm trying to create an Azure Function to connect and query an on-premise Oracle-DB. I can not see that the Oracle Client or an ODBC-driver is installed on the servers to handle this.

Are there any solutions to this using JS or Python?

I have tried using the node-odbc driver, but the server is missing the Oracle client.

答:
Partially answer for connecting to on-premise service like Oracle-db from Azure Functions, there is an existing SO thread How to Azure function configure for Site-to-Site Connectivity? had answered it, which you can refer to. So first, you must make sure networking access to on-premise server available.

Then, if you want to query oracle database via odbc, the oracle odbc driver must be installed on the client-side. However, the oracle odbc driver is a commerce componet, which you need to pay for getting it, and install it manually in Azure Functions. So even you want to use JS or Python to connect it, I think using Java with Oracle jdbc driver is a better solution from Azure Functions to connect Oracle DB to avoid the additional installation.

The other way I thought is to deploy a REST API app as proxy on your on-premise server to handle the query request from Azure Functions with JS or Python to help connecting Oracle DB.


问:
Localization for input field with double value in Razor Pages
In my ViewModel I have a property like this:

```<code>[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public double SomeDoubleProperty { get; set; }
</code>```

Markup:

```<code><div class="form-group row">
    <label asp-for="ViewModel.SomeDoubleProperty" class="col-sm-3 col-form-label">
        @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]
    </label>
    <div class="col-sm-9">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">%</span>
            </div>
            <input asp-for="ViewModel.SomeDoubleProperty"
                   class="form-control">
        </div>
        <span asp-validation-for="ViewModel.SomeDoubleProperty" class="text-danger"></span>
    </div>
</div>
</code>```

After loading the page (with the default value 0) it is shown like this in the input field:

(The current culture and current ui culture of the thread is "de", so the decimal separator "," is the expected one).

But when I now leave the input field, the following validation error is shown:

The field SomeDoubleProperty must be a number.

When replacing the "," with a ".", the validator accepts the value.
How can I achieve that the "," is accepted, too, if the current ui culture is "de"?

答:
you need to download and configure client side validation scripts:

cldrjs

cldr-data

globalizejs

in the root of your project create a new file name it "libman.json" and add the below libraries to it:

```<code>{
  "version": "1.0",
  "defaultProvider": "jsdelivr",
  "libraries": [
    {
      "library": "cldrjs@0.5.1",
      "destination": "wwwroot/lib/cldr"
    },
    {
      "library": "cldr-data@35.1.0",
      "destination": "wwwroot/lib/cldr-data"
    },
    {
      "library": "globalize@1.4.2",
      "destination": "wwwroot/lib/globalize"
    }
  ]
}
</code>```

When you save the file it will download all scripts to the wwwroor/lib folder.

Then open wwwroot/lib/cldr-data/package.json and add the below lines to the end of the page before the closing braket:

```<code>"peerDependencies": {
    "cldr-data": ">=26"
  }
</code>```

When you save the file it will download all json data (numbering, date, time, currency, etc.) for all cultures. The download may take a while (~35MB).

There is one more js library "jquery.validate.globalize.min.js" needs to be installed but the version in jsdelivr 0.1.1 is not compatible, we need v1.0, so either download it manually from GitHub or just use the jsdelivr's import functionality from GitHub as below:

```<code><script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>
</code>```

Then create a new partial view name it "_LocalizationValidationScriptsPartial.cshtml" and add the libraries to it:

```<code><!-- cldr scripts (needed for globalize) -->
<script src="/lib/cldr/dist/cldr.min.js"></script>
<script src="/lib/cldr/dist/cldr/event.min.js"></script>
<script src="/lib/cldr/dist/cldr/supplemental.min.js"></script>

<!-- globalize scripts -->
<script src="/lib/globalize/dist/globalize.min.js"></script>
<script src="/lib/globalize/dist/globalize/number.min.js"></script>
<script src="/lib/globalize/dist/globalize/date.min.js"></script>
<script src="/lib/globalize/dist/globalize/currency.min.js"></script>

<!-- this file can be downloaded from : -->
<!-- https://github.com/johnnyreilly/jquery-validation-globalize -->
<script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>

<!-- code to get check if current cultures scripts are exists -->
<!-- if not, select parent cultures scripts -->
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment HostingEnvironment
@{
    string GetDefaultLocale()
    {
        const string localePattern = "lib\\cldr-data\\main\\{0}";
        var currentCulture = System.Globalization.CultureInfo.CurrentCulture;
        var cultureToUse = "en"; //Default regionalisation to use

        if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.Name))))
            cultureToUse = currentCulture.Name;
        else if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.TwoLetterISOLanguageName))))
            cultureToUse = currentCulture.TwoLetterISOLanguageName;

        return cultureToUse;
    }
}

<script type="text/javascript">
    var culture = "@GetDefaultLocale()";
    $.when(
        $.get("/lib/cldr-data/supplemental/likelySubtags.json"),
        $.get("/lib/cldr-data/main/" + culture + "numbers.json"),
        $.get("/lib/cldr-data/main/" + culture + "/currencies.json"),
        $.get("/lib/cldr-data/supplemental/numberingSystems.json"),
        $.get("/lib/cldr-data/main/" + culture + "/ca-gregorian.json"),
        $.get("/lib/cldr-data/main/" + culture + "/timeZoneNames.json"),
        $.get("/lib/cldr-data/supplemental/timeData.json"),
        $.get("/lib/cldr-data/supplemental/weekData.json"),
    ).then(function () {
        // Normalize $.get results, we only need the JSON, not the request statuses.
        return [].slice.apply(arguments, [0]).map(function (result) {
            return result[0];
        });
    }).then(Globalize.load).then(function () {
        Globalize.locale(culture);
    });
</script>

</code>```

Last, just include this partial view after the default _ValidationScriptsPartial.cshtml where you need the localization validation to be done.

```<code><partial name="_ValidationScriptsPartial.cshtml" />
<partial name="_LocalizationValidationScriptsPartial.cshtml" />
</code>```

Alternate method

I created a TagHelperComponent to avoid all the hard work, you even don't need to download the scripts to your local.

install the nuget package:

Install-Package LazZiya.TagHelpers -Version 2.1.0
```

<ul>
<li>add LazZiya.TagHelpers to _ViewImports :</li>
</ul>

```@using LazZiya.TagHelpers
@addTagHelper *, LazZiya.TagHelpers
```

<ul>
<li>register the localization validation tag helper component in startup:</li>
</ul>

<pre class="lang-cs prettyprint-override"><code>services.AddTransient<ITagHelperComponent, LocalizationValidationScriptsTagHelperComponent>();
</code>```

add the tag to the scripts section of the page for validating localized input fields (the default _ValidationScriptsPartial.cshtml must be loaded as well):

```<code><partial name="_ValidationScriptsPartial.cshtml" />
<localization-validation-scripts></localization-validation-scripts>
</code>```

This TagHelper will automatically detect the current culture name and add all necessary scripts for validating localized values.

For more details see LazZiya.TagHelpers

Body:
In my ViewModel I have a property like this:

[DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)]
public double SomeDoubleProperty { get; set; }

Markup:

        @Localizer[nameof(Model.ViewModel.SomeDoubleProperty)]

                %

            <input asp-for="ViewModel.SomeDoubleProperty"
                   class="form-control">

After loading the page (with the default value 0) it is shown like this in the input field:

(The current culture and current ui culture of the thread is "de", so the decimal separator "," is the expected one).

But when I now leave the input field, the following validation error is shown:

The field SomeDoubleProperty must be a number.

When replacing the "," with a ".", the validator accepts the value.
How can I achieve that the "," is accepted, too, if the current ui culture is "de"?

Body:
you need to download and configure client side validation scripts:

cldrjs

cldr-data

globalizejs

in the root of your project create a new file name it "libman.json" and add the below libraries to it:

{
  "version": "1.0",
  "defaultProvider": "jsdelivr",
  "libraries": [
    {
      "library": "cldrjs@0.5.1",
      "destination": "wwwroot/lib/cldr"
    },
    {
      "library": "cldr-data@35.1.0",
      "destination": "wwwroot/lib/cldr-data"
    },
    {
      "library": "globalize@1.4.2",
      "destination": "wwwroot/lib/globalize"
    }
  ]
}

When you save the file it will download all scripts to the wwwroor/lib folder.

Then open wwwroot/lib/cldr-data/package.json and add the below lines to the end of the page before the closing braket:

"peerDependencies": {
    "cldr-data": ">=26"
  }

When you save the file it will download all json data (numbering, date, time, currency, etc.) for all cultures. The download may take a while (~35MB).

There is one more js library "jquery.validate.globalize.min.js" needs to be installed but the version in jsdelivr 0.1.1 is not compatible, we need v1.0, so either download it manually from GitHub or just use the jsdelivr's import functionality from GitHub as below:

<script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>

Then create a new partial view name it "_LocalizationValidationScriptsPartial.cshtml" and add the libraries to it:

<!-- cldr scripts (needed for globalize) -->
<script src="/lib/cldr/dist/cldr.min.js"></script>
<script src="/lib/cldr/dist/cldr/event.min.js"></script>
<script src="/lib/cldr/dist/cldr/supplemental.min.js"></script>

<!-- globalize scripts -->
<script src="/lib/globalize/dist/globalize.min.js"></script>
<script src="/lib/globalize/dist/globalize/number.min.js"></script>
<script src="/lib/globalize/dist/globalize/date.min.js"></script>
<script src="/lib/globalize/dist/globalize/currency.min.js"></script>

<!-- this file can be downloaded from : -->
<!-- https://github.com/johnnyreilly/jquery-validation-globalize -->
<script src="https://cdn.jsdelivr.net/gh/johnnyreilly/jquery-validation-globalize@1.0.0/jquery.validate.globalize.min.js"></script>

<!-- code to get check if current cultures scripts are exists -->
<!-- if not, select parent cultures scripts -->
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment HostingEnvironment
@{
    string GetDefaultLocale()
    {
        const string localePattern = "lib\\cldr-data\\main\\{0}";
        var currentCulture = System.Globalization.CultureInfo.CurrentCulture;
        var cultureToUse = "en"; //Default regionalisation to use

        if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.Name))))
            cultureToUse = currentCulture.Name;
        else if (System.IO.Directory.Exists(System.IO.Path.Combine(HostingEnvironment.WebRootPath, string.Format(localePattern, currentCulture.TwoLetterISOLanguageName))))
            cultureToUse = currentCulture.TwoLetterISOLanguageName;

        return cultureToUse;
    }
}

<script type="text/javascript">
    var culture = "@GetDefaultLocale()";
    $.when(
        $.get("/lib/cldr-data/supplemental/likelySubtags.json"),
        $.get("/lib/cldr-data/main/" + culture + "numbers.json"),
        $.get("/lib/cldr-data/main/" + culture + "/currencies.json"),
        $.get("/lib/cldr-data/supplemental/numberingSystems.json"),
        $.get("/lib/cldr-data/main/" + culture + "/ca-gregorian.json"),
        $.get("/lib/cldr-data/main/" + culture + "/timeZoneNames.json"),
        $.get("/lib/cldr-data/supplemental/timeData.json"),
        $.get("/lib/cldr-data/supplemental/weekData.json"),
    ).then(function () {
        // Normalize $.get results, we only need the JSON, not the request statuses.
        return [].slice.apply(arguments, [0]).map(function (result) {
            return result[0];
        });
    }).then(Globalize.load).then(function () {
        Globalize.locale(culture);
    });
</script>

Last, just include this partial view after the default _ValidationScriptsPartial.cshtml where you need the localization validation to be done.

<partial name="_ValidationScriptsPartial.cshtml" />
<partial name="_LocalizationValidationScriptsPartial.cshtml" />

Alternate method

I created a TagHelperComponent to avoid all the hard work, you even don't need to download the scripts to your local.

install the nuget package:

Install-Package LazZiya.TagHelpers -Version 2.1.0

add LazZiya.TagHelpers to _ViewImports :

@using LazZiya.TagHelpers
@addTagHelper *, LazZiya.TagHelpers

register the localization validation tag helper component in startup:

services.AddTransient<ITagHelperComponent, LocalizationValidationScriptsTagHelperComponent>();

add the tag to the scripts section of the page for validating localized input fields (the default _ValidationScriptsPartial.cshtml must be loaded as well):

<partial name="_ValidationScriptsPartial.cshtml" />
<localization-validation-scripts></localization-validation-scripts>

This TagHelper will automatically detect the current culture name and add all necessary scripts for validating localized values.

For more details see LazZiya.TagHelpers


问:
How to call get or any method of requests library of python by passing a method name to function argument?
I am using requests library of python. I wanted to call requests method GET,POST or any method depend on the arguments received in the function call. I will call requests method inside that function. How can i achieve this?

```<code>import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = requests.method(endpoint_api) # this method should be replaced by method argument of a function get_endpoint
get_endpoint('get', "https://abc/", ['john','joe','1368797932'])
</code>```

I expect it will replace method with get,post whichever passed to function and that url will invoke.
For ex. requests.get(endpoint_api) # get is replaced by method and it will call the url.

答:
You can use a dictionary for example:

```<code>def get_endpoint(method,shop, list_obj):
    method_f = {
        "get": requests.get,
        "post": requests.post,
        ...
    }
    def invalid_method(*_):
        raise ValueError("Method not supported")
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = method_f.get(method, invalid_method)(endpoint_api) # this method should be replaced by method argument of a function get_endpoint
</code>```

Notice that I added a default function to raise an error if you do not support the method. The error is just for the example purposes and you can raise whatever you need.

Body:
I am using requests library of python. I wanted to call requests method GET,POST or any method depend on the arguments received in the function call. I will call requests method inside that function. How can i achieve this?

import requests

def get_endpoint(method,shop, list_obj):
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = requests.method(endpoint_api) # this method should be replaced by method argument of a function get_endpoint
get_endpoint('get', "https://abc/", ['john','joe','1368797932'])

I expect it will replace method with get,post whichever passed to function and that url will invoke.
For ex. requests.get(endpoint_api) # get is replaced by method and it will call the url.

Body:
You can use a dictionary for example:

def get_endpoint(method,shop, list_obj):
    method_f = {
        "get": requests.get,
        "post": requests.post,
        ...
    }
    def invalid_method(*_):
        raise ValueError("Method not supported")
    join_sentence = '/'.join(list_obj)
    endpoint_api = "https://{0}/admin/2019-04/{1}.json".format(shop, join_sentence)
    a = method_f.get(method, invalid_method)(endpoint_api) # this method should be replaced by method argument of a function get_endpoint

Notice that I added a default function to raise an error if you do not support the method. The error is just for the example purposes and you can raise whatever you need.


问:
how to make http://abcd.com/../../xyz/a.do work
I tried to run something like this http://abcd.com/../../xyz/a.do via browser.But it didn't succeed.

My question is can we run a url where it is fetching data from directories not child of abcd.com

Thanks

Edit:

Let say I have this directory structure under /www/:

    /xzy

    /blah/abcd.com/

And I want to access data in /xyz

答: That is a very old security exploit (directory traversal) that actually worked some years ago. Nowadays, web servers are not susceptible to that.</p>


问:
How to correctly position a radial gradient background?
I have small problem with css position with this code.

Unfortunately I need this circle to be on the right side of the page (div) and not in the middle. Thanks for the answers

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
 background: -moz-radial-gradient(transparent 200px, rgba(255,255,255,0.6) 200px);
  background: -webkit-radial-gradient(transparent 100px , rgba(255,255,255,0.6) 200px ) ;
  background: -ms-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  background: -o-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="session-box">
  <div class="circle"></div>
</div></code>```

i need this

答:
insert circle at calc(100% - 200px) as first parameter

See: https://developer.mozilla.org/en-US/docs/Web/CSS/radial-gradient or

https://css-tricks.com/snippets/css/css-radial-gradient/

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at calc(100% - 200px), transparent 100px, rgba(255,255,255,0.6) 200px);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="session-box">
  <div class="circle"></div>
</div></code>```

Body:
I have small problem with css position with this code.

Unfortunately I need this circle to be on the right side of the page (div) and not in the middle. Thanks for the answers

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
 background: -moz-radial-gradient(transparent 200px, rgba(255,255,255,0.6) 200px);
  background: -webkit-radial-gradient(transparent 100px , rgba(255,255,255,0.6) 200px ) ;
  background: -ms-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  background: -o-radial-gradient(transparent 100px, rgba(255,255,255,0.6) 200px);
  }

i need this

Body:
insert circle at calc(100% - 200px) as first parameter

See: https://developer.mozilla.org/en-US/docs/Web/CSS/radial-gradient or

https://css-tricks.com/snippets/css/css-radial-gradient/

body{
 margin:0;
 padding:0;
 }

 .session-box{
 background:#333;
 width:100%;
 min-height:100vh;
 }

 .circle{
 position: absolute;
  top: 0;
  left 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at calc(100% - 200px), transparent 100px, rgba(255,255,255,0.6) 200px);
  }

<div class="session-box">
  <div class="circle"></div>
</div>


问:
How can I access the entity tree created by QSceneLoader?
I am trying to access the geometry and material of a mesh loaded with QSceneLoader, but I dont know how.

The doc says

Given a 3D source file, the Qt3DRender::QSceneLoader will try to parse it and build a tree of Qt3DCore::QEntity objects with proper Qt3DRender::QGeometryRenderer, Qt3DCore::QTransform and Qt3DRender::QMaterial components.

but it doesnt say how to access that tree. The .component() function seems to be a solution, but it needs an entity name wich I dont have.

I found a file with tests for QSceneLoader using the .component() function (here)[https://code.woboq.org/qt5/qt3d/tests/auto/render/qsceneloader/tst_qsceneloader.cpp.html ], but they seem to build the entity tree manually or something.

I could use the Qmesh Class, but QSceneLoader supports far more file formats including fbx and glTF, wich I want to support.

If this is not possible, an alternative is also appreciated.

答:
I finally found a working solution in this post:

Qt3d Using QSceneLoader with qt 5.8

The SceneWalker does exactly what i need.


问:
I want to add x customers on Prestashop via code but with extra fields
I'm trying to add customers with a code but the PrestaShop is giving me a bug.
I'm using PHP and XML

```<code>$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetEntitiesRQ xmlns:x="urn:Winmax4GetEntitiesRQ">'.
                    '</x:Winmax4GetEntitiesRQ >';
                    $Params=array(
                    'CompanyCode'=>'',
                    'UserLogin'=>'',
                    'UserPassword'=>'',
                    'Winmax4GetEntitiesRQXML'=> $XMLRQString
                    );
                    $return = $client->GetEntities($Params);
                    $XMLRSString = new SimpleXMLElement($return->GetEntitiesResult);

foreach ($XMLRSString->Entities->Entity as $entity)
{
    $default_lang= Configuration::get('PS_LANG_DEFAULT');

    $customer=new Customer();

    $customer->email= $entity->Email;

    $customer->lastname= $entity->EntityType;

    $customer->firstname= [$default_lang => $entity->Name];

    $customer->contribuinte= $entity->TaxPayerID;

    $customer->passwd= $entity->TaxPayerID;

    $customer->active = 1;

    $customer->add();
}
</code>```

ERROR: (1/1) ContextErrorException Warning: preg_match() expects
parameter 2 to be string, array given

in Validate.php line 172

at ValidateCore::isCustomerName(array(object(SimpleXMLElement))) in
ObjectModel.php line 1149

at ObjectModelCore->validateField('firstname',
array(object(SimpleXMLElement))) in ObjectModel.php line 981

at ObjectModelCore->validateFields() in ObjectModel.php line 284

at ObjectModelCore->getFields() in ObjectModel.php line 551

at ObjectModelCore->add(true, true) in Customer.php line 264

at CustomerCore->add() in create_clients.php line 66

答:
When storing values from SimpleXML, if you just refer to the element itself by it's tag name - this will be an instance of SimpleXMLElement.  As you want the actual content of the element, the simplest way to do this is to cast it to a string...</p>

```<code>$customer->firstname= (string)$entity->Name;
</code>```

Body:
I'm trying to add customers with a code but the PrestaShop is giving me a bug.
I'm using PHP and XML

$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetEntitiesRQ xmlns:x="urn:Winmax4GetEntitiesRQ">'.
                    '</x:Winmax4GetEntitiesRQ >';
                    $Params=array(
                    'CompanyCode'=>'',
                    'UserLogin'=>'',
                    'UserPassword'=>'',
                    'Winmax4GetEntitiesRQXML'=> $XMLRQString
                    );
                    $return = $client->GetEntities($Params);
                    $XMLRSString = new SimpleXMLElement($return->GetEntitiesResult);

foreach ($XMLRSString->Entities->Entity as $entity)
{
    $default_lang= Configuration::get('PS_LANG_DEFAULT');

    $customer=new Customer();

    $customer->email= $entity->Email;

    $customer->lastname= $entity->EntityType;

    $customer->firstname= [$default_lang => $entity->Name];

    $customer->contribuinte= $entity->TaxPayerID;

    $customer->passwd= $entity->TaxPayerID;

    $customer->active = 1;

    $customer->add();
}

ERROR: (1/1) ContextErrorException Warning: preg_match() expects
parameter 2 to be string, array given

in Validate.php line 172

at ValidateCore::isCustomerName(array(object(SimpleXMLElement))) in
ObjectModel.php line 1149

at ObjectModelCore->validateField('firstname',
array(object(SimpleXMLElement))) in ObjectModel.php line 981

at ObjectModelCore->validateFields() in ObjectModel.php line 284

at ObjectModelCore->getFields() in ObjectModel.php line 551

at ObjectModelCore->add(true, true) in Customer.php line 264

at CustomerCore->add() in create_clients.php line 66

Body:
When storing values from SimpleXML, if you just refer to the element itself by it's tag name - this will be an instance of SimpleXMLElement.  As you want the actual content of the element, the simplest way to do this is to cast it to a string...

$customer->firstname= (string)$entity->Name;


问:
How to delete a transcribe job in Amazon Transcribe
Do I need to delete a few transcribe jobs that I created using Amazon Transcribe service?

I'm using amazon transcribe for the first time to get a text from the video, it works fine but I didn't find anything there how to delete the particular transcribe job.

答:
Looks like they do offer a delete option now: https://docs.aws.amazon.com/transcribe/latest/dg/API_DeleteTranscriptionJob.html . Unfortunately, the code below is giving me a "Operation not found: DeleteTranscriptionJob" error, and I just can't figure out why.</p>

```<code>$result = $transcribe->deleteTranscriptionJob([
   'TranscriptionJobName' => $transcriptionJobName
]);
</code>```

Body:
Looks like they do offer a delete option now: https://docs.aws.amazon.com/transcribe/latest/dg/API_DeleteTranscriptionJob.html . Unfortunately, the code below is giving me a "Operation not found: DeleteTranscriptionJob" error, and I just can't figure out why.

$result = $transcribe->deleteTranscriptionJob([
   'TranscriptionJobName' => $transcriptionJobName
]);


问:
ExoPlayer layout with fixed aspect ratio
I'm trying to build a YouTube like view using ExoPlayer on Android. I would like the video to appear at the top followed by some other content like title, description, etc. All my videos are 16:9 and I would like the SimpleExoPlayerView to start out in the 16:9 layout. With the layout below, the player occupies the whole screen for a couple of seconds before switching to the correct aspect ratio of the video:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:keepScreenOn="true">

  <com.google.android.exoplayer2.ui.SimpleExoPlayerView android:id="@+id/player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">

  </com.google.android.exoplayer2.ui.SimpleExoPlayerView>

  <TextView
    android:id="@+id/text_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:text="VideoTitle"
    android:textAppearance="@style/TextAppearance.AppCompat.Title" />

  <TextView
    android:id="@+id/text_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:text="description" />
</LinearLayout>
</code>```

答:
We are using the bundled AspectRatioFrameLayout that comes with ExpoPlayer:

https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.html

That's how you use it:

```<code><com.google.android.exoplayer2.ui.AspectRatioFrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">

    <!-- Preview image -->
    <ImageView
        android:id="@+id/imageViewVideo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:contentDescription="@string/img_content_training_video_preview"
        android:focusable="true"
        android:scaleType="centerCrop" />

    <!-- Play button -->
    <ImageView
        android:id="@+id/imageTrainingPreviewIcon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:contentDescription="@string/img_content_training_video_preview"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_play" />

    <!-- Video player -->
    <com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlack"
        android:visibility="gone" />

    <!-- ProgressBar -->
    <include layout="@layout/custom_video_loading_progressbar" />

</com.google.android.exoplayer2.ui.AspectRatioFrameLayout>
</code>```

Then on your Activity or Fragment you must set the aspect ratio:

```<code>aspectRatioFrameLayout.setAspectRatio(16f/9f)
</code>```

You can also set the resize mode in code with setResizeMode.

Body:
I'm trying to build a YouTube like view using ExoPlayer on Android. I would like the video to appear at the top followed by some other content like title, description, etc. All my videos are 16:9 and I would like the SimpleExoPlayerView to start out in the 16:9 layout. With the layout below, the player occupies the whole screen for a couple of seconds before switching to the correct aspect ratio of the video:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:keepScreenOn="true">

  <com.google.android.exoplayer2.ui.SimpleExoPlayerView android:id="@+id/player_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">

  </com.google.android.exoplayer2.ui.SimpleExoPlayerView>

  <TextView
    android:id="@+id/text_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:text="VideoTitle"
    android:textAppearance="@style/TextAppearance.AppCompat.Title" />

  <TextView
    android:id="@+id/text_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:text="description" />
</LinearLayout>

Body:
We are using the bundled AspectRatioFrameLayout that comes with ExpoPlayer:

https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ui/AspectRatioFrameLayout.html

That's how you use it:

<com.google.android.exoplayer2.ui.AspectRatioFrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:resize_mode="fixed_width">

    <!-- Preview image -->
    <ImageView
        android:id="@+id/imageViewVideo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:contentDescription="@string/img_content_training_video_preview"
        android:focusable="true"
        android:scaleType="centerCrop" />

    <!-- Play button -->
    <ImageView
        android:id="@+id/imageTrainingPreviewIcon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:contentDescription="@string/img_content_training_video_preview"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_play" />

    <!-- Video player -->
    <com.google.android.exoplayer2.ui.SimpleExoPlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlack"
        android:visibility="gone" />

    <!-- ProgressBar -->
    <include layout="@layout/custom_video_loading_progressbar" />

</com.google.android.exoplayer2.ui.AspectRatioFrameLayout>

Then on your Activity or Fragment you must set the aspect ratio:

aspectRatioFrameLayout.setAspectRatio(16f/9f)

You can also set the resize mode in code with setResizeMode.


问:
In Django, disable @login_required for search engine spiders
I'm looking for a clean way to let search engine spiders bypass @login_required, viewing pages which typically require a logged-in user.  I could write middleware that would automatically log search engines into a dummy account, but that's not exactly what I'd call clean.  Any suggestions for a better solution?  Thanks.</p>

答:
Don't do this. This is 'cloaking', and can get you banned from Google's index.

Cloaking refers to the practice of presenting different content or URLs to users and search engines. Serving up different results based on user agent may cause your site to be perceived as deceptive and removed from the Google index.

Cloaking: http://www.google.com/support/webmasters/bin/answer.py?answer=66355

Instead, you need to implement Google's First Click Free solution. In this setup, the first click from a Google search result is able to see the full content, subsequent clicks are trapped. This can be done on a referrer basis, or a cookie basis. You can read more about First Click Free here:

First Click Free: http://www.google.com/support/webmasters/bin/answer.py?answer=74536


问:
Is fixed-top/fixed-bottom + inner div's with fixed height the right approach?
I am trying to create stackoverflow-style app with fixed menu and footer panels and the inner div which create browser scroll (as necessary).

I just wanted to ask if the following code is right to achieve the mentioned scenario? fixed-top/fixed-bottom are styles from the Bootstrap4. I see that I have to use fixed constants in my HTML/Style code in my approach, is it OK.

      Header

      (1) The protection of natural persons in relation to the processing of personal data is a fundamental right. Article 8(1) of the Charter of Fundamental Rights of the European Union (the ‘Charter’) and Article 16(1) of the Treaty on the Functioning of
      the European Union (TFEU) provide that everyone has the right to the protection of personal data concerning him or her.

      Footer

```

答:
Instead of using the Bootstrap class please use below css where the header and footer
will have fixed height and position absolute.</p>

```<code>    html body {
        height: 100%;
        overflow: hidden;
      }
      html body .container-fluid.body-content {
        position: absolute;
        top: 50px;
        bottom: 30px;
        right: 0;
        left: 0;
        overflow-y: auto;
      }
      fixed-header {
          position: absolute;
          left: 0;
          right: 0;
          top: 0;
          background-color: #4C4;
          height: 50px;
      }
      fixed-bottom {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: #4C4;
          height: 30px;
      }

 <div class="fixed-header">
      Header
    </div>
    <div class="container-fluid body-content">
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
    </div>
    <div class="fixed-bottom">
      Footer
    </div>
</code>```

Body:
Instead of using the Bootstrap class please use below css where the header and footer
will have fixed height and position absolute.

    html body {
        height: 100%;
        overflow: hidden;
      }
      html body .container-fluid.body-content {
        position: absolute;
        top: 50px;
        bottom: 30px;
        right: 0;
        left: 0;
        overflow-y: auto;
      }
      fixed-header {
          position: absolute;
          left: 0;
          right: 0;
          top: 0;
          background-color: #4C4;
          height: 50px;
      }
      fixed-bottom {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: #4C4;
          height: 30px;
      }

 <div class="fixed-header">
      Header
    </div>
    <div class="container-fluid body-content">
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
      Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>
    </div>
    <div class="fixed-bottom">
      Footer
    </div>


问:
Owl Carousel is not working with direction RTL
The Owl Carousel slider is not working with RTL. I add rtl: true in the configuration. But it's not loading the slider. The slider space is there and navigation is showing. But only the slider content is not showing. How can I fix this problem?

My code is given below:

```<code><div class="row" id="brand-slider">
    <div class="item">
        <a href="#">
        <img src="{base_url()}assets/upload/brands/{$v.image}" class="img-responsive img-centered" alt="{$v.name}">
        </a>
    </div>
    <div class="item">
        <a href="#">
        <img src="{base_url()}assets/upload/brands/{$v.image}" class="img-responsive img-centered" alt="{$v.name}">
        </a>
    </div>
    <div class="item">
        <a href="#">
        <img src="{base_url()}assets/upload/brands/{$v.image}" class="img-responsive img-centered" alt="{$v.name}">
        </a>
    </div>
    <div class="item">
        <a href="#">
        <img src="{base_url()}assets/upload/brands/{$v.image}" class="img-responsive img-centered" alt="{$v.name}">
        </a>
    </div>
</div>

<script>
    $("#brand-slider").owlCarousel({
        rtl: true,
        loop: true,
        items: 6,
        pagination: false,
        autoPlay: true,
        responsive: true
    });
</script>
</code>```

答:
This solution worked for me

Add direction: ltr; to the the .owl-stage-outer class in the owl.carousel.min.css file , as following

```<code>.owl-stage-outer{
 position:relative;
 overflow:hidden;
 -webkit-transform:translate3d(0,0,0);
 direction: ltr;
}
</code>```

Body:
This solution worked for me

Add direction: ltr; to the the .owl-stage-outer class in the owl.carousel.min.css file , as following

.owl-stage-outer{
 position:relative;
 overflow:hidden;
 -webkit-transform:translate3d(0,0,0);
 direction: ltr;
}