问:
How to interpret the loss function in the categorical generative adversarial net?
So I've been implementing the categorical generative adversarial networks which is described in here.

[Jost T. Springenberg. Unsupervised and semi-supervised learning with
categorical generative adversarial networks, April 2016.]

formula

This is the loss function introduced in page 6 and the thing is that the formula uses arg_max which is odd because most of the optimizers I can use on various frameworks such as Tensorflow only work in arg_min.

So would you please guys tell me how to implement this formula?

Here is the code I implemented.

```<code>import tensorflow as tf
import numpy as np
import PIL.Image as Image
# constants
X_dim = 256
Y_dim = 2
Z_dim = 256 * 256
value_lambda = 1.0

X = tf.placeholder(tf.float32, shape=[None, X_dim, X_dim, 1])
Y = tf.placeholder(tf.float32, shape=[None, Y_dim])
Z = tf.placeholder(tf.float32, shape=[None, Z_dim])

initializer = tf.contrib.layers.variance_scaling_initializer
activation_function = tf.nn.elu
regularizer = tf.contrib.layers.l2_regularizer(0.5)

custom_filter = np.ones(shape=[32, 256, 256, 1], dtype=np.float)
custom_filter[:, 255, :, :] = 0
custom_filter[:, :, 255, :] = 0

custom_filter = tf.constant(custom_filter, dtype=tf.float32)

def discriminator(x, name=None):
    with tf.name_scope(name, "discriminator", [x]) as scope:

        D_conv_1 = tf.layers.conv2d(inputs=x, filters=16, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [256, 256]
        D_mean_pool_1 = tf.nn.pool(D_conv_1, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [128, 128]
        D_conv_2 = tf.layers.conv2d(D_mean_pool_1, filters=32, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [128, 128]
        D_mean_pool_2 = tf.nn.pool(D_conv_2, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [64, 64]
        D_conv_3 = tf.layers.conv2d(D_mean_pool_2, filters=64, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [64, 64]
        D_mean_pool_3 = tf.nn.pool(D_conv_3, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [32, 32]
        D_conv_4 = tf.layers.conv2d(D_mean_pool_3, filters=128, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [32, 32]
        D_mean_pool_4 = tf.nn.pool(D_conv_4, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [16, 16]
        D_conv_5 = tf.layers.conv2d(D_mean_pool_4, filters=256, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function,  kernel_regularizer=regularizer)
        # [16, 16]
        D_mean_pool_5 = tf.nn.pool(D_conv_5, window_shape=[
                                   4, 4], pooling_type='AVG', padding='VALID', strides=[4, 4])
        # [4, 4]
        D_conv_6 = tf.layers.conv2d(D_mean_pool_5, filters=2, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function,  kernel_regularizer=regularizer)
        # [4, 4]
        D_mean_pool_6 = tf.nn.pool(D_conv_6, window_shape=[
                                   4, 4], pooling_type='AVG', padding='VALID', strides=[4, 4])
        # [1, 1], and finally, [batch_size][1][1][2]
        D_logit = tf.reshape(D_mean_pool_6, shape=[32, 2])
        # [batch_size][2]

        return D_logit

        '''
        D_hidden_layer_1 = tf.layers.dense(
            inputs=x, units=255, activation=activation_function)
        D_hidden_layer_2 = tf.layers.dense(
            inputs=D_hidden_layer_1, units=16, activation=activation_function)
        D_logit = tf.layers.dense(inputs=D_hidden_layer_2, units=Y_dim,
                                  activation=activation_function)

        return D_logit
        '''

def generator(z, name=None):
    with tf.name_scope(name, "generator", [z]) as scope:
        # z[32, 4096]
        input = tf.reshape(z, shape=[32, 256, 256, 1])
        # input[32, 64, 64, 1]
        G_conv_1 = tf.layers.conv2d(input, filters=96, kernel_size=[
                                    8, 8], padding='SAME', activation=activation_function)
        # [32, 64, 64, 96]
        # G_upscaled_1 = tf.image.resize_bicubic(images=G_conv_1, size=[128, 128])
        # [32, 128, 128, 96]
        G_conv_2 = tf.layers.conv2d(G_conv_1, filters=64, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)
        # [32, 128, 128, 64]
        # G_upscaled_2 = tf.image.resize_bicubic(G_conv_2, size=[256, 256])
        # [32, 256, 256, 64]
        G_conv_3 = tf.layers.conv2d(G_conv_2, filters=64, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)
        # [32, 256, 256, 64]
        G_conv_4 = tf.layers.conv2d(G_conv_3, filters=1, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)

        # [32, 256, 256, 1]
        G_logit = G_conv_4 * custom_filter
        # [32, 256, 256, 1], but filtered out the last column and row

        return G_logit

        '''
        G_hidden_layer_1 = tf.layers.dense(
            inputs=z, units=255, activation=activation_function)
        G_outputs = tf.layers.dense(inputs=G_hidden_layer_1, units=X_dim,
                                    activation=activation_function)

        return G_outputs
        '''

with tf.name_scope("training") as scope:
    # Getting samples from random data
    G_sample = generator(Z)
    # Getting logits
    D_logit_real = discriminator(X)
    D_logit_fake = discriminator(G_sample)

    # Applying softmax
    D_proba_real = tf.nn.softmax(logits=D_logit_real)
    D_proba_real = tf.clip_by_value(
        D_proba_real, clip_value_min=1e-4, clip_value_max=1.0)
    D_proba_fake = tf.nn.softmax(logits=D_logit_fake)
    D_proba_fake = tf.clip_by_value(
        D_proba_fake, clip_value_min=1e-4, clip_value_max=1.0)

    with tf.name_scope("category_1") as sub_scope:
        # Getting Shannon's entrophy in X's distribution
        D_log_real = tf.log(D_proba_real)
        D_entrophy_real = D_proba_real * D_log_real
        D_mean_real = tf.reduce_sum(D_entrophy_real, axis=1)
        D_mean_real = -D_mean_real
        D_entrophy_real_mean = tf.reduce_mean(D_mean_real, axis=0)
        D_entrophy_real_mean = tf.reshape(D_entrophy_real_mean, shape=[1])

    with tf.name_scope("category_2") as sub_scope:
        # Gettning Shannon's entrophy in Z's distribution
        G_log_fake = tf.log(D_proba_fake)
        G_entrophy_fake = D_proba_fake * G_log_fake
        G_mean = tf.reduce_sum(G_entrophy_fake, axis=1)
        G_mean = -G_mean
        G_entrophy_fake_mean = tf.reduce_mean(G_mean, axis=0)
        G_entrophy_fake_mean = tf.reshape(G_entrophy_fake_mean, shape=[1])

    with tf.name_scope("category_3") as sub_scope:
        # Getting Shannon's entrophy between classes
        D_class_mean = tf.reduce_mean(D_proba_real, axis=0, keep_dims=True)
        D_class_mean_log = tf.log(D_class_mean)
        D_class_entropy = D_class_mean * D_class_mean_log
        D_class = tf.reduce_sum(D_class_entropy, axis=1)
        D_class = -D_class
        D_class = tf.reshape(D_class, shape=[1])

        G_class_mean = tf.reduce_mean(D_proba_fake, axis=0, keep_dims=True)
        G_class_mean_log = tf.log(G_class_mean)
        G_class_entrophy = G_class_mean * G_class_mean_log
        G_class = tf.reduce_sum(G_class_entrophy, axis=1)
        G_class = -G_class
        G_class = tf.reshape(G_class, shape=[1])

    with tf.name_scope("supervised") as sub_scope:
        # Getting cross entrophy for labeled data
        D_labeled = Y * D_log_real
        D_cross_entrophy = tf.reduce_sum(D_labeled, axis=1)
        D_cross_entrophy = -D_cross_entrophy
        D_supervised = tf.reduce_mean(D_cross_entrophy, axis=0)
        D_supervised_weighted = value_lambda * D_supervised
        D_supervised_weighted = tf.reshape(D_supervised_weighted, shape=[1])

    D_loss = D_class - D_entrophy_real_mean + \
        G_entrophy_fake_mean + D_supervised_weighted
    G_loss = -G_class + G_entrophy_fake_mean
    D_loss = -D_loss

    D_solver = tf.train.AdamOptimizer().minimize(D_loss)
    G_solver = tf.train.AdamOptimizer().minimize(G_loss)

# with tf.name_scope("testing") as scope:
</code>```

答: I've done some research and asked some questions to my friends who works in a big company doing research on deep learning. As it turns out that the generative adversarial networks is not good at classification jobs. So I changed my mind and implemented it with GoogLenet. Problem solved!</p>

Body:
So I've been implementing the categorical generative adversarial networks which is described in here.

[Jost T. Springenberg. Unsupervised and semi-supervised learning with
categorical generative adversarial networks, April 2016.]

formula

This is the loss function introduced in page 6 and the thing is that the formula uses arg_max which is odd because most of the optimizers I can use on various frameworks such as Tensorflow only work in arg_min.

So would you please guys tell me how to implement this formula?

Here is the code I implemented.

import tensorflow as tf
import numpy as np
import PIL.Image as Image
# constants
X_dim = 256
Y_dim = 2
Z_dim = 256 * 256
value_lambda = 1.0

X = tf.placeholder(tf.float32, shape=[None, X_dim, X_dim, 1])
Y = tf.placeholder(tf.float32, shape=[None, Y_dim])
Z = tf.placeholder(tf.float32, shape=[None, Z_dim])

initializer = tf.contrib.layers.variance_scaling_initializer
activation_function = tf.nn.elu
regularizer = tf.contrib.layers.l2_regularizer(0.5)

custom_filter = np.ones(shape=[32, 256, 256, 1], dtype=np.float)
custom_filter[:, 255, :, :] = 0
custom_filter[:, :, 255, :] = 0

custom_filter = tf.constant(custom_filter, dtype=tf.float32)

def discriminator(x, name=None):
    with tf.name_scope(name, "discriminator", [x]) as scope:

        D_conv_1 = tf.layers.conv2d(inputs=x, filters=16, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [256, 256]
        D_mean_pool_1 = tf.nn.pool(D_conv_1, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [128, 128]
        D_conv_2 = tf.layers.conv2d(D_mean_pool_1, filters=32, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [128, 128]
        D_mean_pool_2 = tf.nn.pool(D_conv_2, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [64, 64]
        D_conv_3 = tf.layers.conv2d(D_mean_pool_2, filters=64, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [64, 64]
        D_mean_pool_3 = tf.nn.pool(D_conv_3, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [32, 32]
        D_conv_4 = tf.layers.conv2d(D_mean_pool_3, filters=128, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function, kernel_regularizer=regularizer)
        # [32, 32]
        D_mean_pool_4 = tf.nn.pool(D_conv_4, window_shape=[
                                   2, 2], pooling_type='AVG', padding='VALID', strides=[2, 2])
        # [16, 16]
        D_conv_5 = tf.layers.conv2d(D_mean_pool_4, filters=256, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function,  kernel_regularizer=regularizer)
        # [16, 16]
        D_mean_pool_5 = tf.nn.pool(D_conv_5, window_shape=[
                                   4, 4], pooling_type='AVG', padding='VALID', strides=[4, 4])
        # [4, 4]
        D_conv_6 = tf.layers.conv2d(D_mean_pool_5, filters=2, kernel_size=[
                                    3, 3], padding='SAME', activation=activation_function,  kernel_regularizer=regularizer)
        # [4, 4]
        D_mean_pool_6 = tf.nn.pool(D_conv_6, window_shape=[
                                   4, 4], pooling_type='AVG', padding='VALID', strides=[4, 4])
        # [1, 1], and finally, [batch_size][1][1][2]
        D_logit = tf.reshape(D_mean_pool_6, shape=[32, 2])
        # [batch_size][2]

        return D_logit

        '''
        D_hidden_layer_1 = tf.layers.dense(
            inputs=x, units=255, activation=activation_function)
        D_hidden_layer_2 = tf.layers.dense(
            inputs=D_hidden_layer_1, units=16, activation=activation_function)
        D_logit = tf.layers.dense(inputs=D_hidden_layer_2, units=Y_dim,
                                  activation=activation_function)

        return D_logit
        '''

def generator(z, name=None):
    with tf.name_scope(name, "generator", [z]) as scope:
        # z[32, 4096]
        input = tf.reshape(z, shape=[32, 256, 256, 1])
        # input[32, 64, 64, 1]
        G_conv_1 = tf.layers.conv2d(input, filters=96, kernel_size=[
                                    8, 8], padding='SAME', activation=activation_function)
        # [32, 64, 64, 96]
        # G_upscaled_1 = tf.image.resize_bicubic(images=G_conv_1, size=[128, 128])
        # [32, 128, 128, 96]
        G_conv_2 = tf.layers.conv2d(G_conv_1, filters=64, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)
        # [32, 128, 128, 64]
        # G_upscaled_2 = tf.image.resize_bicubic(G_conv_2, size=[256, 256])
        # [32, 256, 256, 64]
        G_conv_3 = tf.layers.conv2d(G_conv_2, filters=64, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)
        # [32, 256, 256, 64]
        G_conv_4 = tf.layers.conv2d(G_conv_3, filters=1, kernel_size=[
                                    5, 5], padding='SAME', activation=activation_function)

        # [32, 256, 256, 1]
        G_logit = G_conv_4 * custom_filter
        # [32, 256, 256, 1], but filtered out the last column and row

        return G_logit

        '''
        G_hidden_layer_1 = tf.layers.dense(
            inputs=z, units=255, activation=activation_function)
        G_outputs = tf.layers.dense(inputs=G_hidden_layer_1, units=X_dim,
                                    activation=activation_function)

        return G_outputs
        '''

with tf.name_scope("training") as scope:
    # Getting samples from random data
    G_sample = generator(Z)
    # Getting logits
    D_logit_real = discriminator(X)
    D_logit_fake = discriminator(G_sample)

    # Applying softmax
    D_proba_real = tf.nn.softmax(logits=D_logit_real)
    D_proba_real = tf.clip_by_value(
        D_proba_real, clip_value_min=1e-4, clip_value_max=1.0)
    D_proba_fake = tf.nn.softmax(logits=D_logit_fake)
    D_proba_fake = tf.clip_by_value(
        D_proba_fake, clip_value_min=1e-4, clip_value_max=1.0)

    with tf.name_scope("category_1") as sub_scope:
        # Getting Shannon's entrophy in X's distribution
        D_log_real = tf.log(D_proba_real)
        D_entrophy_real = D_proba_real * D_log_real
        D_mean_real = tf.reduce_sum(D_entrophy_real, axis=1)
        D_mean_real = -D_mean_real
        D_entrophy_real_mean = tf.reduce_mean(D_mean_real, axis=0)
        D_entrophy_real_mean = tf.reshape(D_entrophy_real_mean, shape=[1])

    with tf.name_scope("category_2") as sub_scope:
        # Gettning Shannon's entrophy in Z's distribution
        G_log_fake = tf.log(D_proba_fake)
        G_entrophy_fake = D_proba_fake * G_log_fake
        G_mean = tf.reduce_sum(G_entrophy_fake, axis=1)
        G_mean = -G_mean
        G_entrophy_fake_mean = tf.reduce_mean(G_mean, axis=0)
        G_entrophy_fake_mean = tf.reshape(G_entrophy_fake_mean, shape=[1])

    with tf.name_scope("category_3") as sub_scope:
        # Getting Shannon's entrophy between classes
        D_class_mean = tf.reduce_mean(D_proba_real, axis=0, keep_dims=True)
        D_class_mean_log = tf.log(D_class_mean)
        D_class_entropy = D_class_mean * D_class_mean_log
        D_class = tf.reduce_sum(D_class_entropy, axis=1)
        D_class = -D_class
        D_class = tf.reshape(D_class, shape=[1])

        G_class_mean = tf.reduce_mean(D_proba_fake, axis=0, keep_dims=True)
        G_class_mean_log = tf.log(G_class_mean)
        G_class_entrophy = G_class_mean * G_class_mean_log
        G_class = tf.reduce_sum(G_class_entrophy, axis=1)
        G_class = -G_class
        G_class = tf.reshape(G_class, shape=[1])

    with tf.name_scope("supervised") as sub_scope:
        # Getting cross entrophy for labeled data
        D_labeled = Y * D_log_real
        D_cross_entrophy = tf.reduce_sum(D_labeled, axis=1)
        D_cross_entrophy = -D_cross_entrophy
        D_supervised = tf.reduce_mean(D_cross_entrophy, axis=0)
        D_supervised_weighted = value_lambda * D_supervised
        D_supervised_weighted = tf.reshape(D_supervised_weighted, shape=[1])

    D_loss = D_class - D_entrophy_real_mean + \
        G_entrophy_fake_mean + D_supervised_weighted
    G_loss = -G_class + G_entrophy_fake_mean
    D_loss = -D_loss

    D_solver = tf.train.AdamOptimizer().minimize(D_loss)
    G_solver = tf.train.AdamOptimizer().minimize(G_loss)

# with tf.name_scope("testing") as scope:


来源: stackexchange

问:
How to know if song available in a country or not
How can I find out if a song is available in a country or not so I can enable/disable features of my app based on this information using the Android Spotify SDK or web API.</p>

答:
I found web api to solve your problem that provide you a country code,

have look this https://github.com/spotify/web-api/issues/535 link, this link provide you available_markets

https://labs.spotify.com/2015/03/09/understanding-spotify-web-api/

Parse JSON object with multiple levels Android

ContentLicense: CC BY-SA 3.0


问:
Why Mysql is not handling case sensitive cases
When I test below sql queries:

```<code>    1.  SELECT * FROM  table WHERE  username='username' AND password = 'password';

    2.  SELECT * FROM  table WHERE  username='Username' AND password = 'Password';
</code>```

Both queries are returning the same result even though username and password are case sensitive

答:
Use this query</p>

```<code>SELECT * FROM  table WHERE  username='Username' AND binary password = 'Password';
</code>```

Body:
When I test below sql queries:

    1.  SELECT * FROM  table WHERE  username='username' AND password = 'password';

    2.  SELECT * FROM  table WHERE  username='Username' AND password = 'Password';

Both queries are returning the same result even though username and password are case sensitive

Body:
Use this query

SELECT * FROM  table WHERE  username='Username' AND binary password = 'Password';


问:
Rails User.joins.not(...) in Active Record?
Im looking to query all Users without Comments in a single sql query?

Models:

```<code>class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end
</code>```

So I want the opposite of this:

```<code>User.joins(:comments).group('users.id')
</code>```

But not like this: (because it generates two queries)

```<code>User.where.not(id: Comment.pluck(:user_id))
</code>```

Maybe something like this?

```<code>User.joins.not(:comments).group('users.id')
</code>```

Thanks for any input!

答:
Another simple solution
User.where("id NOT IN (?)", Comment.pluck(:user_id))

ContentLicense: CC BY-SA 4.0

Body:
Im looking to query all Users without Comments in a single sql query?

Models:

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
end

So I want the opposite of this:

User.joins(:comments).group('users.id')

But not like this: (because it generates two queries)

User.where.not(id: Comment.pluck(:user_id))

Maybe something like this?

User.joins.not(:comments).group('users.id')

Thanks for any input!


问:
How to tell Pyinstaller to use Python 3.5 instead of 2.7?
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run.

```<code>cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py
25 INFO: PyInstaller: 3.2.1
25 INFO: Python: 2.7.12
26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena
26 INFO: wrote /home/cali/Desktop/Vocabulary.spec
31 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/cali/Desktop', '/home/cali/Desktop']
32 INFO: checking Analysis
33 INFO: Building Analysis because out00-Analysis.toc is non existent
33 INFO: Initializing module dependency graph...
34 INFO: Initializing module graph hooks...
139 INFO: running Analysis out00-Analysis.toc
160 INFO: Caching module hooks...
164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py
246 INFO: Processing pre-safe import module hook   _xmlplus
1991 INFO: Processing pre-find module path hook   distutils
2209 INFO: Loading module hooks...
2209 INFO: Loading module hook "hook-distutils.py"...
2210 INFO: Loading module hook "hook-xml.py"...
2959 INFO: Loading module hook "hook-httplib.py"...
2960 INFO: Loading module hook "hook-encodings.py"...
3427 INFO: Looking for ctypes DLLs
3428 INFO: Analyzing run-time hooks ...
3435 INFO: Looking for dynamic libraries
3663 INFO: Looking for eggs
3663 INFO: Python library not in binary depedencies. Doing additional searching...
3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt
3768 INFO: checking PYZ
3768 INFO: Building PYZ because out00-PYZ.toc is non existent
3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz
4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully.
4172 INFO: checking PKG
4172 INFO: Building PKG because out00-PKG.toc is non existent
4172 INFO: Building PKG (CArchive) out00-PKG.pkg
7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run
7336 INFO: checking EXE
7336 INFO: Building EXE because out00-EXE.toc is non existent
7336 INFO: Building EXE from out00-EXE.toc
7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary
7352 INFO: Building EXE from out00-EXE.toc completed successfully.
</code>```

How can I overcome the issue?

@EDIT:

I tried to install Pyinstaller using pip3 install pyinstaller as Claudio suggested, but I am getting:

```<code>cali@californiki-pc ~/Desktop $ pip3 install pyinstaller
Collecting pyinstaller
  Using cached PyInstaller-3.2.1.tar.bz2
Collecting setuptools (from pyinstaller)
  Using cached setuptools-35.0.1-py2.py3-none-any.whl
Collecting appdirs>=1.4.0 (from setuptools->pyinstaller)
  Using cached appdirs-1.4.3-py2.py3-none-any.whl
Collecting packaging>=16.8 (from setuptools->pyinstaller)
  Using cached packaging-16.8-py2.py3-none-any.whl
Collecting six>=1.6.0 (from setuptools->pyinstaller)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller)
  Using cached pyparsing-2.2.0-py2.py3-none-any.whl
Building wheels for collected packages: pyinstaller
  Running setup.py bdist_wheel for pyinstaller ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35:
  usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
     or: -c --help [cmd1 cmd2 ...]
     or: -c --help-commands
     or: -c cmd --help

  error: invalid command 'bdist_wheel'

  ----------------------------------------
  Failed building wheel for pyinstaller
  Running setup.py clean for pyinstaller
Failed to build pyinstaller
Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller
  Running setup.py install for pyinstaller ... done
Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

答:
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance:</p>

```<code>pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py'
</code>```

Body:
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run.

cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py
25 INFO: PyInstaller: 3.2.1
25 INFO: Python: 2.7.12
26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena
26 INFO: wrote /home/cali/Desktop/Vocabulary.spec
31 INFO: UPX is not available.
32 INFO: Extending PYTHONPATH with paths
['/home/cali/Desktop', '/home/cali/Desktop']
32 INFO: checking Analysis
33 INFO: Building Analysis because out00-Analysis.toc is non existent
33 INFO: Initializing module dependency graph...
34 INFO: Initializing module graph hooks...
139 INFO: running Analysis out00-Analysis.toc
160 INFO: Caching module hooks...
164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py
246 INFO: Processing pre-safe import module hook   _xmlplus
1991 INFO: Processing pre-find module path hook   distutils
2209 INFO: Loading module hooks...
2209 INFO: Loading module hook "hook-distutils.py"...
2210 INFO: Loading module hook "hook-xml.py"...
2959 INFO: Loading module hook "hook-httplib.py"...
2960 INFO: Loading module hook "hook-encodings.py"...
3427 INFO: Looking for ctypes DLLs
3428 INFO: Analyzing run-time hooks ...
3435 INFO: Looking for dynamic libraries
3663 INFO: Looking for eggs
3663 INFO: Python library not in binary depedencies. Doing additional searching...
3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt
3768 INFO: checking PYZ
3768 INFO: Building PYZ because out00-PYZ.toc is non existent
3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz
4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully.
4172 INFO: checking PKG
4172 INFO: Building PKG because out00-PKG.toc is non existent
4172 INFO: Building PKG (CArchive) out00-PKG.pkg
7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully.
7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run
7336 INFO: checking EXE
7336 INFO: Building EXE because out00-EXE.toc is non existent
7336 INFO: Building EXE from out00-EXE.toc
7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary
7352 INFO: Building EXE from out00-EXE.toc completed successfully.

How can I overcome the issue?

@EDIT:

I tried to install Pyinstaller using pip3 install pyinstaller as Claudio suggested, but I am getting:

cali@californiki-pc ~/Desktop $ pip3 install pyinstaller
Collecting pyinstaller
  Using cached PyInstaller-3.2.1.tar.bz2
Collecting setuptools (from pyinstaller)
  Using cached setuptools-35.0.1-py2.py3-none-any.whl
Collecting appdirs>=1.4.0 (from setuptools->pyinstaller)
  Using cached appdirs-1.4.3-py2.py3-none-any.whl
Collecting packaging>=16.8 (from setuptools->pyinstaller)
  Using cached packaging-16.8-py2.py3-none-any.whl
Collecting six>=1.6.0 (from setuptools->pyinstaller)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller)
  Using cached pyparsing-2.2.0-py2.py3-none-any.whl
Building wheels for collected packages: pyinstaller
  Running setup.py bdist_wheel for pyinstaller ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35:
  usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
     or: -c --help [cmd1 cmd2 ...]
     or: -c --help-commands
     or: -c cmd --help

  error: invalid command 'bdist_wheel'

  ----------------------------------------
  Failed building wheel for pyinstaller
  Running setup.py clean for pyinstaller
Failed to build pyinstaller
Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller
  Running setup.py install for pyinstaller ... done
Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Body:
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance:

pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py'


问:
Can not delete cached item created with beginCache
I have a fragment that I'm caching because there are a lot of database hits to generate the content.

main.php:

```<code>    'cache'=>array(
            'class'=>'system.caching.CFileCache'
    )
</code>```

view.php

```<code><?php if($this->beginCache("my_id", array('duration' => 315360000))) { ?>
   // lots of heavy stuff
<?php $this->endCache(); } ?>
</code>```

My cached fragment only changes when I adjust the configuration in a database table. I'm trying to find a way to delete the cached item using the "my_id". The Yii documentation is somewhat misleading because when it talks about beginCache it refers to the key ("my_id"), but when it talks about deleting items from the cache it also talks about the key, but it is not the same key!
beginCache is essentially a wrapper for an COutputCache widget and so "my_id" is not the key used in the cache.

Does anyone know how to convert "my_id" into a cache-friendly key so that I can delete that specific item from the cache.

I've tried extending from CFileCache but my key is generated from COutputCache which uses CFileCache and I don't think there is a back route. I have also tried beginning a widget with an overloaded version of COutputCache which works but just seems like a really nasty hack.

```<code>    $properties = array();
    $properties['id']=Yii::app()->params["cache_name_matrix"];
    $cache=$this->beginWidget('MyCOutputCache',$properties);
    $key = $cache->getKeyHack();
</code>```

My current work around is flush the whole cache but this gets rid of everything and seems a little bit heavy handed.

Any ideas?

答:
Yii2 try this </p>

```<code>$key = Array ('yii\widgets\FragmentCache','key_id');
Yii::$app->cache->delete($key);
</code>```

Body:
I have a fragment that I'm caching because there are a lot of database hits to generate the content.

main.php:

    'cache'=>array(
            'class'=>'system.caching.CFileCache'
    )

view.php

<?php if($this->beginCache("my_id", array('duration' => 315360000))) { ?>
   // lots of heavy stuff
<?php $this->endCache(); } ?>

My cached fragment only changes when I adjust the configuration in a database table. I'm trying to find a way to delete the cached item using the "my_id". The Yii documentation is somewhat misleading because when it talks about beginCache it refers to the key ("my_id"), but when it talks about deleting items from the cache it also talks about the key, but it is not the same key!
beginCache is essentially a wrapper for an COutputCache widget and so "my_id" is not the key used in the cache.

Does anyone know how to convert "my_id" into a cache-friendly key so that I can delete that specific item from the cache.

I've tried extending from CFileCache but my key is generated from COutputCache which uses CFileCache and I don't think there is a back route. I have also tried beginning a widget with an overloaded version of COutputCache which works but just seems like a really nasty hack.

    $properties = array();
    $properties['id']=Yii::app()->params["cache_name_matrix"];
    $cache=$this->beginWidget('MyCOutputCache',$properties);
    $key = $cache->getKeyHack();

My current work around is flush the whole cache but this gets rid of everything and seems a little bit heavy handed.

Any ideas?

Body:
Yii2 try this

$key = Array ('yii\widgets\FragmentCache','key_id');
Yii::$app->cache->delete($key);


答:
Syntax for Case Sensitive query

```<code>SELECT *  FROM `table` WHERE BINARY `column` = 'value'
</code>```

In your case it will become:

```<code>SELECT * FROM  table WHERE BINARY username='Username' AND BINARY password = 'Password';
</code>```

Title: Why Mysql is not handling case sensitive cases

Body:
Syntax for Case Sensitive query

SELECT *  FROM `table` WHERE BINARY `column` = 'value'

In your case it will become:

SELECT * FROM  table WHERE BINARY username='Username' AND BINARY password = 'Password';


问:
Passing data from an Activity to a fragment that has no onCreate
Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate</p>

答:
Try this one   </p>

```<code>public class SampleActivity extends AppCompactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        if (savedInstanceState == null) {
            Fragment fragment = new SampleFragment();

            Bundle args = new Bundle();

            args.putInt("sample_int", 1);

            fragment.setArguments(args);

            getSupportFragmentManager().beginTransaction()
                 .add(R.id.container, fragment)
                 .commit();
        }
    }
}

public class SampleFragment extends Fragment {

    @Override
    public void onResume() {
        Bundle args = getArguments();

        if (args != null) {
            int sampleInt = args.getInt("sample_int", -1);
        }
    }
}
</code>```

Body:
Try this one

public class SampleActivity extends AppCompactActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        if (savedInstanceState == null) {
            Fragment fragment = new SampleFragment();

            Bundle args = new Bundle();

            args.putInt("sample_int", 1);

            fragment.setArguments(args);

            getSupportFragmentManager().beginTransaction()
                 .add(R.id.container, fragment)
                 .commit();
        }
    }
}

public class SampleFragment extends Fragment {

    @Override
    public void onResume() {
        Bundle args = getArguments();

        if (args != null) {
            int sampleInt = args.getInt("sample_int", -1);
        }
    }
}


问:
React-native rendering button but not showing its height
I am trying to render logout button and its rendering it but its not showing height for the button. i am also adding the files which have data for Both button.js and app.js. now the problem is its showind button but the height of the button is 1 dont know why. i copied this code from somewhere and trying to make something out of it. some other place i am easily able to use button width. but not here.

and my common/index.js has all exported files like Button.js and all
getting button in this form.its showing but not with the size

Button.js

```<code>import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
const Button = ({ onPress, children }) => {
  const { buttonStyle, textStyle } = styles;
return (
  <TouchableOpacity onPress={onPress} style={buttonStyle}>
    <Text style={textStyle}>
      {children}
    </Text>
 </TouchableOpacity>
);
};

const styles = {
textStyle: {
  alignSelf: 'center',
  color: '#007aff',
  fontSize: 16,
  fontWeight: '600',
  paddingTop: 10,
  paddingBottom: 10
},

    buttonStyle: {
  flex: 1,
  alignSelf: 'stretch',
  backgroundColor: '#fff',
  borderRadius: 5,
  borderWidth: 1,
  borderColor: '#007aff',
  marginLeft: 5,
  marginRight: 5
}
};

export { Button };
</code>```

App.js

```<code>import React, {Component} from 'react';
import { View } from 'react-native';
import firebase from 'firebase';
import { Header, Button, Spinner, Card } from './components/common';
import LoginForm from './components/LoginForm';

class App extends Component {

  state = { loggedIn: null };

  componentWillMount() {
    firebase.initializeApp({
      apiKey: '***********************************',
      authDomain: '*********************************',
      databaseURL: '***********************************',
      projectId: '***************************************',
      storageBucket: '*************************************',
      messagingSenderId: '32810678085'
    });

 firebase.auth().onAuthStateChanged((user) => {
      if(user){
        this.setState({ loggedIn: true });
      }else {
        this.setState({ loggedIn: false });
      }
    });

  }

  renderContent(){

    switch (this.state.loggedIn){
      case true:
        return <Button> Log out </Button>

      case false:
        return <LoginForm />;

      default:
        return <Spinner size="large" />;
    }

  }

  render() {
    return (
      <View>
        <Header headerText="Authentication" />
        {this.renderContent()}
      </View>
    )
  }
}

export default App;
</code>```

答:
Just add this:

```<code>marginTop:5
</code>```

to the buttonStyle object.

Body:
I am trying to render logout button and its rendering it but its not showing height for the button. i am also adding the files which have data for Both button.js and app.js. now the problem is its showind button but the height of the button is 1 dont know why. i copied this code from somewhere and trying to make something out of it. some other place i am easily able to use button width. but not here.

and my common/index.js has all exported files like Button.js and all
getting button in this form.its showing but not with the size

Button.js

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
const Button = ({ onPress, children }) => {
  const { buttonStyle, textStyle } = styles;
return (
  <TouchableOpacity onPress={onPress} style={buttonStyle}>
    <Text style={textStyle}>
      {children}
    </Text>
 </TouchableOpacity>
);
};

const styles = {
textStyle: {
  alignSelf: 'center',
  color: '#007aff',
  fontSize: 16,
  fontWeight: '600',
  paddingTop: 10,
  paddingBottom: 10
},

    buttonStyle: {
  flex: 1,
  alignSelf: 'stretch',
  backgroundColor: '#fff',
  borderRadius: 5,
  borderWidth: 1,
  borderColor: '#007aff',
  marginLeft: 5,
  marginRight: 5
}
};

export { Button };

App.js

import React, {Component} from 'react';
import { View } from 'react-native';
import firebase from 'firebase';
import { Header, Button, Spinner, Card } from './components/common';
import LoginForm from './components/LoginForm';

class App extends Component {

  state = { loggedIn: null };

  componentWillMount() {
    firebase.initializeApp({
      apiKey: '***********************************',
      authDomain: '*********************************',
      databaseURL: '***********************************',
      projectId: '***************************************',
      storageBucket: '*************************************',
      messagingSenderId: '32810678085'
    });

 firebase.auth().onAuthStateChanged((user) => {
      if(user){
        this.setState({ loggedIn: true });
      }else {
        this.setState({ loggedIn: false });
      }
    });

  }

  renderContent(){

    switch (this.state.loggedIn){
      case true:
        return <Button> Log out </Button>

      case false:
        return <LoginForm />;

      default:
        return <Spinner size="large" />;
    }

  }

  render() {
    return (
      <View>

        {this.renderContent()}
      </View>
    )
  }
}

export default App;

Body:
Just add this:

marginTop:5

to the buttonStyle object.


问:
Chef Vault Item was not encrypted with your public key
Trying to store encrypted credentials for user creation Chef Vault and then deploy the cookbook to the node I want the user created on.

Using Chef version 12.13.37

Using chef-vault cookbook 2.1.1

Initially created the vault with

```<code>knife vault create ftp users \ '{"user":"password"}' \ --search 'name:my_node_name' \ --admins bk0155 \ --mode client
</code>```

Output of knife vault show ftp users gives

```<code>id:             users
user: password
</code>```

My recipe has this in it:

```<code>include_recipe 'chef-vault'
vault = ChefVault::Item.load("ftp", "users")
user 'testuser' do
      comment 'Test User Account'
      home '/home/testuser'
      shell '/sbin/bash'
      group 'testusers'
      password vault['user']
end
</code>```

And the error I'm getting is

```<code> ChefVault::Exceptions::SecretDecryption
 ---------------------------------------
 ftp/users is not encrypted with your public key.  Contact an administrator of the vault item to encrypt for you!

 Cookbook Trace:
 ---------------
 /var/chef/cache/cookbooks/ftp_test/recipes/default.rb:10:in
 `from_file'

/var/chef/cache/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/run_context.rb:347:in `load_recipe'

  Relevant File Content:
  ----------------------
  /var/chef/cache/cookbooks/ftp_test/recipes/default.rb:

    3:  # Recipe:: default
    4:  #
    5:  # Copyright:: 2017, The Authors, All Rights Reserved.
    6:  #
    7:
    8:  include_recipe 'chef-vault'
    9:
   10>> vault = ChefVault::Item.load("ftp", "users")
   11:
</code>```

I've tried doing
knife update ftp users -S 'name:my_node_name' -M client to update but that doesn't seem to help

Doing a knife data bag show ftp users_keys gives:

```<code>WARNING: Unencrypted data bag detected, ignoring any provided secret options.
admins:
  bk0155
  my_node_name
my_node_name: fqkwg0098mpbDiJKFCsBEoMLiyN0kZLksiZpWwoxepr6lUgBMFGkJvSpkoGf
3ZwZt8PG2keNe9RYQ93rvgRBKGhLwP46lvDMLO78CEBPfSV5S2mYoe7B7mBb
NFhHPmWkXX2IhaL6TkLvvjATVqBEuUbeqtDb7HO5XOSTuBHacovQxEJerHmA
dXWBsPgs/GPnsu8xK3BNLHjvyVJ3ovaYkvCTxdFTWvDfb8184jC9rJX882Op
XCeGhZ3I5BPXDmNi5XW7EAPgjtbqgxIGPZwYHrrEcZji4TMKxnc6O5+9rPB/
/j4mM/QEL5zGtTeeluzmX+wSE605p9KwGAqsLpUn/g==

clients:                  my_node_name
id:                       users_keys
bk0155:                 mDsML41veFJclX0yXVMqYGvW52uRnZRtQTrRl1XTddgUJc0N9RR1qnyk0gxC
07jKkN+AsdkFuMoOGr7UcUCo/1MEsL125CvsSevOGOF9QMvUk67xw8Q+OlP0
4vqmvJNyaxeXxVV7FOVJSTC2ytovStD2WaSshZutNhG+EgIZ0zSOivHHryW+
aFyClqjVIA3Sm7ITuEyheqBJZZntpHhK1a4Gwk1V3T9aJZ3OT5vvFtNzppnx
CerZvQjPdthwmrqbKfMmYG3KmsPUPEMsAHxK8ryw8Sntu/MYechWzUTGYDii
gcuhehwUCgb+6LAM66ygiIqxcpZ3qg2ddcSUbo5V0g==

search_query:             name:my_node_name
</code>```

I have also tried knife vault rotate keys and am still getting the same error.

答:
If by any chance your node key changed, you should run knife vault refresh ftp users_keys, with -M client if you do not set this in knife.rb. If it does not work, try dropping the whole vault and creating it from scratch, but refresh should be sufficient.

update is for updating the content of the vault, rotate is for rotating shared key not client's keys.

Body:
Trying to store encrypted credentials for user creation Chef Vault and then deploy the cookbook to the node I want the user created on.

Using Chef version 12.13.37

Using chef-vault cookbook 2.1.1

Initially created the vault with

knife vault create ftp users \ '{"user":"password"}' \ --search 'name:my_node_name' \ --admins bk0155 \ --mode client

Output of knife vault show ftp users gives

id:             users
user: password

My recipe has this in it:

include_recipe 'chef-vault'
vault = ChefVault::Item.load("ftp", "users")
user 'testuser' do
      comment 'Test User Account'
      home '/home/testuser'
      shell '/sbin/bash'
      group 'testusers'
      password vault['user']
end

And the error I'm getting is

 ChefVault::Exceptions::SecretDecryption
 ---------------------------------------
 ftp/users is not encrypted with your public key.  Contact an administrator of the vault item to encrypt for you!

 Cookbook Trace:
 ---------------
 /var/chef/cache/cookbooks/ftp_test/recipes/default.rb:10:in
 `from_file'

/var/chef/cache/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/run_context.rb:347:in `load_recipe'

  Relevant File Content:
  ----------------------
  /var/chef/cache/cookbooks/ftp_test/recipes/default.rb:

    3:  # Recipe:: default
    4:  #
    5:  # Copyright:: 2017, The Authors, All Rights Reserved.
    6:  #
    7:
    8:  include_recipe 'chef-vault'
    9:
   10>> vault = ChefVault::Item.load("ftp", "users")
   11:

I've tried doing
knife update ftp users -S 'name:my_node_name' -M client to update but that doesn't seem to help

Doing a knife data bag show ftp users_keys gives:

WARNING: Unencrypted data bag detected, ignoring any provided secret options.
admins:
  bk0155
  my_node_name
my_node_name: fqkwg0098mpbDiJKFCsBEoMLiyN0kZLksiZpWwoxepr6lUgBMFGkJvSpkoGf
3ZwZt8PG2keNe9RYQ93rvgRBKGhLwP46lvDMLO78CEBPfSV5S2mYoe7B7mBb
NFhHPmWkXX2IhaL6TkLvvjATVqBEuUbeqtDb7HO5XOSTuBHacovQxEJerHmA
dXWBsPgs/GPnsu8xK3BNLHjvyVJ3ovaYkvCTxdFTWvDfb8184jC9rJX882Op
XCeGhZ3I5BPXDmNi5XW7EAPgjtbqgxIGPZwYHrrEcZji4TMKxnc6O5+9rPB/
/j4mM/QEL5zGtTeeluzmX+wSE605p9KwGAqsLpUn/g==

clients:                  my_node_name
id:                       users_keys
bk0155:                 mDsML41veFJclX0yXVMqYGvW52uRnZRtQTrRl1XTddgUJc0N9RR1qnyk0gxC
07jKkN+AsdkFuMoOGr7UcUCo/1MEsL125CvsSevOGOF9QMvUk67xw8Q+OlP0
4vqmvJNyaxeXxVV7FOVJSTC2ytovStD2WaSshZutNhG+EgIZ0zSOivHHryW+
aFyClqjVIA3Sm7ITuEyheqBJZZntpHhK1a4Gwk1V3T9aJZ3OT5vvFtNzppnx
CerZvQjPdthwmrqbKfMmYG3KmsPUPEMsAHxK8ryw8Sntu/MYechWzUTGYDii
gcuhehwUCgb+6LAM66ygiIqxcpZ3qg2ddcSUbo5V0g==

search_query:             name:my_node_name

I have also tried knife vault rotate keys and am still getting the same error.


问:
Selection.ShapeRange isn't working with ActiveX CommandButton
```<code>Sub sampleButton_Click()
On Error GoTo ErrorHandler

With Selection.ShapeRange
    If .Type = msoGroup Then
        Call setStyleTest(.GroupItems(.GroupItems.Count))
    Else
        For Each shp In ActiveWindow.Selection.ShapeRange
            Call setStyleTest(shp)
        Next shp
    End If
End With
Exit Sub

ErrorHandler:
    MsgBox "Error", vbExclamation

End Sub
</code>```

I use ActiveX CommandButton and have a problem with a testing selection of ShapeRange. What should I change/fix?
Thanks in advance

答:
Problem Explanation

The CommandButton does not have the property ShapeRange

Hence, the error will always arise

In the other hand, if you change the object for a button -the one under form collection- you will not have that problem because that property exists in that object

Note that, even if they resemble in appearance, they are totally different objects, as such, one property may not exist in the other one or behave like in the other.
More info about what you can do -and how to do it- with this button can be found here

Solution/workaround

I can see that you are calling another sub to "personalize" the button created, since it is unknown, you would need to change in that according to the object in order to provide the desired format.
You would also need to invert the order in your code for the correct handling

```<code>...
    If .Type = msoGroup Then
With Selection.ShapeRange
...
</code>```

Further thoughts

I cannot possible think about a scenario where you would need to use active X instead of form button collection, so I would suggest to change all the buttons to that.

Body:
Sub sampleButton_Click()
On Error GoTo ErrorHandler

With Selection.ShapeRange
    If .Type = msoGroup Then
        Call setStyleTest(.GroupItems(.GroupItems.Count))
    Else
        For Each shp In ActiveWindow.Selection.ShapeRange
            Call setStyleTest(shp)
        Next shp
    End If
End With
Exit Sub

ErrorHandler:
    MsgBox "Error", vbExclamation

End Sub

I use ActiveX CommandButton and have a problem with a testing selection of ShapeRange. What should I change/fix?
Thanks in advance

Body:
Problem Explanation

The CommandButton does not have the property ShapeRange

Hence, the error will always arise

In the other hand, if you change the object for a button -the one under form collection- you will not have that problem because that property exists in that object

Note that, even if they resemble in appearance, they are totally different objects, as such, one property may not exist in the other one or behave like in the other.
More info about what you can do -and how to do it- with this button can be found here

Solution/workaround

I can see that you are calling another sub to "personalize" the button created, since it is unknown, you would need to change in that according to the object in order to provide the desired format.
You would also need to invert the order in your code for the correct handling

...
    If .Type = msoGroup Then
With Selection.ShapeRange
...

Further thoughts

I cannot possible think about a scenario where you would need to use active X instead of form button collection, so I would suggest to change all the buttons to that.


问:
Insert Array of values into columns of the table in SQL Server
I have an array

```<code>(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)
</code>```

I want to insert this array of values into the table like

```<code>Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16
</code>```

Body:
I have an array

(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)

I want to insert this array of values into the table like

Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16

Body:
INSERT INTO TableName
VALUES
(1,2,3,4),(5,6,7,8),(9,10,11,12),(13,14,15,16)


问:
How do I compare data range between dates type "TEXT"
I need to compare 2 dates type "TEXT".
My question is, I have date that is exist in the database, and the other date is not existing. How to make query that compare 2 dates type "TEXT", first date is exist, and 2nd date is not. Here is my example data in database 2017 and 2016

My Query is SELECT * FROM oec2 WHERE oec_month BETWEEN '$oec_month1' AND '$oec_month2'
Note: the $oec_month1 (date type TEXT) is exist in db, but the $oec_month2 is not exist.

If I used that query it give me the result of 2017 and 2016

```<code>$db = new ezSQL_mysqli(db_user,db_password,db_name,db_host);

$field='date';
$sort='ASC';
if (isset($_GET['search'])){
$branch_id = $db->escape((int)($_GET['branch_id']));
$branch_region = $_GET['branch_region'];
$oec_month1 = $_GET['oec_month1'];
$oec_month2 = $_GET['oec_month2'];
if(isset($_GET['sorting'])){
    if($_GET['sorting']=='ASC'){$sort='DESC';$dir="down";}
    else {$sort='ASC';$dir="up";}
}
if ($_GET['field']=='result'){$field="result";}
else if ($_GET['field']=='oecgrade'){$field="oecgrade";}
else if ($_GET['field']=='risk'){$field="risk";}

if (!empty($oec_month1)) {
    if (!empty($oec_month2)){$searchquery .= " AND (oec_month BETWEEN '$oec_month1' AND '$oec_month2')";}
    else {$searchquery .= " AND oec_month >= '$oec_month1'";}
} else if (!empty($oec_month2)){$searchquery .= " AND oec_month <= '$oec_month2'";}
if (!empty($branch_id)) {$searchquery .= " AND (branch_id = '$branch_id')";}
if (!empty($branch_region)) {$searchquery .= " AND (branch_region = '$branch_region')";}
$searchquery .= (" order by $field $sort;");
$site_oec = $db->get_results("SELECT * FROM oec2 WHERE 1=1 $searchquery");
$num = $db->num_rows;
</code>```

The final output should be the only data in 2017 because the user pick dates between "01/2017" and "02/2017", but it gives me the result of 2016. FYI: The date "02/2017" is not exist.

答:
You can use STR_TO_DATE() to convert TEXT into appropriate supported date format, then it would be possible to compare values between date.

Example:

If $oec_month1 and $oec_month1 contains date format as:

```<code>$oec_month1 = "01/2017";
$oec_month2 = "01/2017";
</code>```

Then, it may be something like this example:

```<code>SELECT * FROM oec2 WHERE oec_month >= STR_TO_DATE($oec_month1, '%m/%Y') AND oec_month <= STR_TO_DATE($oec_month2, '%m/%Y')
</code>```

For further information about date format please see the link below:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

Body:
I need to compare 2 dates type "TEXT".
My question is, I have date that is exist in the database, and the other date is not existing. How to make query that compare 2 dates type "TEXT", first date is exist, and 2nd date is not. Here is my example data in database 2017 and 2016

My Query is SELECT * FROM oec2 WHERE oec_month BETWEEN '$oec_month1' AND '$oec_month2'
Note: the $oec_month1 (date type TEXT) is exist in db, but the $oec_month2 is not exist.

If I used that query it give me the result of 2017 and 2016

$db = new ezSQL_mysqli(db_user,db_password,db_name,db_host);

$field='date';
$sort='ASC';
if (isset($_GET['search'])){
$branch_id = $db->escape((int)($_GET['branch_id']));
$branch_region = $_GET['branch_region'];
$oec_month1 = $_GET['oec_month1'];
$oec_month2 = $_GET['oec_month2'];
if(isset($_GET['sorting'])){
    if($_GET['sorting']=='ASC'){$sort='DESC';$dir="down";}
    else {$sort='ASC';$dir="up";}
}
if ($_GET['field']=='result'){$field="result";}
else if ($_GET['field']=='oecgrade'){$field="oecgrade";}
else if ($_GET['field']=='risk'){$field="risk";}

if (!empty($oec_month1)) {
    if (!empty($oec_month2)){$searchquery .= " AND (oec_month BETWEEN '$oec_month1' AND '$oec_month2')";}
    else {$searchquery .= " AND oec_month >= '$oec_month1'";}
} else if (!empty($oec_month2)){$searchquery .= " AND oec_month <= '$oec_month2'";}
if (!empty($branch_id)) {$searchquery .= " AND (branch_id = '$branch_id')";}
if (!empty($branch_region)) {$searchquery .= " AND (branch_region = '$branch_region')";}
$searchquery .= (" order by $field $sort;");
$site_oec = $db->get_results("SELECT * FROM oec2 WHERE 1=1 $searchquery");
$num = $db->num_rows;

The final output should be the only data in 2017 because the user pick dates between "01/2017" and "02/2017", but it gives me the result of 2016. FYI: The date "02/2017" is not exist.

Body:
You can use STR_TO_DATE() to convert TEXT into appropriate supported date format, then it would be possible to compare values between date.

Example:

If $oec_month1 and $oec_month1 contains date format as:

$oec_month1 = "01/2017";
$oec_month2 = "01/2017";

Then, it may be something like this example:

SELECT * FROM oec2 WHERE oec_month >= STR_TO_DATE($oec_month1, '%m/%Y') AND oec_month <= STR_TO_DATE($oec_month2, '%m/%Y')

For further information about date format please see the link below:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format


问:
Android get tabLayout from a fragment
I was wondering if there's a way to access the tabLayout from a fragment.

I declare my TabLayout below and I disable all the tabs.

```<code>TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
    for(int i = 0; i < tabStrip.getChildCount(); i++) {
       tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
                return true;
           }
       });
    }
</code>```

What I would like to do is be able to enable them in a fragment inside a ClickListener.

I am not sure I should declare the tabLayout static and access it like that or if there's a correct way of doing this.

I apologize if I did not explain it correct - still a little new to Android.

答:
Declaring tablayout as static variable is a bad way of handling the scenario. You can make use of interface to achieve this instead. Please check out the official link on how to communicate between fragment and activity, it is pretty simple.
https://developer.android.com/training/basics/fragments/communicating.html</p>

Title: Android get tabLayout from a fragment

Body:
I was wondering if there's a way to access the tabLayout from a fragment.

I declare my TabLayout below and I disable all the tabs.

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
    for(int i = 0; i < tabStrip.getChildCount(); i++) {
       tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
                return true;
           }
       });
    }

What I would like to do is be able to enable them in a fragment inside a ClickListener.

I am not sure I should declare the tabLayout static and access it like that or if there's a correct way of doing this.

I apologize if I did not explain it correct - still a little new to Android.


问:
Replace Object Fields
I have an object that looks like this:

PetForm

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}
</code>```

I want to replace the fields with the values of null to an empty string like this:

Result:

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}
</code>```

I did the following:

```<code>Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");
</code>```

Am I missing something in this method?

答: If you're trying to assign the value in the && operator, you need just one equals sign: PetForm[key] = ""

Title: Replace Object Fields

Body:
I have an object that looks like this:

PetForm

{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}

I want to replace the fields with the values of null to an empty string like this:

Result:

{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}

I did the following:

Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");

Am I missing something in this method?


问:
How do I make a vertical graph based on inputs?
Input

```<code>1 1 3 1
</code>```

Output

```<code>  #
  #
####
</code>```

Input

```<code>0 3 0 4 5
</code>```

Output

```<code>    #
   ##
 # ##
 # ##
 # ##
</code>```

This is the code I have so far..

```<code>#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}
</code>```

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

答:
I've written this code based on the code in the question. This will get input number one by one. It can only consume up to 80 numbers.

```<code>void draw(const int* height, int length, int max)
{
    char* t_mat;
    char* mat;

    size_t mat_size = length * max * sizeof(char);

    t_mat = (char*)malloc(mat_size);
    mat = (char*)malloc(mat_size);

    // build transposed graph
    for (int i = 0; i < length; i++) {
        int value = height[i];

        for (int j = max - 1; j >= 0; j--) {
            if (j + value >= max)
                t_mat[i * max + j] = '#';
            else
                t_mat[i * max + j] = ' ';
        }
    }

    // tanspose t_mat to mat
    for (int i = 0; i < max; i++)
        for (int j = 0; j < length; j++)
            mat[i * length + j] = t_mat[j * max + i];

    // print
    for (int i = 0; i < max; i++) {
        for (int j = 0; j < length; j++)
            printf("%c", mat[i * length + j]);
        printf("\n");
    }

    free(t_mat);
    free(mat);
}

int main()
{
    int height[80], length=0, max=0;

    while (length < 80 && scanf("%d",&height[length++]) != EOF) {

        // update max number
        if (height[length-1] > max)
            max=height[length-1];

        // draw the graph with the updated number
        draw(height, length, max);
    }
}
</code>```

This method first creates a transposed version of the input. For example, if your input sequence is:

```<code>5 3 0 4 5
</code>```

this code first creates a char matrix that corresponds to:

```<code>#####  // 5 #'s in this row
  ###  // 3 #'s in this row
       // 0 #'s in this row
 ####  // 4 #'s in this row
#####  // 5 #'s in this row
</code>```

and then transpose it to get the desired graph:

```<code>#   #
#  ##
## ##
## ##
## ##
</code>```

If you compile it and run it with this input sequence: 5 3 0 4 5 you'll get following sequence of output.

```<code>5 // <- your input
#
#
#
#
#
3 // <- your input
#
#
##
##
##
0 // <- your input
#
#
##
##
##
4 // <- your input
#
#  #
## #
## #
## #
5 // <- your input
#   #
#  ##
## ##
## ##
## ##
</code>```

This program will terminate after consuming 80 input numbers.

Body:
Input

1 1 3 1

Output

  #
  #
####

Input

0 3 0 4 5

Output

    #
   ##
 # ##
 # ##
 # ##

This is the code I have so far..

#include <stdio.h>
int main (void){
    int height[80],length=0,max=0;
    while ((scanf("%d",&height[length++])) != EOF && length <=79) {
        if (height[length-1] > max) {
            max=height[length-1];
        }
    }
}

The input may not contain no more than 80 values.
I am not entire certain on how to add on more codes from here.

Body:
I've written this code based on the code in the question. This will get input number one by one. It can only consume up to 80 numbers.

void draw(const int* height, int length, int max)
{
    char* t_mat;
    char* mat;

    size_t mat_size = length * max * sizeof(char);

    t_mat = (char*)malloc(mat_size);
    mat = (char*)malloc(mat_size);

    // build transposed graph
    for (int i = 0; i < length; i++) {
        int value = height[i];

        for (int j = max - 1; j >= 0; j--) {
            if (j + value >= max)
                t_mat[i * max + j] = '#';
            else
                t_mat[i * max + j] = ' ';
        }
    }

    // tanspose t_mat to mat
    for (int i = 0; i < max; i++)
        for (int j = 0; j < length; j++)
            mat[i * length + j] = t_mat[j * max + i];

    // print
    for (int i = 0; i < max; i++) {
        for (int j = 0; j < length; j++)
            printf("%c", mat[i * length + j]);
        printf("\n");
    }

    free(t_mat);
    free(mat);
}

int main()
{
    int height[80], length=0, max=0;

    while (length < 80 && scanf("%d",&height[length++]) != EOF) {

        // update max number
        if (height[length-1] > max)
            max=height[length-1];

        // draw the graph with the updated number
        draw(height, length, max);
    }
}

This method first creates a transposed version of the input. For example, if your input sequence is:

5 3 0 4 5

this code first creates a char matrix that corresponds to:

#####  // 5 #'s in this row
  ###  // 3 #'s in this row
       // 0 #'s in this row
 ####  // 4 #'s in this row
#####  // 5 #'s in this row

and then transpose it to get the desired graph:

#   #
#  ##
## ##
## ##
## ##

If you compile it and run it with this input sequence: 5 3 0 4 5 you'll get following sequence of output.

5 // <- your input
#
#
#
#
#
3 // <- your input
#
#
##
##
##
0 // <- your input
#
#
##
##
##
4 // <- your input
#
#  #
## #
## #
## #
5 // <- your input
#   #
#  ##
## ##
## ##
## ##

This program will terminate after consuming 80 input numbers.


答:
var petForm = {
  name: "Bobo",
  type: "Golden Retriever",
  food: null,
  toys: null
}
Object.keys(petForm).forEach(function(item) {
  if (petForm[item] === null) {

    petForm[item] = "";
  }

})

console.log(petForm)```

Title: Replace Object Fields


问:
Python open() requires full path
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

```<code>with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)
</code>```

If I give the full path to the file, it will work. Why open() requires full path of the file ?

答: I have identified the problem. I was running my code on Visual Studio Code debugger. The root directory I have opened was above the level of my file. When I opened the same directory, it worked.</p>

Title: Python open() requires full path

Body:
I am writing a script to read a csv file. The csv file and script lies in the same directory. But when I tried to open the file it gives me FileNotFoundError: [Errno 2] No such file or directory: 'zipcodes.csv'. The code I used to read the file is

with open('zipcodes.csv', 'r') as zipcode_file:
    reader = csv.DictReader(zipcode_file)

If I give the full path to the file, it will work. Why open() requires full path of the file ?


问:
How can I add loop in after function?
My javascript is like this :

```<code>$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);
</code>```

I want to add loop in after like that

How can I do it?

答:
This how you can achieve what you need exactly.

```<code>$('#thumbnail-view').after((function(){
        // Here you can write you for loop and return the concatenated string
        var str = "";
        for(var i=0; i< 10; i++) {
            str = str + "<div>test</div>";
        }
        return str;
    })());
});
</code>```

It basically creates an IFFE. which executes immediately and returns a string for '$.after()' to consume.

Title: How can I add loop in after function?

Body:
My javascript is like this :

$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);

I want to add loop in after like that

How can I do it?

Body:
This how you can achieve what you need exactly.

$('#thumbnail-view').after((function(){
        // Here you can write you for loop and return the concatenated string
        var str = "";
        for(var i=0; i< 10; i++) {
            str = str + "<div>test</div>";
        }
        return str;
    })());
});

It basically creates an IFFE. which executes immediately and returns a string for '$.after()' to consume.


问:
Using service account for Google Analytics Reporting
I am trying to create a simple node app and I using service account to automate the OAuth Flow. While am able to successfully do this, am not able to retrieve the report from Google Analytics using this service account. I get the following error message,

```<code>{
  "error": {
    "code": 403,
    "message": "User does not have any Google Analytics account.",
    "status": "PERMISSION_DENIED"
  }
}
</code>```

I can't add this service account to the Analytics account as my owner account (under which I created this service account) has only read-only access. So how do I proceed? How can I grant this service account the same read-only access as my owner account? When I login into Google Analytics using my owner account, I am not able to perform any User Management as it has limited access.

Please help me on how to proceed here.

Thanks

答:
If using a service account, there is no way to proceed other than finding someone with user management permissions and have him add the account.

It is hard to see why you would expect it to be otherwise; the purpose of the permission system is to prevent unauthorized access, and it would do a pretty poor job if it suddenly allowed you to exceed your privileges by adding a user.

Body:
I am trying to create a simple node app and I using service account to automate the OAuth Flow. While am able to successfully do this, am not able to retrieve the report from Google Analytics using this service account. I get the following error message,

{
  "error": {
    "code": 403,
    "message": "User does not have any Google Analytics account.",
    "status": "PERMISSION_DENIED"
  }
}

I can't add this service account to the Analytics account as my owner account (under which I created this service account) has only read-only access. So how do I proceed? How can I grant this service account the same read-only access as my owner account? When I login into Google Analytics using my owner account, I am not able to perform any User Management as it has limited access.

Please help me on how to proceed here.

Thanks


问:
How do I access css/scss with react?
I have a react component where I am trying to change the background color of the css when clicking the div.

I know you can set the color in the component, but I am using this component many times, and don't to make multiple component files with just a different color, and even if I did, I am curious besides the fact.

How can I access (or even console.log to figure it out on my own) the css file and its properties through the component?  Thanks ahead of time.

答:
If you want to keep all background-color styles in your .css/.scss file, you will need to have a good className strategy to link the styles to your components. Here is my suggestion:

styles.scss

```<code>.blue {
  background-color: blue;

  &.clicked {
    background-color: red;
  }
}
</code>```

Container.js

```<code>import React from 'react';
import ClickableDiv from './ClickableDiv.js';

const Container = () => (
  <ClickableDiv className="blue">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;
</code>```

ClickableDiv.js

```<code>import React, { Component } from 'react';

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = { clicked: false };
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    this.setState({ clicked: true });
  }

  render() {
    const divClassName = [this.props.classname];
    if (this.state.clicked) divClassName.push('clicked');
    return (
      <div className={divClassName.join(' ').trim()} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;
</code>```

Rendered Markup

Unclicked:

```<code><div class="blue"><p>This is my text.</p></div>
</code>```

Clicked:

```<code><div class="blue clicked"><p>This is my text.</p></div>
</code>```

Title: How do I access css/scss with react?

Body:
If you want to keep all background-color styles in your .css/.scss file, you will need to have a good className strategy to link the styles to your components. Here is my suggestion:

styles.scss

.blue {
  background-color: blue;

  &.clicked {
    background-color: red;
  }
}

Container.js

import React from 'react';
import ClickableDiv from './ClickableDiv.js';

const Container = () => (
  <ClickableDiv className="blue">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;

ClickableDiv.js

import React, { Component } from 'react';

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = { clicked: false };
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    this.setState({ clicked: true });
  }

  render() {
    const divClassName = [this.props.classname];
    if (this.state.clicked) divClassName.push('clicked');
    return (
      <div className={divClassName.join(' ').trim()} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;

Rendered Markup

Unclicked:

<div class="blue"><p>This is my text.</p></div>

Clicked:

<div class="blue clicked"><p>This is my text.</p></div>


问:
Use Xcode 8 with iOS 11
I want to use Xcode 8 with iOS 11.

should I upgrade my Xcode. However, my code can't be built by the new compiler, so I want to stay with Xcode 8.

How can I achieve that?

Apple revealed several new iOS 11 features at WWDC 2017.

答:
Check this out: As of now this is only for Debugging on iOS device not Simulator

Download the SDK from Apple

Copy this iOS 11.0 image file to: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/

Restart Xcode.

Title: Use Xcode 8 with iOS 11


问:
How to create number list 1 until 9 and plus 1 at another row in php?
How to create number list in php 1 until 9 with this out put

1 2 3 4 5 6 7 8 9

2 3 4 5 6 7 8 9 1

3 4 5 6 7 8 9 1 2

4 5 6 7 8 9 1 2 3

5 6 7 8 9 1 2 3 4

6 7 8 9 1 2 3 4 5

7 8 9 1 2 3 4 5 6

8 9 1 2 3 4 5 6 7

9 1 2 3 4 5 6 7 8

Please Let me know ...

答:
Here's one that accepts a variable number of rows and columns:</p>

```<code><?php
$rows = 9;
$cols = 9;
for ($row = 0; $row < $rows; $row++) {
  $num = ($row % $cols);
  for ($col = 0; $col < $cols; $col++) {
      if (++$num == $cols + 1) {
          $num = 1;
      }
      echo $num . ' ';
  }
  echo PHP_EOL;
}
</code>```

Body:
Here's one that accepts a variable number of rows and columns:

<?php
$rows = 9;
$cols = 9;
for ($row = 0; $row < $rows; $row++) {
  $num = ($row % $cols);
  for ($col = 0; $col < $cols; $col++) {
      if (++$num == $cols + 1) {
          $num = 1;
      }
      echo $num . ' ';
  }
  echo PHP_EOL;
}


问:
How to search through POSTed form values using regex and return results
I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.

The members are stored in a SESSION variable:

```<code>$_SESSION['members'] = json_decode($jsonFile);
</code>```

but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!

-Manoj

答:
I think I'd be using a database to store the data rather than JSON so that you can use the LIKE searches, e.g.

```<code>SELECT * FROM users WHERE name LIKE 'Jon%'
</code>```

If you absolutely have to use JSON you could loop through all members and use a regexp like

```<code>preg_match('/^'.$term.'.*/i', $element, $matches);
</code>```

to check them all.

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.

The members are stored in a SESSION variable:

$_SESSION['members'] = json_decode($jsonFile);

but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!

-Manoj

Body:
I think I'd be using a database to store the data rather than JSON so that you can use the LIKE searches, e.g.

SELECT * FROM users WHERE name LIKE 'Jon%'

If you absolutely have to use JSON you could loop through all members and use a regexp like

preg_match('/^'.$term.'.*/i', $element, $matches);

to check them all.


问:
How can I get Express.js to 404 only on missing routes?
At the moment I have the following which sits below all my other routes:

```<code>app.get('*', function(req, res){
  console.log('404ing');
  res.render('404');
});
</code>```

And according to the logs, it is being fired even when the route is being matched above.  How can I get it to only fire when nothing is matched?

答:
I wanted a catch all that would render my 404 page only on missing routes and found it here in the error handling docs https://expressjs.com/en/guide/error-handling.html

```<code>app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(404).render('404.ejs')
})
</code>```

This worked for me.

Body:
At the moment I have the following which sits below all my other routes:

app.get('*', function(req, res){
  console.log('404ing');
  res.render('404');
});

And according to the logs, it is being fired even when the route is being matched above.  How can I get it to only fire when nothing is matched?

Body:
I wanted a catch all that would render my 404 page only on missing routes and found it here in the error handling docs https://expressjs.com/en/guide/error-handling.html

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(404).render('404.ejs')
})

This worked for me.


问:
Closure compiler source map = empty (Chrome) or wrong (Firefox) code window
I have a set of JavaScript files in 'src' folder compiled by Closure Compiler in a single file cw-around.js in 'src/comp' with generated source maps cw-around.js.map also in 'src/comp'.

"//# sourceMappingURL=xxx" is at the end of the compiled file cw-around.js.
xxx being a full HTTP link (local web server) to cw-around.js.map and being successfully tested in a browser.
{"version":3,"file":"cw-around.js" is the beginning of the cw-around.js.map file

In the Dev mode/sources file list, I can see the associated files in Chrome and Firefox (when I put a wrong xxx, I can see only the compiled cw-around.js file).

There, when I double click on an associated file (cw-demodata.js, one of the JavaScript file name that was included in the compiled file):

In Chrome 58 or 61 ("JavaScript source maps enabled" + "source map detected"), an empty code window is displayed.

In Firefox 54 ("show original sources" + "devtools.source-map.locations.enabled;true"), the HTML code of my calling web page is displayed.

What's wrong? How to investigate to identify what's wrong?

答:
I found a solution to my issue: to compile the js files and generate the source map in the same directory as the js files. The associated js files are now properly displayed in both Chrome and Firefox.

Previously, after successfully opening the compiled js file and the source map, it seems that the browser was unable to find and load the non compiled js files.
It would have been great to have an error message in the console to quickly spot the problem...


问:
Using ng-if inside ng-repeat doesn't work
I have an array called polls with many objects poll. Each poll has a property moduleState which is initally set to the string "notVoted". The moduleState for an individual poll may later  be set to the string "voted". Here is the template for one of my partials:

```<code><div ng-init="loadPage()">
    <div ng-repeat="poll in polls">
        <div ng-if="poll.moduleState  === 'notVoted'">
          //Template 1
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          //Template 2
        </div>
    </div>
</div>
</code>```

The problem is, both templates are used for each poll in polls. So if there were 3 poll objects in the array polls, the partial would put out:

Template 1

Template 2

Template 1

Template 2

Template 1

Template 2

I suspect this is because of a weird interaction between ng-if and ng-repeat. How can I get it so only one template per poll shows?

Edit: As requested, here is a console.log of a poll object. As you can see, moduleState is in fact set to "notVoted"

答:
Even though this is not the answer but this post represent how should we proceed for troubleshooting this sort of issues.

```<code><div ng-init="loadPage()">
    <div ng-repeat="poll in polls">
        <span>poll.moduleState: {{poll.moduleState}}</span>
        <div ng-if="poll.moduleState  === 'notVoted'">
          //Template 1
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          //Template 2
        </div>
    </div>
</div>
</code>```

note I have introduced test span to check how much time loop iterates and what is the value of that poll object property.

More ever you can also use some chrome extensions that extracts property value from the current runtime ng binding and shows in the developer tool. You can find that tool here. Explore how you can utilize the tool to find out what values are being bind in the dom element and get your issue resolved. :)

Hope this helps you.

Body:
I have an array called polls with many objects poll. Each poll has a property moduleState which is initally set to the string "notVoted". The moduleState for an individual poll may later  be set to the string "voted". Here is the template for one of my partials:

          //Template 1

          //Template 2

The problem is, both templates are used for each poll in polls. So if there were 3 poll objects in the array polls, the partial would put out:

Template 1

Template 2

Template 1

Template 2

Template 1

Template 2

I suspect this is because of a weird interaction between ng-if and ng-repeat. How can I get it so only one template per poll shows?

Edit: As requested, here is a console.log of a poll object. As you can see, moduleState is in fact set to "notVoted"

Body:
Even though this is not the answer but this post represent how should we proceed for troubleshooting this sort of issues.

<div ng-init="loadPage()">
    <div ng-repeat="poll in polls">
        <span>poll.moduleState: {{poll.moduleState}}</span>
        <div ng-if="poll.moduleState  === 'notVoted'">
          //Template 1
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          //Template 2
        </div>
    </div>
</div>

note I have introduced test span to check how much time loop iterates and what is the value of that poll object property.

More ever you can also use some chrome extensions that extracts property value from the current runtime ng binding and shows in the developer tool. You can find that tool here. Explore how you can utilize the tool to find out what values are being bind in the dom element and get your issue resolved. :)

Hope this helps you.


答:
You can build the string first, before calling the after() function.

For example, this appends the string 123456789 using a loop.

```<code>var res = "";
for (var i = 1; i <= 9; i++) {
    res += i;
}
$('#thumbnail-view').after(res);
</code>```

Title: How can I add loop in after function?

Body:
You can build the string first, before calling the after() function.

For example, this appends the string 123456789 using a loop.

var res = "";
for (var i = 1; i <= 9; i++) {
    res += i;
}
$('#thumbnail-view').after(res);


问:
Get Source of Current Tab in Google Chrome via Applescript
It's child's play to do this in Safari, which has good Applescript support. Google Chrome's AS support has just arrived so I'm giving them the benefit of the doubt. I am basically trying to grab the current HTML via the clipboard so I can get information out. We have some nifty commands like this:

```<code>tell application "Google Chrome"
 view source of active tab of window 1
 save active tab of window 1
 print active tab of window 1
 reload active tab of window 1
 go back active tab of window 1
 go forward active tab of window 1
 copy selection of active tab of window 1
 paste selection active tab of window 1
end tell
</code>```

but alas you can't say "set X to source of active tab of window 1". Anyone have any suggestions for me? My current ideas are to load the code I need in the background in Safari (pretty ugly) or try to display source and grab it with UI script, but that's also ugly. Also I keep encountering scripting bugs that keep it from working.

Any help would be appreciated.

答: Seeing as how Chrome's AS support has "just arrived" it is bound to be "exciting" to use. In trying some of the commands they have available in their dictionary, it looks as though they still have some kinks to work out. Until Google exposes a way in the API to get the source code more easily (and/or works out the related kinks), you'll have to use one of the alternatives you mention in your post. </p>

Body:
It's child's play to do this in Safari, which has good Applescript support. Google Chrome's AS support has just arrived so I'm giving them the benefit of the doubt. I am basically trying to grab the current HTML via the clipboard so I can get information out. We have some nifty commands like this:

tell application "Google Chrome"
 view source of active tab of window 1
 save active tab of window 1
 print active tab of window 1
 reload active tab of window 1
 go back active tab of window 1
 go forward active tab of window 1
 copy selection of active tab of window 1
 paste selection active tab of window 1
end tell

but alas you can't say "set X to source of active tab of window 1". Anyone have any suggestions for me? My current ideas are to load the code I need in the background in Safari (pretty ugly) or try to display source and grab it with UI script, but that's also ugly. Also I keep encountering scripting bugs that keep it from working.

Any help would be appreciated.


答:
Using interface to communicate between fragment and activity, for sample

create interface.

```<code>public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onClickToEnableTab();
}
</code>```

implement it in activity. Do the code to enable your tab

```<code>public class Activity implement OnFragmentInteractionListener{
    @Override
    public void onClickToEnableTab() {
       // TODO : Enable you tab layout
    }
}
</code>```

in fragment

```<code>public class YourFragment extends Fragment {
private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
}
</code>```

And then, in your fragment inside onClickListenner you can call

```<code>mListener.onClickToEnableTab();
</code>```

Title: Android get tabLayout from a fragment

Body:
I was wondering if there's a way to access the tabLayout from a fragment.

I declare my TabLayout below and I disable all the tabs.

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);

LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
    for(int i = 0; i < tabStrip.getChildCount(); i++) {
       tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
                return true;
           }
       });
    }

What I would like to do is be able to enable them in a fragment inside a ClickListener.

I am not sure I should declare the tabLayout static and access it like that or if there's a correct way of doing this.

I apologize if I did not explain it correct - still a little new to Android.

Body:
Using interface to communicate between fragment and activity, for sample

create interface.

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onClickToEnableTab();
}

implement it in activity. Do the code to enable your tab

public class Activity implement OnFragmentInteractionListener{
    @Override
    public void onClickToEnableTab() {
       // TODO : Enable you tab layout
    }
}

in fragment

public class YourFragment extends Fragment {
private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
}

And then, in your fragment inside onClickListenner you can call

mListener.onClickToEnableTab();


问:
How can I generate a WebApi2 URL without specifying a Name on the Route attribute with AttributeRouting?
I've configured my ASP.NET MVC5 application to use AttributeRouting for WebApi:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}
</code>```

I have an ApiController as follows:

```<code>[RoutePrefix("api/v1/subjects")]
public class SubjectsController : ApiController
{
    [Route("search")]
    [HttpPost]
    public SearchResultsViewModel Search(SearchCriteriaViewModel criteria)
    {
        //...
    }
}
</code>```

I would like to generate a URL to my WebApi controller action without having to specify an explicit route name.

According to this page on CodePlex, all MVC routes have a distinct name, even if it is not specified.

In the absence of a specified route name, Web API will generate a
  default route name. If there is only one attribute route for the
  action name on a particular controller, the route name will take the
  form "ControllerName.ActionName". If there are multiple attributes
  with the same action name on that controller, a suffix gets added to
  differentiate between the routes: "Customer.Get1", "Customer.Get2".

On ASP.NET, it doesn't say exactly what is the default naming convention, but it does indicate that every route has a name.

In Web API, every route has a name. Route names are useful for
  generating links, so that you can include a link in an HTTP response.

Based on these resources, and an answer by StackOverflow user Karhgath, I was led to believe that the following would produce a URL to my WebApi route:

```<code>@(Url.RouteUrl("Subjects.Search"))
</code>```

However, this produces an error:

A route named 'Subjects.Search' could not be found in the route
  collection.

I've tried a few other variants based on other answers I found on StackOverflow, none with success.

```<code>@(Url.Action("Search", "Subjects", new { httproute = "" }))

@(Url.HttpRouteUrl("Search.Subjects", new {}))
</code>```

In fact, even providing a Route name in the attribute only seems to work with:

```<code>@(Url.HttpRouteUrl("Search.Subjects", new {}))
</code>```

Where "Search.Subjects" is specified as the route name in the Route attribute.

I don't want to be forced to specify a unique name for my routes.

How can I generate a URL to my WebApi controller action without having to explicitly specify a route name in the Route attribute?

Is it possible that the default route naming scheme has changed or is documented incorrectly at CodePlex?

Does anyone have some insight on the proper way to retrieve a URL for a route that has been setup with AttributeRouting?

答:
Very first thing is, if you want to access a route then definitely you need a unique identifier for that just like any other variable we use in normal c# programming.

Hence if defining a unique name for each route is a headache for you, but still I think you will have to with it because the benefit its providing is much better.

Benefit: Think of a scenario where you want to change your route to a new value but it will require you to change that value across the applciation wherever you have used it.
In this scenario, it will be helpful.

Following is the code sample to generate link from route name.

```<code>public class BooksController : ApiController
{
    [Route("api/books/{id}", Name="GetBookById")]
    public BookDto GetBook(int id)
    {
        // Implementation not shown...
    }

    [Route("api/books")]
    public HttpResponseMessage Post(Book book)
    {
        // Validate and add book to database (not shown)

        var response = Request.CreateResponse(HttpStatusCode.Created);

        // Generate a link to the new book and set the Location header in the response.
        string uri = **Url.Link("GetBookById", new { id = book.BookId });**
        response.Headers.Location = new Uri(uri);
        return response;
    }
}
</code>```

Please read this link

And yes you are gonna need to define this routing name in order to access them with the ease you want to access. The convention based link generation you want is currently not available.

One more thing I would like to add here is, if this is really very concerning issue for you then we can write out own helper methods which will take two parameters {ControllerName} and {ActionName} and will return the route value using some logic.

Let us know if you really think that its worthy to do that.

Body:
I've configured my ASP.NET MVC5 application to use AttributeRouting for WebApi:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}

I have an ApiController as follows:

[RoutePrefix("api/v1/subjects")]
public class SubjectsController : ApiController
{
    [Route("search")]
    [HttpPost]
    public SearchResultsViewModel Search(SearchCriteriaViewModel criteria)
    {
        //...
    }
}

I would like to generate a URL to my WebApi controller action without having to specify an explicit route name.

According to this page on CodePlex, all MVC routes have a distinct name, even if it is not specified.

In the absence of a specified route name, Web API will generate a
  default route name. If there is only one attribute route for the
  action name on a particular controller, the route name will take the
  form "ControllerName.ActionName". If there are multiple attributes
  with the same action name on that controller, a suffix gets added to
  differentiate between the routes: "Customer.Get1", "Customer.Get2".

On ASP.NET, it doesn't say exactly what is the default naming convention, but it does indicate that every route has a name.

In Web API, every route has a name. Route names are useful for
  generating links, so that you can include a link in an HTTP response.

Based on these resources, and an answer by StackOverflow user Karhgath, I was led to believe that the following would produce a URL to my WebApi route:

@(Url.RouteUrl("Subjects.Search"))

However, this produces an error:

A route named 'Subjects.Search' could not be found in the route
  collection.

I've tried a few other variants based on other answers I found on StackOverflow, none with success.

@(Url.Action("Search", "Subjects", new { httproute = "" }))

@(Url.HttpRouteUrl("Search.Subjects", new {}))

In fact, even providing a Route name in the attribute only seems to work with:

@(Url.HttpRouteUrl("Search.Subjects", new {}))

Where "Search.Subjects" is specified as the route name in the Route attribute.

I don't want to be forced to specify a unique name for my routes.

How can I generate a URL to my WebApi controller action without having to explicitly specify a route name in the Route attribute?

Is it possible that the default route naming scheme has changed or is documented incorrectly at CodePlex?

Does anyone have some insight on the proper way to retrieve a URL for a route that has been setup with AttributeRouting?

Body:
Very first thing is, if you want to access a route then definitely you need a unique identifier for that just like any other variable we use in normal c# programming.

Hence if defining a unique name for each route is a headache for you, but still I think you will have to with it because the benefit its providing is much better.

Benefit: Think of a scenario where you want to change your route to a new value but it will require you to change that value across the applciation wherever you have used it.
In this scenario, it will be helpful.

Following is the code sample to generate link from route name.

public class BooksController : ApiController
{
    [Route("api/books/{id}", Name="GetBookById")]
    public BookDto GetBook(int id)
    {
        // Implementation not shown...
    }

    [Route("api/books")]
    public HttpResponseMessage Post(Book book)
    {
        // Validate and add book to database (not shown)

        var response = Request.CreateResponse(HttpStatusCode.Created);

        // Generate a link to the new book and set the Location header in the response.
        string uri = **Url.Link("GetBookById", new { id = book.BookId });**
        response.Headers.Location = new Uri(uri);
        return response;
    }
}

Please read this link

And yes you are gonna need to define this routing name in order to access them with the ease you want to access. The convention based link generation you want is currently not available.

One more thing I would like to add here is, if this is really very concerning issue for you then we can write out own helper methods which will take two parameters {ControllerName} and {ActionName} and will return the route value using some logic.

Let us know if you really think that its worthy to do that.


问:
Upload build/ipa for testing in TestFlight
I am using application loader to upload my IPA on TestFlight to make it available for testers to test the app.
Application loader shows a successfully uploaded message but when I log into iTunesConnect in Apple developer account, I don't see the build in TestFlight under that particular app.

This is what application loader shows.

This is what the iTunesConnect shows.

答: you need to invite internal and external tester to test app after invite in test flight show.</p>