问:
Symfony3 I have to show from a related entity
I have a question.

I have 2 entity

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="call_center")
 */
class Call {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Number", mappedBy="number")
     * @ORM\Column(type="string")
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
      private $value;
......
    getters setters

/**
 * @ORM\Entity
 * @ORM\Table(name="number")
 */
class Number {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Call", inversedBy="number")
     * @ORM\JoinColumn(nullable=false)
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
    private $link;
</code>```

And I would like to show my data in controller.
This is my controller

```<code>class DefaultController extends Controller
{
    /**
     * @Route("/pl/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getRepository('AppBundle:Call')->findAll();

        foreach ($em as $name) {
        switch(1) {
            case $name->getNumber():
                echo $name->getValue();
                echo $name->getLink(); <----PROBLEME
                break;
            default:
                break;
        }
        }

        return $this->render('default/index.html.twig', array(
            'em' => $name
        ));
    }
}
</code>```

Data with entity call displayed but I don't know how dipsplay data from Number (getLink()). The problem is that I have a loop in which I have to display for a particular value relationship. Probably I have to create repository for entity?

```<code>Entity Call
/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set number
 *
 * @param string $number
 *
 * @return Call
 */
public function setNumber($number)
{
    $this->number = $number;

    return $this;
}

/**
 * Get number
 *
 * @return string
 */
public function getNumber()
{
    return $this->number;
}

/**
 * Set value
 *
 * @param string $value
 *
 * @return Call
 */
public function setValue($value)
{
    $this->value = $value;

    return $this;
}

/**
 * Get value
 *
 * @return string
 */
public function getValue()
{
    return $this->value;
}

entity Number

/**
     * Set number
     *
     * @param \AppBundle\Entity\Call $number
     *
     * @return Number
     */
    public function setNumber(\AppBundle\Entity\Call $number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return \AppBundle\Entity\Call
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set link
     *
     * @param string $link
     *
     * @return Number
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }
</code>```

答:
Maybe you have a string because you tell doctrine to put a string ?

remove the following annotation from your relation :

```<code>@ORM\Column(type="string")
</code>```

Body:
I have a question.

I have 2 entity

/**
 * @ORM\Entity
 * @ORM\Table(name="call_center")
 */
class Call {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Number", mappedBy="number")
     * @ORM\Column(type="string")
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
      private $value;
......
    getters setters

/**
 * @ORM\Entity
 * @ORM\Table(name="number")
 */
class Number {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Call", inversedBy="number")
     * @ORM\JoinColumn(nullable=false)
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
    private $link;

And I would like to show my data in controller.
This is my controller

class DefaultController extends Controller
{
    /**
     * @Route("/pl/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getRepository('AppBundle:Call')->findAll();

        foreach ($em as $name) {
        switch(1) {
            case $name->getNumber():
                echo $name->getValue();
                echo $name->getLink(); <----PROBLEME
                break;
            default:
                break;
        }
        }

        return $this->render('default/index.html.twig', array(
            'em' => $name
        ));
    }
}

Data with entity call displayed but I don't know how dipsplay data from Number (getLink()). The problem is that I have a loop in which I have to display for a particular value relationship. Probably I have to create repository for entity?

Entity Call
/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set number
 *
 * @param string $number
 *
 * @return Call
 */
public function setNumber($number)
{
    $this->number = $number;

    return $this;
}

/**
 * Get number
 *
 * @return string
 */
public function getNumber()
{
    return $this->number;
}

/**
 * Set value
 *
 * @param string $value
 *
 * @return Call
 */
public function setValue($value)
{
    $this->value = $value;

    return $this;
}

/**
 * Get value
 *
 * @return string
 */
public function getValue()
{
    return $this->value;
}

entity Number

/**
     * Set number
     *
     * @param \AppBundle\Entity\Call $number
     *
     * @return Number
     */
    public function setNumber(\AppBundle\Entity\Call $number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return \AppBundle\Entity\Call
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set link
     *
     * @param string $link
     *
     * @return Number
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }

Body:
Maybe you have a string because you tell doctrine to put a string ?

remove the following annotation from your relation :

@ORM\Column(type="string")


来源: stackexchange

问:
How to display only my costumes (created ) modules in Odoo (OpenERP)
I would like to show only my custom module in Odoo interface, without displaying other Odoo Modules.

I have tried to assign my module to the user ( in user settings interface) and hidde other modules to him. But when the user login he see only the Web module, without the other modules.

For example:

I Odoo menu you can see the names of modules like : Sales, Calender ...etc

My goal is to hidde all module to users, and display only my module ( my costum module)

Any help please ... Thank you

答:
Inherit action for module list and add a domain

Try below code:

```<code><record id="open_module_tree" model="ir.actions.act_window">
        <field name="name">Apps</field>
        <field name="res_model">ir.module.module</field>
        <field name="view_type">form</field>
        <field name="view_mode">kanban,tree,form</field>
        <field name="domain">[('name,'=','your_module_name')]</field>
        <field name="context">{'search_default_app':1}</field>
        <field name="search_view_id" ref="view_module_filter"/>
        <field name="help" type="html">
          <p><b>No module found!</b></p>
          <p>You should try other search criteria.</p>
        </field>
    </record>
</code>```

Hope it will help you.

ContentLicense: CC BY-SA 3.0

Body:
Inherit action for module list and add a domain

Try below code:

<record id="open_module_tree" model="ir.actions.act_window">
        <field name="name">Apps</field>
        <field name="res_model">ir.module.module</field>
        <field name="view_type">form</field>
        <field name="view_mode">kanban,tree,form</field>
        <field name="domain">[('name,'=','your_module_name')]</field>
        <field name="context">{'search_default_app':1}</field>
        <field name="search_view_id" ref="view_module_filter"/>
        <field name="help" type="html">
          <p><b>No module found!</b></p>
          <p>You should try other search criteria.</p>
        </field>
    </record>

Hope it will help you.


问:
Perl in Windows Vista 32bit?
I want to practice Perl in Windows Vista 32bit, how can I do it ?

Thanks.

答: You can use ActivePerl.</p>

ContentLicense: CC BY-SA 2.5

Title: Perl in Windows Vista 32bit?

Body: You can use ActivePerl.


问:
Textfield does not detect touch
I found a weird problem in my iOS application written in Swift. Sometimes textfield does not work ie textfield does not detect touch and keyboard is not showing. All the textfields in every viewControllers suddenly stops working. Help is much appreciated thank you.

Edit: Adding some code

```<code> override func viewDidLoad()
{
    super.viewDidLoad()

    oldPswdTextField.delegate = self
    newPswdTextField.delegate = self
    confirmPswdTextField.delegate = self
}
</code>```

////On back button click///////

```<code>func resignAllResponsers()
{
    if oldPswdTextField.isFirstResponder
    {
        oldPswdTextField.resignFirstResponder()
    }
    else if newPswdTextField.isFirstResponder
    {
        newPswdTextField.resignFirstResponder()
    }
    else if confirmPswdTextField.isFirstResponder
    {
        confirmPswdTextField.resignFirstResponder()
    }
}
</code>```

/////////////////

```<code>func textFieldShouldClear(_ textField: UITextField) -> Bool
{
    if textField.tag == 0
    {
        showPswdBtn.setImage(UIImage(named: "eyeClose.png"), for: UIControlState.normal)
    }
    else if textField.tag == 1
    {
        showNewPswdBtn.setImage(UIImage(named: "eyeClose.png"), for: UIControlState.normal)
    }

    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()
    return true;
}
</code>```

答:
I found the solution.
The problem was because ui alert controllers were dismissing wrongly. After made it correct, textField problem was sorted out.</p>

Title: Textfield does not detect touch

Body:
I found a weird problem in my iOS application written in Swift. Sometimes textfield does not work ie textfield does not detect touch and keyboard is not showing. All the textfields in every viewControllers suddenly stops working. Help is much appreciated thank you.

Edit: Adding some code

 override func viewDidLoad()
{
    super.viewDidLoad()

    oldPswdTextField.delegate = self
    newPswdTextField.delegate = self
    confirmPswdTextField.delegate = self
}

////On back button click///////

func resignAllResponsers()
{
    if oldPswdTextField.isFirstResponder
    {
        oldPswdTextField.resignFirstResponder()
    }
    else if newPswdTextField.isFirstResponder
    {
        newPswdTextField.resignFirstResponder()
    }
    else if confirmPswdTextField.isFirstResponder
    {
        confirmPswdTextField.resignFirstResponder()
    }
}

/////////////////

func textFieldShouldClear(_ textField: UITextField) -> Bool
{
    if textField.tag == 0
    {
        showPswdBtn.setImage(UIImage(named: "eyeClose.png"), for: UIControlState.normal)
    }
    else if textField.tag == 1
    {
        showNewPswdBtn.setImage(UIImage(named: "eyeClose.png"), for: UIControlState.normal)
    }

    return true
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    textField.resignFirstResponder()
    return true;
}


问:
image_dim_ordering - what am I missing here?
EDIT: Could not reproduce this issue using cuda 8.0 and using titan X (Pascal)

Using tensorflow backend for keras I have issues that are related to image_dim_ordering.
When I use image_dim_ordering='th' in the keras config file, everything works well But when I use 'tf', training simply doesn't really improve much from 0.5 accuracy.

The motivation is that currently my live augmentations are very costly, and I'd love to remove the unneeded reshape from theano dim order convention to tensorflow.

I tried recreating the issue with simple  code to allow reproduction by other people which may assist me to  understand what am I doing wrong here. I'm well aware of the channel,height,width different conventions, and at least I think that I handle that.

While I didn't fully reproduce my problem in the compact example (maybe because it's a trivial task), the training results are repeatedly different, and much worse for the 'tf' case, even when I try different seed values.
Note - in this reproducing code, all that the network needs to do is to tell apart full patches of -1.0 from full patches of 1.0

This is my '~/.keras/keras.json'

```<code>{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_dim_ordering": "th"
}
</code>```

my tensorflow version is ''0.11.0rc0'' (it happened on 0,10 as well)
my keras is latest git pull of today.

Using 'th' for the image_dim_ordering I get accuracy >=0.99 at epoch 4 for three different seeds.
Using 'tf' for the dim order I get accuracy >= 0.9 much latest as you can see below in the log, only at around epoch 24

The following is a standalone code that should reproduce the problem:

```<code>from keras import backend as K
import keras.optimizers
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, Input
from keras.models import Model
import numpy as np

def make_model(input_dim_size):
    if K.image_dim_ordering() == 'tf':
        input_shape = (input_dim_size, input_dim_size,1)
    else:
        input_shape = (1, input_dim_size, input_dim_size)
    img_input = Input(shape=input_shape)

    x = Convolution2D(64,5,5,border_mode='same')(img_input)
    x = Activation('relu')(x)
    x = MaxPooling2D((2,2),strides=(2,2))(x)

    x = Convolution2D(64, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(64, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(128, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(128, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Flatten()(x)
    x = Dense(1024*2)(x)
    x = Activation('relu')(x)
    x = Dropout(0.5)(x)

    x = Dense(1024 * 2)(x)
    x = Activation('relu')(x)
    x = Dropout(0.75)(x)

    x = Dense(200)(x)
    x = Activation('relu')(x)
    x = Dropout(0.75)(x)

    x = Dense(1,activation='sigmoid')(x)

    model = Model(img_input, x)

    learning_rate = 0.01

    sgd = keras.optimizers.sgd(lr=learning_rate, momentum=0.9, nesterov=True)

    model.summary()

    model.compile(loss='binary_crossentropy',
                  optimizer=sgd,
                  metrics=['accuracy']
                  )
    return model

np.random.seed(456)

def dummy_generator(mini_batch_size=64, block_size=100):
    if K.image_dim_ordering() == 'tf':
        tensor_X_shape = (mini_batch_size,block_size, block_size,1)
    else:
        tensor_X_shape = (mini_batch_size, 1, block_size, block_size)

    X = np.zeros(tensor_X_shape, dtype=np.float32)
    y = np.zeros((mini_batch_size, 1))

    while True:
        for b in range(mini_batch_size):
            X[b, :, :, :] = (float(b % 2) * 2.0) - 1.0
            y[b, :] = float(b % 2)
        yield X,y

with K.tf.device('/gpu:2'):
    K.set_session(K.tf.Session(config=K.tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)))
    MINI_BATCH_SIZE = 64
    PATCH_SIZE = 100
    model = make_model(PATCH_SIZE)
    gen = dummy_generator(mini_batch_size=MINI_BATCH_SIZE,block_size=PATCH_SIZE)
    model.fit_generator(gen, MINI_BATCH_SIZE*10,
                        100, verbose=1,
                        callbacks=[],
                        validation_data=None,
                        nb_val_samples=None,
                        max_q_size=1,
                        nb_worker=1, pickle_safe=False)
</code>```

For the 'tf' case this is the training log: (and looks very similar on different seeds):

```<code>Epoch 1/100
640/640 [==============================] - 1s - loss: 0.6932 - acc: 0.4781
Epoch 2/100
640/640 [==============================] - 0s - loss: 0.6932 - acc: 0.4938
Epoch 3/100
640/640 [==============================] - 0s - loss: 0.6921 - acc: 0.5203
Epoch 4/100
640/640 [==============================] - 0s - loss: 0.6920 - acc: 0.5469
Epoch 5/100
640/640 [==============================] - 0s - loss: 0.6935 - acc: 0.4875
Epoch 6/100
640/640 [==============================] - 0s - loss: 0.6941 - acc: 0.4969
Epoch 7/100
640/640 [==============================] - 0s - loss: 0.6937 - acc: 0.5047
Epoch 8/100
640/640 [==============================] - 0s - loss: 0.6931 - acc: 0.5312
Epoch 9/100
640/640 [==============================] - 0s - loss: 0.6923 - acc: 0.5250
Epoch 10/100
640/640 [==============================] - 0s - loss: 0.6929 - acc: 0.5281
Epoch 11/100
640/640 [==============================] - 0s - loss: 0.6934 - acc: 0.4953
Epoch 12/100
640/640 [==============================] - 0s - loss: 0.6918 - acc: 0.5234
Epoch 13/100
640/640 [==============================] - 0s - loss: 0.6930 - acc: 0.5125
Epoch 14/100
640/640 [==============================] - 0s - loss: 0.6939 - acc: 0.4797
Epoch 15/100
640/640 [==============================] - 0s - loss: 0.6936 - acc: 0.5047
Epoch 16/100
640/640 [==============================] - 0s - loss: 0.6917 - acc: 0.4922
Epoch 17/100
640/640 [==============================] - 0s - loss: 0.6945 - acc: 0.4891
Epoch 18/100
640/640 [==============================] - 0s - loss: 0.6948 - acc: 0.5000
Epoch 19/100
640/640 [==============================] - 0s - loss: 0.6968 - acc: 0.4594
Epoch 20/100
640/640 [==============================] - 0s - loss: 0.6919 - acc: 0.5391
Epoch 21/100
640/640 [==============================] - 0s - loss: 0.6904 - acc: 0.5172
Epoch 22/100
640/640 [==============================] - 0s - loss: 0.6881 - acc: 0.5906
Epoch 23/100
640/640 [==============================] - 0s - loss: 0.6804 - acc: 0.6359
Epoch 24/100
640/640 [==============================] - 0s - loss: 0.6470 - acc: 0.8219
Epoch 25/100
640/640 [==============================] - 0s - loss: 0.4134 - acc: 0.9625
Epoch 26/100
640/640 [==============================] - 0s - loss: 0.2347 - acc: 0.9953
Epoch 27/100
640/640 [==============================] - 0s - loss: 0.1231 - acc: 1.0000
</code>```

And for the 'th' case the training log is (and looks very similar on different seeds):

```<code>Epoch 1/100
640/640 [==============================] - 3s - loss: 0.6891 - acc: 0.5594
Epoch 2/100
640/640 [==============================] - 2s - loss: 0.6079 - acc: 0.7328
Epoch 3/100
640/640 [==============================] - 2s - loss: 0.3166 - acc: 0.9422
Epoch 4/100
640/640 [==============================] - 2s - loss: 0.1767 - acc: 0.9969
</code>```

I find it suspicious that it's so fast in the tensorflow case, (0s), but after adding debug printing to the generator it does seem to get called.
I thought that maybe it's related to keras not needing to reshape anything, but 2-3 seconds sounds too much time for this amount of reshapes

If anyone can try to reproduce the results that I see and help me understand what the heck am I missing here, I'd be grateful :)

答:
This thread is bit old but I am still replying in case someone faces the same issues.

The error is caused due to the inconsistent Keras backend configuration...

```<code>{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_dim_ordering": "th"
}
</code>```

The configuration uses tensorflow as backend but uses image dimension ordering of Theano instead of tensorflow. change image_dim_ordering to tf and that should solve the issue..

```<code>"image_dim_ordering": "tf"
</code>```

Body:
EDIT: Could not reproduce this issue using cuda 8.0 and using titan X (Pascal)

Using tensorflow backend for keras I have issues that are related to image_dim_ordering.
When I use image_dim_ordering='th' in the keras config file, everything works well But when I use 'tf', training simply doesn't really improve much from 0.5 accuracy.

The motivation is that currently my live augmentations are very costly, and I'd love to remove the unneeded reshape from theano dim order convention to tensorflow.

I tried recreating the issue with simple  code to allow reproduction by other people which may assist me to  understand what am I doing wrong here. I'm well aware of the channel,height,width different conventions, and at least I think that I handle that.

While I didn't fully reproduce my problem in the compact example (maybe because it's a trivial task), the training results are repeatedly different, and much worse for the 'tf' case, even when I try different seed values.
Note - in this reproducing code, all that the network needs to do is to tell apart full patches of -1.0 from full patches of 1.0

This is my '~/.keras/keras.json'

{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_dim_ordering": "th"
}

my tensorflow version is ''0.11.0rc0'' (it happened on 0,10 as well)
my keras is latest git pull of today.

Using 'th' for the image_dim_ordering I get accuracy >=0.99 at epoch 4 for three different seeds.
Using 'tf' for the dim order I get accuracy >= 0.9 much latest as you can see below in the log, only at around epoch 24

The following is a standalone code that should reproduce the problem:

from keras import backend as K
import keras.optimizers
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense, Input
from keras.models import Model
import numpy as np

def make_model(input_dim_size):
    if K.image_dim_ordering() == 'tf':
        input_shape = (input_dim_size, input_dim_size,1)
    else:
        input_shape = (1, input_dim_size, input_dim_size)
    img_input = Input(shape=input_shape)

    x = Convolution2D(64,5,5,border_mode='same')(img_input)
    x = Activation('relu')(x)
    x = MaxPooling2D((2,2),strides=(2,2))(x)

    x = Convolution2D(64, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(64, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(128, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Convolution2D(128, 5, 5, border_mode='same')(x)
    x = Activation('relu')(x)
    x = MaxPooling2D((2, 2), strides=(2, 2))(x)

    x = Flatten()(x)
    x = Dense(1024*2)(x)
    x = Activation('relu')(x)
    x = Dropout(0.5)(x)

    x = Dense(1024 * 2)(x)
    x = Activation('relu')(x)
    x = Dropout(0.75)(x)

    x = Dense(200)(x)
    x = Activation('relu')(x)
    x = Dropout(0.75)(x)

    x = Dense(1,activation='sigmoid')(x)

    model = Model(img_input, x)

    learning_rate = 0.01

    sgd = keras.optimizers.sgd(lr=learning_rate, momentum=0.9, nesterov=True)

    model.summary()

    model.compile(loss='binary_crossentropy',
                  optimizer=sgd,
                  metrics=['accuracy']
                  )
    return model

np.random.seed(456)

def dummy_generator(mini_batch_size=64, block_size=100):
    if K.image_dim_ordering() == 'tf':
        tensor_X_shape = (mini_batch_size,block_size, block_size,1)
    else:
        tensor_X_shape = (mini_batch_size, 1, block_size, block_size)

    X = np.zeros(tensor_X_shape, dtype=np.float32)
    y = np.zeros((mini_batch_size, 1))

    while True:
        for b in range(mini_batch_size):
            X[b, :, :, :] = (float(b % 2) * 2.0) - 1.0
            y[b, :] = float(b % 2)
        yield X,y

with K.tf.device('/gpu:2'):
    K.set_session(K.tf.Session(config=K.tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)))
    MINI_BATCH_SIZE = 64
    PATCH_SIZE = 100
    model = make_model(PATCH_SIZE)
    gen = dummy_generator(mini_batch_size=MINI_BATCH_SIZE,block_size=PATCH_SIZE)
    model.fit_generator(gen, MINI_BATCH_SIZE*10,
                        100, verbose=1,
                        callbacks=[],
                        validation_data=None,
                        nb_val_samples=None,
                        max_q_size=1,
                        nb_worker=1, pickle_safe=False)

For the 'tf' case this is the training log: (and looks very similar on different seeds):

Epoch 1/100
640/640 [==============================] - 1s - loss: 0.6932 - acc: 0.4781
Epoch 2/100
640/640 [==============================] - 0s - loss: 0.6932 - acc: 0.4938
Epoch 3/100
640/640 [==============================] - 0s - loss: 0.6921 - acc: 0.5203
Epoch 4/100
640/640 [==============================] - 0s - loss: 0.6920 - acc: 0.5469
Epoch 5/100
640/640 [==============================] - 0s - loss: 0.6935 - acc: 0.4875
Epoch 6/100
640/640 [==============================] - 0s - loss: 0.6941 - acc: 0.4969
Epoch 7/100
640/640 [==============================] - 0s - loss: 0.6937 - acc: 0.5047
Epoch 8/100
640/640 [==============================] - 0s - loss: 0.6931 - acc: 0.5312
Epoch 9/100
640/640 [==============================] - 0s - loss: 0.6923 - acc: 0.5250
Epoch 10/100
640/640 [==============================] - 0s - loss: 0.6929 - acc: 0.5281
Epoch 11/100
640/640 [==============================] - 0s - loss: 0.6934 - acc: 0.4953
Epoch 12/100
640/640 [==============================] - 0s - loss: 0.6918 - acc: 0.5234
Epoch 13/100
640/640 [==============================] - 0s - loss: 0.6930 - acc: 0.5125
Epoch 14/100
640/640 [==============================] - 0s - loss: 0.6939 - acc: 0.4797
Epoch 15/100
640/640 [==============================] - 0s - loss: 0.6936 - acc: 0.5047
Epoch 16/100
640/640 [==============================] - 0s - loss: 0.6917 - acc: 0.4922
Epoch 17/100
640/640 [==============================] - 0s - loss: 0.6945 - acc: 0.4891
Epoch 18/100
640/640 [==============================] - 0s - loss: 0.6948 - acc: 0.5000
Epoch 19/100
640/640 [==============================] - 0s - loss: 0.6968 - acc: 0.4594
Epoch 20/100
640/640 [==============================] - 0s - loss: 0.6919 - acc: 0.5391
Epoch 21/100
640/640 [==============================] - 0s - loss: 0.6904 - acc: 0.5172
Epoch 22/100
640/640 [==============================] - 0s - loss: 0.6881 - acc: 0.5906
Epoch 23/100
640/640 [==============================] - 0s - loss: 0.6804 - acc: 0.6359
Epoch 24/100
640/640 [==============================] - 0s - loss: 0.6470 - acc: 0.8219
Epoch 25/100
640/640 [==============================] - 0s - loss: 0.4134 - acc: 0.9625
Epoch 26/100
640/640 [==============================] - 0s - loss: 0.2347 - acc: 0.9953
Epoch 27/100
640/640 [==============================] - 0s - loss: 0.1231 - acc: 1.0000

And for the 'th' case the training log is (and looks very similar on different seeds):

Epoch 1/100
640/640 [==============================] - 3s - loss: 0.6891 - acc: 0.5594
Epoch 2/100
640/640 [==============================] - 2s - loss: 0.6079 - acc: 0.7328
Epoch 3/100
640/640 [==============================] - 2s - loss: 0.3166 - acc: 0.9422
Epoch 4/100
640/640 [==============================] - 2s - loss: 0.1767 - acc: 0.9969

I find it suspicious that it's so fast in the tensorflow case, (0s), but after adding debug printing to the generator it does seem to get called.
I thought that maybe it's related to keras not needing to reshape anything, but 2-3 seconds sounds too much time for this amount of reshapes

If anyone can try to reproduce the results that I see and help me understand what the heck am I missing here, I'd be grateful :)

Body:
This thread is bit old but I am still replying in case someone faces the same issues.

The error is caused due to the inconsistent Keras backend configuration...

{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_dim_ordering": "th"
}

The configuration uses tensorflow as backend but uses image dimension ordering of Theano instead of tensorflow. change image_dim_ordering to tf and that should solve the issue..

"image_dim_ordering": "tf"


问:
Laravel Mail Send Attach Wrong Encoding
Im sending a csv attachement file, but laravel send the csv with wrong encoding when someone opens the email.

In my case since is in portuguese language the csv file have special charecters like ã, ç, ão. €,..

Example code:
```</p>

```class MailCron extends Mailable
{
    use Queueable, SerializesModels;

    public $csv;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($csv)
    {
        $this->csv = $csv;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {

        return $this->from('info@domain.com')
            ->view('mail.leads')
            ->attach($this->csv->store("csv",false,true)['full']);

    }
}
```

答:
This should set the headers in the mail:

```<code>public function build()
{
    $this->withSwiftMessage(function (\Swift_Message $message) {
        $message->getHeaders()
            ->addTextHeader('Content-Type', 'text/plain; charset=utf-8');
    });

    return $this->from('info@domain.com')
        ->view('mail.leads')
        ->attach($this->csv->store("csv",false,true)['full']);
}
</code>```

Be sure to check with header text/plain and text/html.

Title: Laravel Mail Send Attach Wrong Encoding

Body:
Im sending a csv attachement file, but laravel send the csv with wrong encoding when someone opens the email.

In my case since is in portuguese language the csv file have special charecters like ã, ç, ão. €,..

Example code:
```

class MailCron extends Mailable
{
    use Queueable, SerializesModels;

    public $csv;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($csv)
    {
        $this->csv = $csv;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {

        return $this->from('info@domain.com')
            ->view('mail.leads')
            ->attach($this->csv->store("csv",false,true)['full']);

    }
}

Body:
This should set the headers in the mail:

public function build()
{
    $this->withSwiftMessage(function (\Swift_Message $message) {
        $message->getHeaders()
            ->addTextHeader('Content-Type', 'text/plain; charset=utf-8');
    });

    return $this->from('info@domain.com')
        ->view('mail.leads')
        ->attach($this->csv->store("csv",false,true)['full']);
}

Be sure to check with header text/plain and text/html.


问:
How to pass JMX JVM options to Hadoop Mapper and Reducer
I'd like to turn on JMX for all my Hadoop mappers and reducers.

To do so, I need to add the following options as JVM options to the mapper/reducer JVMs:

```<code>-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=0
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
</code>```

How can I do this from the Hadoop command line?

I know I can add JVM options to the mapper/reducer by adding:

-D mapreduce.map.java.opts=<an option> -D mapreduce.reduce.java.opts=<an option>

and that will pass <an option> to the JVMs.

How do I add the entire JMX options list from above. Will the following work?

```<code>-D mapreduce.map.java.opts="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=0 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false" -D mapreduce.reduce.java.opts="<same as for map>"
</code>```

I couldn't find any documentation or examples with helpful information.

答:
Yes.

If you run the command from the question, it will add all the properties to the mapper/reducer JVM.

Body:
I'd like to turn on JMX for all my Hadoop mappers and reducers.

To do so, I need to add the following options as JVM options to the mapper/reducer JVMs:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=0
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

How can I do this from the Hadoop command line?

I know I can add JVM options to the mapper/reducer by adding:

-D mapreduce.map.java.opts=<an option> -D mapreduce.reduce.java.opts=<an option>

and that will pass <an option> to the JVMs.

How do I add the entire JMX options list from above. Will the following work?

-D mapreduce.map.java.opts="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=0 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false" -D mapreduce.reduce.java.opts="<same as for map>"

I couldn't find any documentation or examples with helpful information.


问:
What's C#'s await equivalent in javascript/jquery?
I'm using a jQuery library called bootbox

```<code>bootbox.dialog({
    title: "Group",
    buttons: {
        success: {
            label: "OK",
            className: "btn-success",
            callback: function () {
                postForm();
            }
        }
    }
});

function postForm() {
    $.ajax({
        type: "POST",
        url: $("#add-group").val(),
        data: $("#form").serialize(),
        success: function (data) {
            return true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            return false;
        }
    });
}
</code>```

When I click on the "OK" button, unless I return a false value like this:

```<code>callback: function () {
    return false;
}
</code>```

the dialog will close.

In the callback function, I'm calling postForm which is a function that makes an AJAX call to my server side to perform some operation. Depending on the outcome of that operation, I would like to keep the dialog still open.

But because it's an AJAX call, and the result takes a while to come back, the dialog closes immediately after postForm() regardless of my result.

How can I tell javascript to await for the result of the ajax call?

It'll be great if I can do something like this:

```<code>callback: function () {
    var result = await postForm();
    return result;
}
</code>```

答:
With the advent of ES2017, the answer to this question is async/await.

It's THE JS solution for “callback hell”.
Promise is the equivalent to System.Threading.Tasks.Task.
You can await a Promise in an async function.

Unlike in C#, there is no way to call an async-function in a synchronous function.

So you can await a Promise in an async function, and ONLY in an async-function.

```<code>async function foo()
{
     return 123;
}

let result = await foo();
console.log(result)
</code>```

You can use TypeScript or babel to transpile async/await back to ES5 (while IE11 exists).

There's a promise polyfill for IE11.

See ECMA-draft 262 or MDN for closer information.

A good example of promise is the FETCH api.

The fetch-API is good for async/await ajax requests.

Why ? Because if you have to promisify XmlHttpRequest, it looks like this:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta http-equiv="Content-Language" content="en" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <meta name="google" value="notranslate" />

    <!--
    <meta name="author" content="name" />
    <meta name="description" content="description here" />
    <meta name="keywords" content="keywords,here" />

    <link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
    <link rel="stylesheet" href="stylesheet.css" type="text/css" />
    -->

    <title>Title</title>

    <style type="text/css" media="all">
        body
        {
            background-color: #0c70b4;
            color: #546775;
            font: normal 400 18px "PT Sans", sans-serif;
            -webkit-font-smoothing: antialiased;
        }
    </style>

    <script type="text/javascript">
        <!--
        // http://localhost:57566/foobar/ajax/json.ashx

        var ajax = {};
        ajax.x = function () {
            if (typeof XMLHttpRequest !== 'undefined') {
                return new XMLHttpRequest();
            }
            var versions = [
                "MSXML2.XmlHttp.6.0",
                "MSXML2.XmlHttp.5.0",
                "MSXML2.XmlHttp.4.0",
                "MSXML2.XmlHttp.3.0",
                "MSXML2.XmlHttp.2.0",
                "Microsoft.XmlHttp"
            ];

            var xhr;
            for (var i = 0; i < versions.length; i++) {
                try {
                    xhr = new ActiveXObject(versions[i]);
                    break;
                } catch (e) {
                }
            }
            return xhr;
        };

        ajax.send = function (url, callback, method, data, async) {
            if (async === undefined)
            {
                async = true;
            }

            var x = ajax.x();
            x.open(method, url, async);
            x.onreadystatechange = function () {
                if (x.readyState == 4) {
                    callback(x.responseText)
                }
            };
            if (method == 'POST') {
                x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            }
            x.send(data)
        };

        ajax.get = function (url, data, callback, async) {
            var query = [];
            for (var key in data) {
                query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
            ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
        };

        ajax.post = function (url, data, callback, async) {
            var query = [];
            for (var key in data) {
                query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
            ajax.send(url, callback, 'POST', query.join('&'), async)
        };

        ///////////

        function testAjaxCall() {
            ajax.get("./ajax/json.ashx", null, function (bError, strMessage, iStatus)
                {
                    console.log("args:", arguments);

                    console.log("Error:", bError);
                    console.log("Message:", strMessage);
                    console.log("Status:", iStatus);
                }
                , true
            );

        }
        -->
    </script>

</head>
<body>

    <script type="text/javascript">

        function ajaxGet(url, data)
        {
            var result;

            return new Promise(function (resolve, reject)
                {

                    ajax.get(url, data, function (bError, strMessage, iStatus)
                        {

                            // console.log("args:", arguments);

                            // console.log("Error:", bError);
                            // console.log("Message:", strMessage);
                            // console.log("Status:", iStatus);

                            result = bError;
                            resolve(result);
                        }
                        ,true
                    );

                }
            );

        }

        async function main()
        {
            var ajaxResult = await ajaxGet("./ajax/json.ashx");
            console.log("ajaxResult: ", ajaxResult);
        }

        async function lol()
        {
            var res = null;

            var myPromise = new Promise(function (resolve, reject)
            {
                // Standard AJAX request setup and load.
                var request = new XMLHttpRequest();

                // Request a user's comment from our fake blog.
                request.open('GET', 'https://localhost:57566/ajax/json.ashx');

                /*
                // Set function to call when resource is loaded.
                // Onload same as onreadystatechange - onload added with XHR2
                request.onload = function ()
                {
                    // internal server error/404
                    if (request.status === 200)
                    {
                        res = request.response;
                        // console.log(request.response);
                        console.log("onload- resolving promise");
                        resolve(request.response);
                    } else
                    {
                        console.log("onload- rejectinv promise");
                        reject('Page loaded, but status not OK.');
                    }
                };
                */

                request.onreadystatechange = function ()
                {
                    console.log("readystate:", request.readyState);
                    console.log("status:", request.status)

                    if (request.readyState != 4) return;

                    // XMLHttpRequest.DONE = 200, 0=cancelled 304 = redirect
                    //if (!(request.status != 200 && request.status != 304 && request.status != 0))
                    if (request.status === 200)
                    {
                        console.log("successy")
                        resolve(request.responseText); // Success
                        return;
                    }

                    if (request.status != 200 && request.status != 0 && request.status != 304)
                    {
                        console.log('HTTP error ' + request.status);
                        // reject('Page loaded, but status not OK.');
                        reject(new Error("Server error - Status NOK", "filename", "linenum666")); // Error
                        return;
                    }

                    if (request.status === 0)
                    {
                        console.log("cancelled:", request)
                        //resolve(null); // Cancelled, HTTPS protocol error
                        return;
                    }

                    reject(new Error("Strange error", "filename", "linenum666")); // Some Error
                };

                // Set function to call when loading fails.
                request.onerror = function ()
                {
                    // Cannot connect
                    console.log("OMG OnError");
                    // reject('Aww, didn\'t work at all. Network connectivity issue.');
                    reject(new Error("Aww, didn\'t work at all. Network connectivity issue.", "filename", "linenum666")); // Some Error

                };

                if (!navigator.onLine)
                {
                    console.log("No internet connection");
                    reject("No internet connection");
                }
                else
                {
                    try
                    {
                        request.send();
                    }
                    catch (ex)
                    {
                        console.log("send", ex.message, ex);
                    }
                }

            });

            return myPromise;
        }

        async function autorun()
        {
            console.clear();
            // await main();

            try
            {
                var resp = await lol();
                console.log("resp:", resp);
            }
            catch (ex)
            {
                console.log("foo", ex.message, ex);
            }

            console.log("I am here !");
        }

        if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
        else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
        else window.onload = autorun;
    </script>

</body>
</html>
</code>```

Body:
I'm using a jQuery library called bootbox

bootbox.dialog({
    title: "Group",
    buttons: {
        success: {
            label: "OK",
            className: "btn-success",
            callback: function () {
                postForm();
            }
        }
    }
});

function postForm() {
    $.ajax({
        type: "POST",
        url: $("#add-group").val(),
        data: $("#form").serialize(),
        success: function (data) {
            return true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            return false;
        }
    });
}

When I click on the "OK" button, unless I return a false value like this:

callback: function () {
    return false;
}

the dialog will close.

In the callback function, I'm calling postForm which is a function that makes an AJAX call to my server side to perform some operation. Depending on the outcome of that operation, I would like to keep the dialog still open.

But because it's an AJAX call, and the result takes a while to come back, the dialog closes immediately after postForm() regardless of my result.

How can I tell javascript to await for the result of the ajax call?

It'll be great if I can do something like this:

callback: function () {
    var result = await postForm();
    return result;
}

Body:
With the advent of ES2017, the answer to this question is async/await.

It's THE JS solution for “callback hell”.
Promise is the equivalent to System.Threading.Tasks.Task.
You can await a Promise in an async function.

Unlike in C#, there is no way to call an async-function in a synchronous function.

So you can await a Promise in an async function, and ONLY in an async-function.

async function foo()
{
     return 123;
}

let result = await foo();
console.log(result)

You can use TypeScript or babel to transpile async/await back to ES5 (while IE11 exists).

There's a promise polyfill for IE11.

See ECMA-draft 262 or MDN for closer information.

A good example of promise is the FETCH api.

The fetch-API is good for async/await ajax requests.

Why ? Because if you have to promisify XmlHttpRequest, it looks like this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <meta http-equiv="cache-control" content="max-age=0" />
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="expires" content="0" />
    <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
    <meta http-equiv="pragma" content="no-cache" />

    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta http-equiv="Content-Language" content="en" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />

    <meta name="google" value="notranslate" />

    <!--
    <meta name="author" content="name" />
    <meta name="description" content="description here" />
    <meta name="keywords" content="keywords,here" />

    <link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon" />
    <link rel="stylesheet" href="stylesheet.css" type="text/css" />
    -->

    <title>Title</title>

    <style type="text/css" media="all">
        body
        {
            background-color: #0c70b4;
            color: #546775;
            font: normal 400 18px "PT Sans", sans-serif;
            -webkit-font-smoothing: antialiased;
        }
    </style>

    <script type="text/javascript">
        <!--
        // http://localhost:57566/foobar/ajax/json.ashx

        var ajax = {};
        ajax.x = function () {
            if (typeof XMLHttpRequest !== 'undefined') {
                return new XMLHttpRequest();
            }
            var versions = [
                "MSXML2.XmlHttp.6.0",
                "MSXML2.XmlHttp.5.0",
                "MSXML2.XmlHttp.4.0",
                "MSXML2.XmlHttp.3.0",
                "MSXML2.XmlHttp.2.0",
                "Microsoft.XmlHttp"
            ];

            var xhr;
            for (var i = 0; i < versions.length; i++) {
                try {
                    xhr = new ActiveXObject(versions[i]);
                    break;
                } catch (e) {
                }
            }
            return xhr;
        };

        ajax.send = function (url, callback, method, data, async) {
            if (async === undefined)
            {
                async = true;
            }

            var x = ajax.x();
            x.open(method, url, async);
            x.onreadystatechange = function () {
                if (x.readyState == 4) {
                    callback(x.responseText)
                }
            };
            if (method == 'POST') {
                x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            }
            x.send(data)
        };

        ajax.get = function (url, data, callback, async) {
            var query = [];
            for (var key in data) {
                query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
            ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
        };

        ajax.post = function (url, data, callback, async) {
            var query = [];
            for (var key in data) {
                query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
            ajax.send(url, callback, 'POST', query.join('&'), async)
        };

        ///////////

        function testAjaxCall() {
            ajax.get("./ajax/json.ashx", null, function (bError, strMessage, iStatus)
                {
                    console.log("args:", arguments);

                    console.log("Error:", bError);
                    console.log("Message:", strMessage);
                    console.log("Status:", iStatus);
                }
                , true
            );

        }
        -->
    </script>

</head>
<body>

    <script type="text/javascript">

        function ajaxGet(url, data)
        {
            var result;

            return new Promise(function (resolve, reject)
                {

                    ajax.get(url, data, function (bError, strMessage, iStatus)
                        {

                            // console.log("args:", arguments);

                            // console.log("Error:", bError);
                            // console.log("Message:", strMessage);
                            // console.log("Status:", iStatus);

                            result = bError;
                            resolve(result);
                        }
                        ,true
                    );

                }
            );

        }

        async function main()
        {
            var ajaxResult = await ajaxGet("./ajax/json.ashx");
            console.log("ajaxResult: ", ajaxResult);
        }

        async function lol()
        {
            var res = null;

            var myPromise = new Promise(function (resolve, reject)
            {
                // Standard AJAX request setup and load.
                var request = new XMLHttpRequest();

                // Request a user's comment from our fake blog.
                request.open('GET', 'https://localhost:57566/ajax/json.ashx');

                /*
                // Set function to call when resource is loaded.
                // Onload same as onreadystatechange - onload added with XHR2
                request.onload = function ()
                {
                    // internal server error/404
                    if (request.status === 200)
                    {
                        res = request.response;
                        // console.log(request.response);
                        console.log("onload- resolving promise");
                        resolve(request.response);
                    } else
                    {
                        console.log("onload- rejectinv promise");
                        reject('Page loaded, but status not OK.');
                    }
                };
                */

                request.onreadystatechange = function ()
                {
                    console.log("readystate:", request.readyState);
                    console.log("status:", request.status)

                    if (request.readyState != 4) return;

                    // XMLHttpRequest.DONE = 200, 0=cancelled 304 = redirect
                    //if (!(request.status != 200 && request.status != 304 && request.status != 0))
                    if (request.status === 200)
                    {
                        console.log("successy")
                        resolve(request.responseText); // Success
                        return;
                    }

                    if (request.status != 200 && request.status != 0 && request.status != 304)
                    {
                        console.log('HTTP error ' + request.status);
                        // reject('Page loaded, but status not OK.');
                        reject(new Error("Server error - Status NOK", "filename", "linenum666")); // Error
                        return;
                    }

                    if (request.status === 0)
                    {
                        console.log("cancelled:", request)
                        //resolve(null); // Cancelled, HTTPS protocol error
                        return;
                    }

                    reject(new Error("Strange error", "filename", "linenum666")); // Some Error
                };

                // Set function to call when loading fails.
                request.onerror = function ()
                {
                    // Cannot connect
                    console.log("OMG OnError");
                    // reject('Aww, didn\'t work at all. Network connectivity issue.');
                    reject(new Error("Aww, didn\'t work at all. Network connectivity issue.", "filename", "linenum666")); // Some Error

                };

                if (!navigator.onLine)
                {
                    console.log("No internet connection");
                    reject("No internet connection");
                }
                else
                {
                    try
                    {
                        request.send();
                    }
                    catch (ex)
                    {
                        console.log("send", ex.message, ex);
                    }
                }

            });

            return myPromise;
        }

        async function autorun()
        {
            console.clear();
            // await main();

            try
            {
                var resp = await lol();
                console.log("resp:", resp);
            }
            catch (ex)
            {
                console.log("foo", ex.message, ex);
            }

            console.log("I am here !");
        }

        if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
        else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
        else window.onload = autorun;
    </script>

</body>
</html>

ContentLicense: CC BY-SA 4.0


问:
Laravel: Auth::user()->role_id in app.blade.php display Trying to get property of non-object
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

```<code><ul class="nav navbar-nav">
   @if(Auth::user()->role_id == 1)
    <li><a href="{!! url('/admin/users'); !!}">Users</a></li>
   @endif
</ul>
</code>```

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

```<code><?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }
</code>```

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

答:
You can add this code in your index() method in AdminUsersController:

```<code> public function __construct()
 {
     // user must log in to use this controller
     $this->middleware('auth');
 }

 public function index()
 {
    $users = User::paginate(5);

    if(Auth::check()){
       $roldId = Auth::user()->role_id;
       if($roldId !== 1) {
           return redirect('/home');
       }
    }

    return view('admin.users.index', compact('users'));
 }
</code>```

It works for me and I hope it will work for you too.

Body:
In my users table I add role_id column where 1 is admin and 2 is user. So, when I want to his page in header in my app.blade.php file like this:

   @if(Auth::user()->role_id == 1)

Users

   @endif

error appear:
(3/3) ErrorException
The use statement with non-compound name 'Auth' has no effect (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php) (View: C:\xampp\htdocs\vendetta\resources\views\layouts\app.blade.php)

index() method in AdminUsersController looks like this:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Role;
use App\Http\Requests\UserCreateRequest;
use App\Http\Requests\UserUpdateRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Auth;

class AdminUsersController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::paginate(5);

        if(Auth::user()->role_id !== 1) {
            return redirect('/home');
        }

        return view('admin.users.index', compact('users'));
    }

When I use check() instead of user()->role_id == 1, It works but then all users can see except one that not login, but I want to see only admin.

I cannot find the answer in similar topics...

Body:
You can add this code in your index() method in AdminUsersController:

 public function __construct()
 {
     // user must log in to use this controller
     $this->middleware('auth');
 }

 public function index()
 {
    $users = User::paginate(5);

    if(Auth::check()){
       $roldId = Auth::user()->role_id;
       if($roldId !== 1) {
           return redirect('/home');
       }
    }

    return view('admin.users.index', compact('users'));
 }

It works for me and I hope it will work for you too.


答: ActivePerl is a good Windows Perl interpreter</p>

Title: Perl in Windows Vista 32bit?

Body:
I want to practice Perl in Windows Vista 32bit, how can I do it ?

Thanks.


问:
pass a list by reference in R function
I have a simple recursion function in R that would modify its input arguments. I use eval.parent(substitute()) in order to apply the changes on the arguments, However I get this error:
"invalid (do_set) left-hand side to assignment "
Does anyone know how to fix this error?
Here is my function:</p>

```<code>decompose_clade=function(ind,Small_clades_ind,Remove_tips,Clades){
  Ch=Children(tree,ind)
  if(Ch[1]<length(tree$tip.label)){
    l=Remove_tips
    l=c(l,Ch[1])
    eval.parent(substitute(Remove_tips=l))
    print("tip added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)<4){
    s=Small_clades_ind
    s=c(s,Ch[1])
    eval.parent(substitute(Small_clades_ind=s))
    print("small clade added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)>80){
    decompose_clade(Ch[1],Small_clades_ind,Remove_tips,Clades)
    print("function calls again")
  }else{
   m=Clades
   m=c(m,Ch[1])
    eval.parent(substitute(Clades<-m))
    print("a clade added=")
    print(Ch[1])
  }

}
</code>```

答:
May be you can follow the following approach.

```<code>x <- 1
fn <- function() {
    x <<- 2
}
</code>```

Now x is 2.

Title: pass a list by reference in R function

Body:
I have a simple recursion function in R that would modify its input arguments. I use eval.parent(substitute()) in order to apply the changes on the arguments, However I get this error:
"invalid (do_set) left-hand side to assignment "
Does anyone know how to fix this error?
Here is my function:

decompose_clade=function(ind,Small_clades_ind,Remove_tips,Clades){
  Ch=Children(tree,ind)
  if(Ch[1]<length(tree$tip.label)){
    l=Remove_tips
    l=c(l,Ch[1])
    eval.parent(substitute(Remove_tips=l))
    print("tip added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)<4){
    s=Small_clades_ind
    s=c(s,Ch[1])
    eval.parent(substitute(Small_clades_ind=s))
    print("small clade added=")
    print(Ch[1])
  }else if(length(extract.clade(tree,Ch[1])$tip.label)>80){
    decompose_clade(Ch[1],Small_clades_ind,Remove_tips,Clades)
    print("function calls again")
  }else{
   m=Clades
   m=c(m,Ch[1])
    eval.parent(substitute(Clades<-m))
    print("a clade added=")
    print(Ch[1])
  }

}

Body:
May be you can follow the following approach.

x <- 1
fn <- function() {
    x <<- 2
}

Now x is 2.


问:
Why is require module in JavaScript not able to import the fs library?
The javascript code is as follows:

```<code>const fs = require('fs');

function init() {
     alert("Done!");
}

init();
</code>```

While executing the Javascript code, I am not able to get the alert Done! on my webpage. On further analysis I came to a conclusion that it is most probably because the require statement is not working (there was an alert when I commented the require statement). Why is it so?

答:
require is not available in the browser but is used in NodeJS. If you want to use it in your browser, you'll need a building tool like Browserify or Webpack.

By the way, the File System package is available in NodeJS only.

Body:
The javascript code is as follows:

const fs = require('fs');

function init() {
     alert("Done!");
}

init();

While executing the Javascript code, I am not able to get the alert Done! on my webpage. On further analysis I came to a conclusion that it is most probably because the require statement is not working (there was an alert when I commented the require statement). Why is it so?


问:
Pass function parameter of undefined type pointer
I have references to dynamically loaded dll's function. Before calling them I need to make universal function that compares they are not equal to null? How to define undefined type parameter in my case?

I do :

```<code>boolean canLoad(void value)
{
    if (!value)
    {
        LogIt("could not locate the function");
        return false;
    }
    else
        return true;
}
</code>```

But compiler is not happy about void .

答:
void means no type or for argument lists no arguments. If you want a generic pointer then that is void *.

But it's better to have templates instead as that will make it more type-safe.

Also it's better to be explicit (i.e. value == nullptr as the condition, though this is kind of subjective), and use proper standard types (what is boolean?)

Body:
I have references to dynamically loaded dll's function. Before calling them I need to make universal function that compares they are not equal to null? How to define undefined type parameter in my case?

I do :

boolean canLoad(void value)
{
    if (!value)
    {
        LogIt("could not locate the function");
        return false;
    }
    else
        return true;
}

But compiler is not happy about void .


问:
insert into table1 select * from another table2 , then delete the row from table2
I am trying to  insert rows into table1 select * from table2 and finally delete the rows from table2  using function in oracle sql developer. I am not getting how to do it.

follwing is my function:

```<code>create or replace FUNCTION DELETEROW(GODOWN_DIST_CODE IN
TEST_TABLE.GODOWN_DIST_CODE%TYPE)  return varchar2
AS
returned_value varchar2(50);
BEGIN
begin
INSERT INTO TEST_TABLE_BACKUP SELECT * FROM TEST_TABLE WHERE
GODOWN_DIST_CODE=GODOWN_DIST_CODE;
DELETE TEST_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

INSERT INTO NEW_TABLE_BACKUP SELECT * FROM NEW_TABLE WHERE GODOWN_DIST_CODE
= GODOWN_DIST_CODE;
DELETE FROM NEW_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

exception
 WHEN no_data_found THEN
      returned_value := '#';
end;
RETURN returned_value;
END;
</code>```

答:
Try this:-

```<code>CREATE OR REPLACE PROCEDURE TABLE2_TO_TABLE1
  IS
  BEGIN
    EXECUTE IMMEDIATE 'INSERT INTO TABLE1(
              Field1,
              Field2,
              Field3
              )
            SELECT Field1,
                  Field2,
                  Field3
                  FROM TABLE2';
    EXECUTE IMMEDIATE 'DELETE TABLE2 where rownum != 0';
 END TABLE2_TO_TABLE1;
</code>```

Execute Procedure

```<code>BEGIN
    TABLE2_TO_TABLE1;
END;
/
</code>```

Body:
I am trying to  insert rows into table1 select * from table2 and finally delete the rows from table2  using function in oracle sql developer. I am not getting how to do it.

follwing is my function:

create or replace FUNCTION DELETEROW(GODOWN_DIST_CODE IN
TEST_TABLE.GODOWN_DIST_CODE%TYPE)  return varchar2
AS
returned_value varchar2(50);
BEGIN
begin
INSERT INTO TEST_TABLE_BACKUP SELECT * FROM TEST_TABLE WHERE
GODOWN_DIST_CODE=GODOWN_DIST_CODE;
DELETE TEST_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

INSERT INTO NEW_TABLE_BACKUP SELECT * FROM NEW_TABLE WHERE GODOWN_DIST_CODE
= GODOWN_DIST_CODE;
DELETE FROM NEW_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

exception
 WHEN no_data_found THEN
      returned_value := '#';
end;
RETURN returned_value;
END;

Body:
Try this:-

CREATE OR REPLACE PROCEDURE TABLE2_TO_TABLE1
  IS
  BEGIN
    EXECUTE IMMEDIATE 'INSERT INTO TABLE1(
              Field1,
              Field2,
              Field3
              )
            SELECT Field1,
                  Field2,
                  Field3
                  FROM TABLE2';
    EXECUTE IMMEDIATE 'DELETE TABLE2 where rownum != 0';
 END TABLE2_TO_TABLE1;

Execute Procedure

BEGIN
    TABLE2_TO_TABLE1;
END;
/


问:
Jquery each with where clause or similar
I have this bit of code

```<code>newDocumentState.documents = jQuery.grep(newDocumentState.documents,
    item => item["documentId"] !== docToRemove.name);

    $.each(newDocumentState.documents), (index, value ) => {
    this.documentState.addDocument(new DocumentMeta(value.documentId));
    });
</code>```

I was wondering if I could have something like this or similar instead.

```<code>$.each(newDocumentState.documents.where(x => x.documentId !== docToRemove.name),
    (index, value ) => {
    this.documentState.addDocument(new DocumentMeta(value.documentId));
    });
</code>```

答:
According to the answers I received, I came up with this

```<code>   $.each(newDocumentState.documents.filter(obj => obj.documentId !== docToRemove.name),
                    (index, value) => {
                        this.documentState.addDocument(new DocumentMeta(value.documentId));
                    });
</code>```

It works. Tks.

Body:
I have this bit of code

newDocumentState.documents = jQuery.grep(newDocumentState.documents,
    item => item["documentId"] !== docToRemove.name);

    $.each(newDocumentState.documents), (index, value ) => {
    this.documentState.addDocument(new DocumentMeta(value.documentId));
    });

I was wondering if I could have something like this or similar instead.

$.each(newDocumentState.documents.where(x => x.documentId !== docToRemove.name),
    (index, value ) => {
    this.documentState.addDocument(new DocumentMeta(value.documentId));
    });

Body:
According to the answers I received, I came up with this

   $.each(newDocumentState.documents.filter(obj => obj.documentId !== docToRemove.name),
                    (index, value) => {
                        this.documentState.addDocument(new DocumentMeta(value.documentId));
                    });

It works. Tks.


问:
VBA - How can I give an error code based on the sum of my textbox values ina user form?
So I currently have a userform with 3 input boxes and a save button.
The three inputs have to be between 0.0 and 1.0, which is what I have done using the code below.

I now need the sum of those 3 inputs to equal 1. If the sum of those inputs is not equal to 1 I want to display an error message upon the click of the save button.

Really stuck on this and have tried a couple of different methods which havent worked.

Is there any way to do this?

```<code>Private Sub CommandButton1_Click()

Dim textbox1 As Integer
Dim textbox2 As Integer
Dim textbox3 As Integer

On Error GoTo errHandler
textbox1 = CInt(UserForm1.textbox1.Value)
If textbox1 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If

On Error GoTo errHandler
textbox2 = CInt(UserForm1.textbox2.Value)
If textbox2 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If
Exit Sub

On Error GoTo errHandler
textbox3 = CInt(UserForm1.textbox3.Value)
If textbox3 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If
Exit Sub
errHandler:
MsgBox Err.Description
End Sub
</code>```

答:
I took some liberties in answering your questions because I saw opportunities to improve your code versus just getting you to the answer. The code below should be easier to read/manage and I hope it will help you in writing better code in the future below. Code first, and then I will explain the process:

```<code>Private Sub CommandButton1_Click()

    Dim Inputs(1 To 3) As Variant
    Dim Total As Double

    ' It is better to anticipate errors (check the values that could cause an error) than it is to
    ' use a GoTo block that catches everything.
    ' On Error GoTo errHandler

    Inputs(1) = GetInputFromTextbox(UserForm1.textbox1)
    Inputs(2) = GetInputFromTextbox(UserForm1.textbox2)
    Inputs(3) = GetInputFromTextbox(UserForm1.textbox3)

    ' Handle the errors all in the same block (simply for readability)
    If IsEmpty(Inputs(1)) Then
        InvalidInput "Textbox1"
        UserForm1.Hide
    ElseIf IsEmpty(Inputs(2)) Then
        InvalidInput "Textbox2"
        UserForm1.Hide
    ElseIf IsEmpty(Inputs(3)) Then
        InvalidInput "Textbox3"
        UserForm1.Hide
    Else
        ' This will only execute if the three previous inputs are valid
        Total = Application.WorksheetFunction.Sum(Inputs)
        If Total <> 1 Then
            TotalInputsInvalid Total
        End If
    End If

End Sub

' Define the function as a variant so it can return a null value
' This is important since the user could enter a 0 value and the default return of
' the function, if defined as a numeric type, would be 0. This would, in turn, prevent error handling.
Private Function GetInputFromTextbox(ByVal InputMember As Object) As Variant
    If IsNumeric(InputMember.Value) Then
        If CDbl(InputMember.Value) < 1 Then
            GetInputFromTextbox = Round(CDbl(InputMember.Value), 2)
        End If
    End If

    ' Notice that, if the conditions for a valid input are not met, nothing happens.
    ' This allows us to handle errors within the calling routine.
End Function

' This will alert the user if the input given is invalid.
Private Sub InvalidInput(ByVal MemberName As String)
    MsgBox "There is an invalid input in " & MemberName & ". Please enter value between 0.0 and 1.0."
End Sub

Private Sub TotalInputsInvalid(ByVal TotalValue As Double)
    MsgBox "The total value of all inputs must equal 1. The current total is " & Round(TotalValue, 2) & ". Please adjust the inputs accordingly."
End Sub
</code>```

First of all, I have defined one variable for the input values. The main benefit to this is that your code is cleaner and makes more sense. Having variables such as Foo1, Foo2, Foo3, etc. makes your code a little bit messier. An array can make this process easier, especially if this application has to scale to accomodate more textboxes.

Also notice that, per YowE3k's suggestion, I have declared the array as an array of doubles, and likewise with Total. Doubles allow floating point precision whereas Longs and Integers only allow whole numbers (sidenote on this, never use Integer. Get in the habit of only using Longs for anything you would use an Int for).

Next, I have defined a function that gets the clean input from the textbox. This is a good habit to get into. Keep in mind that a copy-paste now inevitably means additional debugging/fixing time later. There are rare cases where is it somewhat unavoidable for the current circumstances, but more often than not a Function or Sub will do wonders.

In the case of the function I have defined, it first checks for a numeric input (avoiding the Type Mismatch error) and then checks to ensure the value is not greater than 1. If both of these conditions succeed then it returns the value (rounded to the second decimal place), else it returns nothing.

I use this function to get all three values, and then I test the validity of all three values in the same If/ElseIf block. This will ensure all three values are valid before performing the final check.

In the final check, it ensures that the total is equal to 1, and if it is then nothing happens. If it isn't, it alerts the user that the inputs are invalid.

The process here is to use functions to return values, and then to use logic to handle errors. This is far more effective than GoTo blocks, and it makes debugging code much easier (at least in my experience).

If you have any questions, please ask. Best of luck!

EDIT: Changed declaration of Inputs from Double to Variant. The Double type automatically sets the base values to 0 versus allowing Empty. This in turn prevents checking invalid values vs. zeroes. The Variant type fixes this.

Body:
So I currently have a userform with 3 input boxes and a save button.
The three inputs have to be between 0.0 and 1.0, which is what I have done using the code below.

I now need the sum of those 3 inputs to equal 1. If the sum of those inputs is not equal to 1 I want to display an error message upon the click of the save button.

Really stuck on this and have tried a couple of different methods which havent worked.

Is there any way to do this?

Private Sub CommandButton1_Click()

Dim textbox1 As Integer
Dim textbox2 As Integer
Dim textbox3 As Integer

On Error GoTo errHandler
textbox1 = CInt(UserForm1.textbox1.Value)
If textbox1 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If

On Error GoTo errHandler
textbox2 = CInt(UserForm1.textbox2.Value)
If textbox2 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If
Exit Sub

On Error GoTo errHandler
textbox3 = CInt(UserForm1.textbox3.Value)
If textbox3 > 1 Then
    MsgBox "Invalid Input, Please enter value between 0.0 and 1.0"
Else
    UserForm1.Hide
End If
Exit Sub
errHandler:
MsgBox Err.Description
End Sub

Body:
I took some liberties in answering your questions because I saw opportunities to improve your code versus just getting you to the answer. The code below should be easier to read/manage and I hope it will help you in writing better code in the future below. Code first, and then I will explain the process:

Private Sub CommandButton1_Click()

    Dim Inputs(1 To 3) As Variant
    Dim Total As Double

    ' It is better to anticipate errors (check the values that could cause an error) than it is to
    ' use a GoTo block that catches everything.
    ' On Error GoTo errHandler

    Inputs(1) = GetInputFromTextbox(UserForm1.textbox1)
    Inputs(2) = GetInputFromTextbox(UserForm1.textbox2)
    Inputs(3) = GetInputFromTextbox(UserForm1.textbox3)

    ' Handle the errors all in the same block (simply for readability)
    If IsEmpty(Inputs(1)) Then
        InvalidInput "Textbox1"
        UserForm1.Hide
    ElseIf IsEmpty(Inputs(2)) Then
        InvalidInput "Textbox2"
        UserForm1.Hide
    ElseIf IsEmpty(Inputs(3)) Then
        InvalidInput "Textbox3"
        UserForm1.Hide
    Else
        ' This will only execute if the three previous inputs are valid
        Total = Application.WorksheetFunction.Sum(Inputs)
        If Total <> 1 Then
            TotalInputsInvalid Total
        End If
    End If

End Sub

' Define the function as a variant so it can return a null value
' This is important since the user could enter a 0 value and the default return of
' the function, if defined as a numeric type, would be 0. This would, in turn, prevent error handling.
Private Function GetInputFromTextbox(ByVal InputMember As Object) As Variant
    If IsNumeric(InputMember.Value) Then
        If CDbl(InputMember.Value) < 1 Then
            GetInputFromTextbox = Round(CDbl(InputMember.Value), 2)
        End If
    End If

    ' Notice that, if the conditions for a valid input are not met, nothing happens.
    ' This allows us to handle errors within the calling routine.
End Function

' This will alert the user if the input given is invalid.
Private Sub InvalidInput(ByVal MemberName As String)
    MsgBox "There is an invalid input in " & MemberName & ". Please enter value between 0.0 and 1.0."
End Sub

Private Sub TotalInputsInvalid(ByVal TotalValue As Double)
    MsgBox "The total value of all inputs must equal 1. The current total is " & Round(TotalValue, 2) & ". Please adjust the inputs accordingly."
End Sub

First of all, I have defined one variable for the input values. The main benefit to this is that your code is cleaner and makes more sense. Having variables such as Foo1, Foo2, Foo3, etc. makes your code a little bit messier. An array can make this process easier, especially if this application has to scale to accomodate more textboxes.

Also notice that, per YowE3k's suggestion, I have declared the array as an array of doubles, and likewise with Total. Doubles allow floating point precision whereas Longs and Integers only allow whole numbers (sidenote on this, never use Integer. Get in the habit of only using Longs for anything you would use an Int for).

Next, I have defined a function that gets the clean input from the textbox. This is a good habit to get into. Keep in mind that a copy-paste now inevitably means additional debugging/fixing time later. There are rare cases where is it somewhat unavoidable for the current circumstances, but more often than not a Function or Sub will do wonders.

In the case of the function I have defined, it first checks for a numeric input (avoiding the Type Mismatch error) and then checks to ensure the value is not greater than 1. If both of these conditions succeed then it returns the value (rounded to the second decimal place), else it returns nothing.

I use this function to get all three values, and then I test the validity of all three values in the same If/ElseIf block. This will ensure all three values are valid before performing the final check.

In the final check, it ensures that the total is equal to 1, and if it is then nothing happens. If it isn't, it alerts the user that the inputs are invalid.

The process here is to use functions to return values, and then to use logic to handle errors. This is far more effective than GoTo blocks, and it makes debugging code much easier (at least in my experience).

If you have any questions, please ask. Best of luck!

EDIT: Changed declaration of Inputs from Double to Variant. The Double type automatically sets the base values to 0 versus allowing Empty. This in turn prevents checking invalid values vs. zeroes. The Variant type fixes this.


问:
Get screenshot on Windows with Python?
I am creating a Beta Testers reporting module so they can send in thier comments on my software, but I would like to have the option to include a screenshot with the report. How do I take a screenshot of the screen with Python on Windows? I have found several examples on Linux, but haven't had much luck on Windows.</p>

答:
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:

```<code>from mss import mss

with mss() as sct:
    sct.shot()
</code>```

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..

Title: Get screenshot on Windows with Python?

Body:
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:

from mss import mss

with mss() as sct:
    sct.shot()

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..


问:
How to get admin consent working both for Graph API endpoint and Outlook REST endpoint?
The objective : having a one time consent of an admin to be able to read all company mailboxes, using some functionalities of Graph API, and some of Outlook REST API (webhooks are more advanced)

Reading the Microsoft doc, it seems the best flow is "OAuth 2.0 client credentials grant".

My app is created through apps.microsoft.com, scopes are defined to access all mailboxes.

The admin connects to https://login.microsoftonline.com/common/adminconsent?client_id=XXX&redirect_uri=XXX.

Then I retrieve the token to https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token with grant_type=client_credentials&client_id=XX&client_secret=XX&scope=https://graph.microsoft.com/.default

The token is returned. Everything works perfectly with Microsoft Graph.

But when I retrieve a token, changing the scope to https://outlook.office.com/.default, I get a token which is refused for my query, with a 401 and a 'too weak token with strength 1 instead of 2'.

Where should we change the scopes ? Or should I have another authorization flow ?

Thanks

答:
The Outlook endpoint requires a token obtained with an X509 certificate credential, rather than a client secret, and it also requires a token with the proper audience (the aud parameter in the JWT). To get all this, you need to register the app in the Azure portal (portal.azure.com or manage.windowsazure.com) and upload your public key in the app registration's manifest. I have a sample that does this here: https://github.com/jasonjoh/outlook-fetch.

Unfortunately as it stands right now there's no way to add Outlook-specific scopes to the App registration portal (apps.dev.microsoft.com), making the Azure registration method necessary in this case.


问:
Reading text from image in Python Selenium
Is it possible to scrap text from image element, as in the picture:

Picture

I did everything else, but

```<code>Salzufer 16
10587 Berlin
</code>```

Is in the shape of an image?

I use Selenium webdriver and need to scrape data like Address,Contact,Branch of economic activity..

答:
Seems that the text that you are looking for is embedded in the "text" argument of the textRender.aspx file. You may consider to reverse engineer it.

Otherwise for more general purpose OCR you can use Google Vision APIs https://cloud.google.com/vision/

Body:
Is it possible to scrap text from image element, as in the picture:

Picture

I did everything else, but

Salzufer 16
10587 Berlin

Is in the shape of an image?

I use Selenium webdriver and need to scrape data like Address,Contact,Branch of economic activity..


问:
How do I change button text from "Choose an option" in Woocommerce?
How would I go about changing this PHP code to to change Choose an option based on the id of the select element in the Woocommerce plugin for WordPress? I believe I have found the correct PHP file in wc-template-function.php but my lack of PHP skills is holding me back. Here is what I have so far:

```<code>if ( ! function_exists( 'wc_dropdown_variation_attribute_options' ) ) {

    /**
     * Output a list of variation attributes for use in the cart forms.
     *
     * @param array $args
     * @since 2.4.0
     */
    function wc_dropdown_variation_attribute_options( $args = array() ) {
        $args = wp_parse_args( $args, array(
            'options'          => false,
            'attribute'        => false,
            'product'          => false,
            'selected'         => false,
            'name'             => '',
            'id'               => '',
            'class'            => '',
            'show_option_none' => __( 'Choose an option', 'woocommerce' ),
            'show_option_color' => __( 'Choose a color', 'woocommerce' ),
            'show_option_size' => __( 'Choose a size', 'woocommerce' )
        ) );

        $options   = $args['options'];
        $product   = $args['product'];
        $attribute = $args['attribute'];
        $name      = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
        $id        = $args['id'] ? $args['id'] : sanitize_title( $attribute );
        $class     = $args['class'];

        if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
            $attributes = $product->get_variation_attributes();
            $options    = $attributes[ $attribute ];
        }

        echo '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '">';

        if ( $args['show_option_none'] ) {
            echo '<option value="">' . esc_html( $args['show_option_none'] ) . '</option>';
        }
        if ( $args['$id_colors'] ) {
            echo '<option value="">' . esc_html( $args['show_option_color'] ) . '</option>';
        }
        if ( $args['$id_sizes'] ) {
            echo '<option value="">' . esc_html( $args['show_option_size'] ) . '</option>';
        }

        if ( ! empty( $options ) ) {
            if ( $product && taxonomy_exists( $attribute ) ) {
                // Get terms if this is a taxonomy - ordered. We need the names too.
                $terms = wc_get_product_terms( $product->id, $attribute, array( 'fields' => 'all' ) );

                foreach ( $terms as $term ) {
                    if ( in_array( $term->slug, $options ) ) {
                        echo '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
                    }
                }
            } else {
                foreach ( $options as $option ) {
                    // This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
                    $selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
                    echo '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
                }
            }
        }

        echo '</select>';
    }
}
</code>```

You can see where I tried to add show_option_color and show_option_size in to the array and then add if statements for them, but it doesn't seem to be working. I'm not sure how to reference the id of the select element and write the if statement based on if its is the correct select element.

Here is the HTML I'm trying to target.

```<code><select id="sizes" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a size</select>

<select id="colors" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a color</select>
</code>```

variable.php code lines 27 - 38:

```<code><?php foreach ( $attributes as $attribute_name => $options ) : ?>
                    <tr>
                        <td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
                        <td class="value">
                            <?php
                                $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
                                wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                                echo end( $attribute_keys ) === $attribute_name ? '<a class="reset_variations" href="#">' . __( 'Clear selection', 'woocommerce' ) . '</a>' : '';
                            ?>
                        </td>
                    </tr>
                <?php endforeach;?>
</code>```

答:
Updated code, made it for anyone still interested</p>

```<code>add_filter( 'woocommerce_dropdown_variation_attribute_options_args',
fix_option', 10 );
function fix_option( $args ) {
    $attr = get_taxonomy( $args['attribute'] );
    $label = $attr->labels->name;
    $fix = str_replace('Product', '', $label);
    $fix = strtolower($fix); /
    $args['show_option_none'] = apply_filters( 'the_title', 'Select a '.$fix );
}
</code>```

Body:
How would I go about changing this PHP code to to change Choose an option based on the id of the select element in the Woocommerce plugin for WordPress? I believe I have found the correct PHP file in wc-template-function.php but my lack of PHP skills is holding me back. Here is what I have so far:

if ( ! function_exists( 'wc_dropdown_variation_attribute_options' ) ) {

    /**
     * Output a list of variation attributes for use in the cart forms.
     *
     * @param array $args
     * @since 2.4.0
     */
    function wc_dropdown_variation_attribute_options( $args = array() ) {
        $args = wp_parse_args( $args, array(
            'options'          => false,
            'attribute'        => false,
            'product'          => false,
            'selected'         => false,
            'name'             => '',
            'id'               => '',
            'class'            => '',
            'show_option_none' => __( 'Choose an option', 'woocommerce' ),
            'show_option_color' => __( 'Choose a color', 'woocommerce' ),
            'show_option_size' => __( 'Choose a size', 'woocommerce' )
        ) );

        $options   = $args['options'];
        $product   = $args['product'];
        $attribute = $args['attribute'];
        $name      = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
        $id        = $args['id'] ? $args['id'] : sanitize_title( $attribute );
        $class     = $args['class'];

        if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
            $attributes = $product->get_variation_attributes();
            $options    = $attributes[ $attribute ];
        }

        echo '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '">';

        if ( $args['show_option_none'] ) {
            echo '<option value="">' . esc_html( $args['show_option_none'] ) . '</option>';
        }
        if ( $args['$id_colors'] ) {
            echo '<option value="">' . esc_html( $args['show_option_color'] ) . '</option>';
        }
        if ( $args['$id_sizes'] ) {
            echo '<option value="">' . esc_html( $args['show_option_size'] ) . '</option>';
        }

        if ( ! empty( $options ) ) {
            if ( $product && taxonomy_exists( $attribute ) ) {
                // Get terms if this is a taxonomy - ordered. We need the names too.
                $terms = wc_get_product_terms( $product->id, $attribute, array( 'fields' => 'all' ) );

                foreach ( $terms as $term ) {
                    if ( in_array( $term->slug, $options ) ) {
                        echo '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . apply_filters( 'woocommerce_variation_option_name', $term->name ) . '</option>';
                    }
                }
            } else {
                foreach ( $options as $option ) {
                    // This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
                    $selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
                    echo '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) ) . '</option>';
                }
            }
        }

        echo '</select>';
    }
}

You can see where I tried to add show_option_color and show_option_size in to the array and then add if statements for them, but it doesn't seem to be working. I'm not sure how to reference the id of the select element and write the if statement based on if its is the correct select element.

Here is the HTML I'm trying to target.

<select id="sizes" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a size</select>

<select id="colors" class="" name="attribute_sizes" data-attribute_name="attribute_sizes">Want this to say Choose a color</select>

variable.php code lines 27 - 38:

<?php foreach ( $attributes as $attribute_name => $options ) : ?>

                        <label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?>

                            <?php
                                $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) : $product->get_variation_default_attribute( $attribute_name );
                                wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                                echo end( $attribute_keys ) === $attribute_name ? '' . __( 'Clear selection', 'woocommerce' ) . '' : '';
                            ?>

                <?php endforeach;?>

Body:
Updated code, made it for anyone still interested

add_filter( 'woocommerce_dropdown_variation_attribute_options_args',
fix_option', 10 );
function fix_option( $args ) {
    $attr = get_taxonomy( $args['attribute'] );
    $label = $attr->labels->name;
    $fix = str_replace('Product', '', $label);
    $fix = strtolower($fix); /
    $args['show_option_none'] = apply_filters( 'the_title', 'Select a '.$fix );
}