问:
Feature format error when reading tfrecord (Cannot convert a ndarray into a Tensor or Operation)
I have been working for a long time on creating my own database to train a CNN. Now, I have a problem with reading data from the tfrecord file. I have successfully saved a tfrecord file, which contains two features: image and label. When I try to read it, it just read the first batch and then I get a error message.

The code for saving the tfrecord file is (I assumed only 5 files because of time):

```<code>#SAVE TFRECORD FILE

import tensorflow as tf
import numpy as np
import Image

image_filename = [('/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/00%03d.png' % x) for x in range(1,6)]

records_filename = '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/DS.tfrecord'
writer = tf.python_io.TFRecordWriter(records_filename)

original_images = []

for img_path in image_filename:

    image = np.array(Image.open(img_path))
    #img_label = 'GP'
    img_label = b'\x01'
    img_raw = image.tostring()

    example = tf.train.Example(features=tf.train.Features(feature={
        'image_raw': tf.train.Feature(bytes_list = tf.train.BytesList(value = [img_raw])),
        'label': tf.train.Feature(bytes_list = tf.train.BytesList(value = [img_label])),
        }))

    writer.write(example.SerializeToString())

writer.close()
</code>```

The code for reading that tfrecord file is:

```<code>#READ TFRECORD FILE

import tensorflow as tf
import skimage.io as io

IMAGE_HEIGHT = 24
IMAGE_WIDTH = 24
IMAGE_CHANNELS = 3
BATCH_SIZE = 2

tfrecords_filename = '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/DS.tfrecord'

def read_and_decode(filename_queue):

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example, features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'label': tf.FixedLenFeature([], tf.string),
        })

    image = tf.decode_raw(features['image_raw'], tf.uint8)
    image_reshape = tf.reshape(image, [IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])

    label = tf.cast(features['label'], tf.string)
    label_reshape = label

    images, label = tf.train.shuffle_batch([image_reshape, label_reshape],
                                           batch_size = 2,
                                           capacity = 30,
                                           num_threads = 2,
                                           min_after_dequeue = 10)
    return images, label

filename_queue = tf.train.string_input_producer([tfrecords_filename], num_epochs=10)
image, label = read_and_decode(filename_queue)

init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())

with tf.Session()  as sess:

    sess.run(init_op)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)

    for i in range(5):

        img, label = sess.run([image, label])
        print(img.shape)
        print(label)

        print('current batch')

        io.imshow(img[0, :, :, :])
        io.show()

        io.imshow(img[1, :, :, :])
        io.show()

    coord.request_stop()
    coord.join(threads)
</code>```

It is important to mention that if I change img, label = sess.run([image, label]) for img = sess.run(image) I have no error. That makes me think that the issue is related to the format of the label feature.

The error screen is similar to:

```<code>>>>
(2, 24, 24, 3)
['\x01' '\x01']
current batch

Traceback (most recent call last):
  File "/home/ag/Dropbox/DL/6_CNN_BD/DS2.py", line 52, in <module>
    img, label = sess.run([image, label])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 952, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 230, in for_fetch
    return _ListFetchMapper(fetch)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 337, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 238, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 271, in __init__
    % (fetch, type(fetch), str(e)))
TypeError: Fetch argument array(['\x01', '\x01'], dtype=object) has invalid type <type 'numpy.ndarray'>, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)
</code>```

I have tried in different ways but no success. Any suggestion for that problem?

答:
Here is the code, with some little changes that helped to fix the problem.</p>

```<code>#READ TFRECORD FILE

import tensorflow as tf
import skimage.io as io
import Image

IMAGE_HEIGHT = 24
IMAGE_WIDTH = 24
IMAGE_CHANNELS = 3
BATCH_SIZE = 5
MIN_AFTER_DEQUEUE = 10000
CAPACITY = MIN_AFTER_DEQUEUE+3*BATCH_SIZE
NUM_THREADS = 2

tfrecords_filename = ['/home/ag/Dropbox/DL/6_CNN_BD/data_resized/TFrecords/DS01.tfrecord', '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/TFrecords/DS02.tfrecord']

def read_and_decode(filename_queue):

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example, features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'label': tf.FixedLenFeature([], tf.string),
        })

    image = tf.decode_raw(features['image_raw'], tf.uint8)
    image_reshape = tf.reshape(image, [IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])

    label = tf.cast(features['label'], tf.string)
    label_reshape = label

    images, label = tf.train.shuffle_batch([image_reshape, label_reshape],
                                           batch_size = BATCH_SIZE,
                                           capacity = CAPACITY,
                                           num_threads = NUM_THREADS,
                                           min_after_dequeue = MIN_AFTER_DEQUEUE)
    #images, label = tf.train.batch([image_reshape, label_reshape], batch_size = 2, capacity = 30, num_threads = 2, min_after_dequeue = 10)

    return images, label
    #return image_reshape, label_reshape

filename_queue = tf.train.string_input_producer(tfrecords_filename, num_epochs=10)
image, label = read_and_decode(filename_queue)

init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())

with tf.Session()  as sess:

    sess.run(init_op)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)

    for i in range(1000):

        img, lbl = sess.run([image, label])
        print(i, img.shape, lbl)

        print('current batch')

        #img_save = Image.fromarray(img, 'RGB')
        #img_save.save("/home/ag/Dropbox/DL/6_CNN_BD/data_resized/02GraspableGraspingRectangles_RGB/" + str(i) + "-train.png")

        #io.imshow(img[0, :, :, :])
        #io.show()

        #io.imshow(img[1, :, :, :])
        #io.show()

    coord.request_stop()
    coord.join(threads)
</code>```

Body:
I have been working for a long time on creating my own database to train a CNN. Now, I have a problem with reading data from the tfrecord file. I have successfully saved a tfrecord file, which contains two features: image and label. When I try to read it, it just read the first batch and then I get a error message.

The code for saving the tfrecord file is (I assumed only 5 files because of time):

#SAVE TFRECORD FILE

import tensorflow as tf
import numpy as np
import Image

image_filename = [('/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/00%03d.png' % x) for x in range(1,6)]

records_filename = '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/DS.tfrecord'
writer = tf.python_io.TFRecordWriter(records_filename)

original_images = []

for img_path in image_filename:

    image = np.array(Image.open(img_path))
    #img_label = 'GP'
    img_label = b'\x01'
    img_raw = image.tostring()

    example = tf.train.Example(features=tf.train.Features(feature={
        'image_raw': tf.train.Feature(bytes_list = tf.train.BytesList(value = [img_raw])),
        'label': tf.train.Feature(bytes_list = tf.train.BytesList(value = [img_label])),
        }))

    writer.write(example.SerializeToString())

writer.close()

The code for reading that tfrecord file is:

#READ TFRECORD FILE

import tensorflow as tf
import skimage.io as io

IMAGE_HEIGHT = 24
IMAGE_WIDTH = 24
IMAGE_CHANNELS = 3
BATCH_SIZE = 2

tfrecords_filename = '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/01GraspableGraspingRectangles_RGB/DS.tfrecord'

def read_and_decode(filename_queue):

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example, features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'label': tf.FixedLenFeature([], tf.string),
        })

    image = tf.decode_raw(features['image_raw'], tf.uint8)
    image_reshape = tf.reshape(image, [IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])

    label = tf.cast(features['label'], tf.string)
    label_reshape = label

    images, label = tf.train.shuffle_batch([image_reshape, label_reshape],
                                           batch_size = 2,
                                           capacity = 30,
                                           num_threads = 2,
                                           min_after_dequeue = 10)
    return images, label

filename_queue = tf.train.string_input_producer([tfrecords_filename], num_epochs=10)
image, label = read_and_decode(filename_queue)

init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())

with tf.Session()  as sess:

    sess.run(init_op)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)

    for i in range(5):

        img, label = sess.run([image, label])
        print(img.shape)
        print(label)

        print('current batch')

        io.imshow(img[0, :, :, :])
        io.show()

        io.imshow(img[1, :, :, :])
        io.show()

    coord.request_stop()
    coord.join(threads)

It is important to mention that if I change img, label = sess.run([image, label]) for img = sess.run(image) I have no error. That makes me think that the issue is related to the format of the label feature.

The error screen is similar to:

>>>
(2, 24, 24, 3)
['\x01' '\x01']
current batch

Traceback (most recent call last):
  File "/home/ag/Dropbox/DL/6_CNN_BD/DS2.py", line 52, in <module>
    img, label = sess.run([image, label])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 952, in _run
    fetch_handler = _FetchHandler(self._graph, fetches, feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 408, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 230, in for_fetch
    return _ListFetchMapper(fetch)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 337, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 238, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 271, in __init__
    % (fetch, type(fetch), str(e)))
TypeError: Fetch argument array(['\x01', '\x01'], dtype=object) has invalid type <type 'numpy.ndarray'>, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)

I have tried in different ways but no success. Any suggestion for that problem?

Body:
Here is the code, with some little changes that helped to fix the problem.

#READ TFRECORD FILE

import tensorflow as tf
import skimage.io as io
import Image

IMAGE_HEIGHT = 24
IMAGE_WIDTH = 24
IMAGE_CHANNELS = 3
BATCH_SIZE = 5
MIN_AFTER_DEQUEUE = 10000
CAPACITY = MIN_AFTER_DEQUEUE+3*BATCH_SIZE
NUM_THREADS = 2

tfrecords_filename = ['/home/ag/Dropbox/DL/6_CNN_BD/data_resized/TFrecords/DS01.tfrecord', '/home/ag/Dropbox/DL/6_CNN_BD/data_resized/TFrecords/DS02.tfrecord']

def read_and_decode(filename_queue):

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example, features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'label': tf.FixedLenFeature([], tf.string),
        })

    image = tf.decode_raw(features['image_raw'], tf.uint8)
    image_reshape = tf.reshape(image, [IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS])

    label = tf.cast(features['label'], tf.string)
    label_reshape = label

    images, label = tf.train.shuffle_batch([image_reshape, label_reshape],
                                           batch_size = BATCH_SIZE,
                                           capacity = CAPACITY,
                                           num_threads = NUM_THREADS,
                                           min_after_dequeue = MIN_AFTER_DEQUEUE)
    #images, label = tf.train.batch([image_reshape, label_reshape], batch_size = 2, capacity = 30, num_threads = 2, min_after_dequeue = 10)

    return images, label
    #return image_reshape, label_reshape

filename_queue = tf.train.string_input_producer(tfrecords_filename, num_epochs=10)
image, label = read_and_decode(filename_queue)

init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())

with tf.Session()  as sess:

    sess.run(init_op)

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord = coord)

    for i in range(1000):

        img, lbl = sess.run([image, label])
        print(i, img.shape, lbl)

        print('current batch')

        #img_save = Image.fromarray(img, 'RGB')
        #img_save.save("/home/ag/Dropbox/DL/6_CNN_BD/data_resized/02GraspableGraspingRectangles_RGB/" + str(i) + "-train.png")

        #io.imshow(img[0, :, :, :])
        #io.show()

        #io.imshow(img[1, :, :, :])
        #io.show()

    coord.request_stop()
    coord.join(threads)


来源: stackexchange

问:
ASP.NET C# foreach only print last item in list
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

```<code>public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);
            }
        }
    }
</code>```

Here is the aspx part:

```<code><div class="admin-page">
      <h1>Valid Links:</h1>
        <asp:Literal ID="ValidLinksBox" runat="server" />
      <h1>Invalid Links:</h1>
        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />
  </div>
</code>```

This is the result:

Validate Links result

答:
You should append the text in the textbox, Please try the below code.</p>

```<code>        for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text += "<br/>" + validPages[i] + "<br/>";
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "
" + validPages[i] + "
";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("

{0}

", invalidPage);
            }
        }
    }

Here is the aspx part:

Valid Links:

        <asp:Literal ID="ValidLinksBox" runat="server" />

Invalid Links:

        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />

This is the result:

Validate Links result

Body:
You should append the text in the textbox, Please try the below code.

        for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text += "<br/>" + validPages[i] + "<br/>";
            }


问:
Show / Hide - Content on Button Click
Hello fellow programmer,

im getting used to Angular 2, therefore Typescript, so have mercy with me.

I have 5 Buttons which should enable or Disable Content on Click, like a Sidemenu.

HTML - Code

```<code>  <li class="navigation-items">
    <button class="dropdown-header" (click)="onSelect(2)">Link 2</button>
    <div *ngIf="DropdownVar == 2" class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
</code>```

Typescript - Code

```<code>DropdownVar = 0;

onSelect(x){
 this.DropdownVar = x;
 console.log(x);
}
</code>```

It seems that my var gets the propper value but my *ngif does not work.
Is there a better way to handle my Problem?

Additional i would like to have a little animation for the Content which i want to show, but i guess css is the way to go.

答:
You can directly do it with (click)="DropdownVar=2" , no need of onSelect method

```<code> <li class="navigation-items">
        <button class="dropdown-header" (click)="DropdownVar=2">Link 2</button>
        <div *ngIf="DropdownVar === 2" class="dropdown-content">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </li>
</code>```

And use === instead of == in Angular2

Title: Show / Hide - Content on Button Click

Body:
Hello fellow programmer,

im getting used to Angular 2, therefore Typescript, so have mercy with me.

I have 5 Buttons which should enable or Disable Content on Click, like a Sidemenu.

HTML - Code

    <button class="dropdown-header" (click)="onSelect(2)">Link 2</button>

      Link 1
      Link 2
      Link 3

Typescript - Code

DropdownVar = 0;

onSelect(x){
 this.DropdownVar = x;
 console.log(x);
}

It seems that my var gets the propper value but my *ngif does not work.
Is there a better way to handle my Problem?

Additional i would like to have a little animation for the Content which i want to show, but i guess css is the way to go.

Body:
You can directly do it with (click)="DropdownVar=2" , no need of onSelect method

 <li class="navigation-items">
        <button class="dropdown-header" (click)="DropdownVar=2">Link 2</button>
        <div *ngIf="DropdownVar === 2" class="dropdown-content">
          <a href="#">Link 1</a>
          <a href="#">Link 2</a>
          <a href="#">Link 3</a>
        </div>
      </li>

And use === instead of == in Angular2


问:
How to hook jenkins in bitbucket
I am not able to find how to add hooks of jenkin in bitbucket,
Previously there was a link in bitbucket for hooks but now it is missing

Please help

UPDATE:-
 All the solution that are given on stackoverflow are outdated as bitbucket has change few feature

答:
We use the Jenkins Bitbucket Webhook and it works well.

It's for Bitbucket Server 4.0.0 - 4.14.4

I hope this helps.

EDIT: Today (Nov, 2017), this add on is not free, but worth the cost.

Title: How to hook jenkins in bitbucket


问:
Hapi.js auth not working
This is my code now the problem here is when I am running this with hapi version 14.x.x or below it works for me perfectly fine but when I am running this with hapi version 15.0.1 or greater it gives me following error.

Is there any change in authentication process?

```<code>throw new Error(msgs.join(' ') || 'Unknown error');
    ^

    Error: Unknown authentication strategy UserAuth in /api/user/loginDetails
        at Object.exports.unique.exports.contain.exports.reachTemplate.exports.assert.condition [as assert] (F:\cbl\projects\lawn-mower\node_modules\hapi\node_modules\hoek\lib\index.js:736
    :11)
        at internals.Auth.test.internals.Auth._setupRoute (F:\cbl\projects\lawn-mower\node_modules\hapi\lib\auth.js:144:14)
</code>```

Sample route that I am using

```<code>  {
        method: 'POST',
        path: '/api/user/loginDetails',
        config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
            },
            validate: {
                payload: {

                },
                headers: UniversalFunctions.authorizationHeaderObj,
                failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
                'hapi-swagger': {
                    payloadType : 'form',
                    responses:Config.APP_CONSTANTS.swaggerDefaultResponseMessages
                }
            }
        }
    }
</code>```

strategy I am using

```<code>server.register(require('hapi-auth-bearer-token'), function (err) {
    console.log("aaaaa");
    server.auth.strategy('UserAuth', 'bearer-access-token', {
        allowQueryToken: false,
        allowMultipleHeaders: true,
        accessTokenName: 'accessToken',
        validateFunc: function (token, callback) {

        }
    });
});
</code>```

答:
This resolved the issue for me  plugin registrations are asynchronous from hapi version 15.x.x or above

Explanation : In version 14.x.x or lower things go synchronously like when we will start the server it will find register the plugins first then it will go for routes server.route(Routes).

This was fixed in hapi version 15.x.x and above now  plugin registrations are asynchronous so we need to register our plugins first then need to initialize the routes as in example below.

Click here to get more details about it from latest updates thread no is 3295

```<code>  server.register(Plugins, function (err) {

        if (err){
            console.log("===========err=========",err)
            server.error('Error while loading plugins : ' + err)
        }else {
            console.log("====================");
            server.route(Routes);
            server.log('info','Plugins Loaded');
        }
    });
</code>```

Title: Hapi.js auth not working

Body:
This is my code now the problem here is when I am running this with hapi version 14.x.x or below it works for me perfectly fine but when I am running this with hapi version 15.0.1 or greater it gives me following error.

Is there any change in authentication process?

throw new Error(msgs.join(' ') || 'Unknown error');
    ^

    Error: Unknown authentication strategy UserAuth in /api/user/loginDetails
        at Object.exports.unique.exports.contain.exports.reachTemplate.exports.assert.condition [as assert] (F:\cbl\projects\lawn-mower\node_modules\hapi\node_modules\hoek\lib\index.js:736
    :11)
        at internals.Auth.test.internals.Auth._setupRoute (F:\cbl\projects\lawn-mower\node_modules\hapi\lib\auth.js:144:14)

Sample route that I am using

  {
        method: 'POST',
        path: '/api/user/loginDetails',
        config: {
            auth: 'UserAuth',
            handler: function (request, reply) {
            },
            validate: {
                payload: {

                },
                headers: UniversalFunctions.authorizationHeaderObj,
                failAction: UniversalFunctions.failActionFunction
            },
            plugins: {
                'hapi-swagger': {
                    payloadType : 'form',
                    responses:Config.APP_CONSTANTS.swaggerDefaultResponseMessages
                }
            }
        }
    }

strategy I am using

server.register(require('hapi-auth-bearer-token'), function (err) {
    console.log("aaaaa");
    server.auth.strategy('UserAuth', 'bearer-access-token', {
        allowQueryToken: false,
        allowMultipleHeaders: true,
        accessTokenName: 'accessToken',
        validateFunc: function (token, callback) {

        }
    });
});

Body:
This resolved the issue for me  plugin registrations are asynchronous from hapi version 15.x.x or above

Explanation : In version 14.x.x or lower things go synchronously like when we will start the server it will find register the plugins first then it will go for routes server.route(Routes).

This was fixed in hapi version 15.x.x and above now  plugin registrations are asynchronous so we need to register our plugins first then need to initialize the routes as in example below.

Click here to get more details about it from latest updates thread no is 3295

  server.register(Plugins, function (err) {

        if (err){
            console.log("===========err=========",err)
            server.error('Error while loading plugins : ' + err)
        }else {
            console.log("====================");
            server.route(Routes);
            server.log('info','Plugins Loaded');
        }
    });


问:
Why are chinese characters still not showing in eclipse?
Even after using the guide from here to set the UTF-8 encoding, I went on and restarted eclipse but the text are still showing as weird characters like in my screenshot below.

Please advise what else can I do.

答: The guide you followed appears to be for text in the Eclipse console, while your problem is in the code editor. In my case (Neon.3) I solved that by setting UTF-8 in Window / Preferences / General / Workspace / Text file encoding.


问:
AngularJS not selecting the user-selection in a select box
I hope you guys are doing very good in your life. I am trying to make a select box with a default selection and allowing user to change the selection if they want.

Here is the JSFiddle: https://jsfiddle.net/ibnyusrat/jf5gggj0/

I am using this line to write the select box and its options:

```<code><select name="defaultQuality" ng-model="CreatePlayer.form.defaultQuality" ng-options="item.quality as item.label for item in CreatePlayer.getQualities() track by item.quality">
     <option style="display:none" value="">Select a quality</option>
</select>
</code>```

And the function that produces the options is:

```<code>CreatePlayer.getQualities = function(){
    var c = Array();
    c[0] = {quality:"SD",label:"SD"};
    if(CreatePlayer.form.p1080){
      c[1]={quality:"HD",label:"HD"}
    }
    return c;
 }
</code>```

If I remove this line:

```<code> CreatePlayer.form.defaultQuality = {quality:"SD",label:"SD"};
</code>```

It does seem to work. The issue is, if I don't define a default option, the select works as it should. But the moment I define a default option, and then I programmatically add an option to the list, changing selection causes the select box to revert to the empty value for the firs time, but in all the following times it works. So the user actually has to select the option twice to get it to recognize it.

Am I making a very obvious mistake here? Please help.

答:
Ok, so first thing first - This is a working solution: https://jsfiddle.net/jf5gggj0/1/

The first thing I did is to change CreatePlayer.getQualities from a function into an array. Why? Because it's much better performances-wise - Instead of calling this function on every digest cycle (Which happens a lot), Angular can now just track changes on the object.

Before:

```<code>CreatePlayer.getQualities = function(){
    var c = Array();
    c[0] = {quality:"SD",label:"SD"};
    if(CreatePlayer.form.p1080){
      c[1]={quality:"HD",label:"HD"}
    }
    return c;
}
</code>```

After:

```<code>CreatePlayer.getQualities = [{quality:"SD",label:"SD"}];
</code>```

Next thing I did was to add ng-change="CreatePlayer.enableHD()" on the checkbox, which call the following function when you check/uncheck it:

```<code>CreatePlayer.enableHD = function() {
    if(CreatePlayer.form.p1080){
        CreatePlayer.getQualities.push({quality:"HD",label:"HD"});
      return;
    }
    var a =  CreatePlayer.getQualities.map(function(e) { return e.quality; }).indexOf('HD');
    if( a !== -1 ) {
        CreatePlayer.getQualities.splice(a, 1);
    }
};
</code>```

What this function does is that it check if the box is checked (if(CreatePlayer.form.p1080){ ... }), and if it does, it adds the HD option to the select options, otherwise, it removes it:

```<code>var a =  CreatePlayer.getQualities.map(
   // return an array of the "quality" values, and keeps the same indexes as the original "getQualities" array
   function(e) { return e.quality; }
).indexOf('HD'); // Return the position of "HD" in order to remove it from the original "getQualities" array
</code>```

And then I use the a (Which holds the position of "HD") variable to remove the element from the array:  CreatePlayer.getQualities.splice(a, 1);

The last thing was to change the ngOptions expression.

Before:

```<code>ng-options="item.quality as item.label for item in CreatePlayer.getQualities() track by item.quality"
</code>```

After:

```<code>ng-options="item as item.label for item in CreatePlayer.getQualities"
</code>```

I removed the track by item.quality because the ngModel of the select is referencing to an element inside the CreatePlayer.getQualities array in the controller: CreatePlayer.form.defaultQuality = CreatePlayer.getQualities[0]; so now Angular manage the binding of the select value for you, and that's why it's not getting reset avery time you change the elements inside the getQualities array.

Well, that's about it :)

But just remember - Avoid as much as possible binding functions to the view, only bind members of the scope (properties/objects).

Body:
I hope you guys are doing very good in your life. I am trying to make a select box with a default selection and allowing user to change the selection if they want.

Here is the JSFiddle: https://jsfiddle.net/ibnyusrat/jf5gggj0/

I am using this line to write the select box and its options:

<select name="defaultQuality" ng-model="CreatePlayer.form.defaultQuality" ng-options="item.quality as item.label for item in CreatePlayer.getQualities() track by item.quality">
     <option style="display:none" value="">Select a quality</option>
</select>

And the function that produces the options is:

CreatePlayer.getQualities = function(){
    var c = Array();
    c[0] = {quality:"SD",label:"SD"};
    if(CreatePlayer.form.p1080){
      c[1]={quality:"HD",label:"HD"}
    }
    return c;
 }

If I remove this line:

 CreatePlayer.form.defaultQuality = {quality:"SD",label:"SD"};

It does seem to work. The issue is, if I don't define a default option, the select works as it should. But the moment I define a default option, and then I programmatically add an option to the list, changing selection causes the select box to revert to the empty value for the firs time, but in all the following times it works. So the user actually has to select the option twice to get it to recognize it.

Am I making a very obvious mistake here? Please help.

Body:
Ok, so first thing first - This is a working solution: https://jsfiddle.net/jf5gggj0/1/

The first thing I did is to change CreatePlayer.getQualities from a function into an array. Why? Because it's much better performances-wise - Instead of calling this function on every digest cycle (Which happens a lot), Angular can now just track changes on the object.

Before:

CreatePlayer.getQualities = function(){
    var c = Array();
    c[0] = {quality:"SD",label:"SD"};
    if(CreatePlayer.form.p1080){
      c[1]={quality:"HD",label:"HD"}
    }
    return c;
}

After:

CreatePlayer.getQualities = [{quality:"SD",label:"SD"}];

Next thing I did was to add ng-change="CreatePlayer.enableHD()" on the checkbox, which call the following function when you check/uncheck it:

CreatePlayer.enableHD = function() {
    if(CreatePlayer.form.p1080){
        CreatePlayer.getQualities.push({quality:"HD",label:"HD"});
      return;
    }
    var a =  CreatePlayer.getQualities.map(function(e) { return e.quality; }).indexOf('HD');
    if( a !== -1 ) {
        CreatePlayer.getQualities.splice(a, 1);
    }
};

What this function does is that it check if the box is checked (if(CreatePlayer.form.p1080){ ... }), and if it does, it adds the HD option to the select options, otherwise, it removes it:

var a =  CreatePlayer.getQualities.map(
   // return an array of the "quality" values, and keeps the same indexes as the original "getQualities" array
   function(e) { return e.quality; }
).indexOf('HD'); // Return the position of "HD" in order to remove it from the original "getQualities" array

And then I use the a (Which holds the position of "HD") variable to remove the element from the array:  CreatePlayer.getQualities.splice(a, 1);

The last thing was to change the ngOptions expression.

Before:

ng-options="item.quality as item.label for item in CreatePlayer.getQualities() track by item.quality"

After:

ng-options="item as item.label for item in CreatePlayer.getQualities"

I removed the track by item.quality because the ngModel of the select is referencing to an element inside the CreatePlayer.getQualities array in the controller: CreatePlayer.form.defaultQuality = CreatePlayer.getQualities[0]; so now Angular manage the binding of the select value for you, and that's why it's not getting reset avery time you change the elements inside the getQualities array.

Well, that's about it :)

But just remember - Avoid as much as possible binding functions to the view, only bind members of the scope (properties/objects).


问:
Sharing ASP.NET session cookies with a Java applet
I have a Java applet that runs inside a forms-authenticated aspx page. In the .NET 1.1 version of my site, the applet has access to the session cookie and is able to retrieve a file from the server, but in the .NET 2.0 version it fails to authenticate.

I have seen a couple of forum posts elsewhere that state that 2.0 sets cookies to HttpOnly by default, but the solutions given haven't worked for me so far. I also read somewhere that 2.0 may be discriminating based on user-agent.

Does anyone have any experience or insight into this?

答: Filip is both correct and incorrect, at least wrt to Java and ASP.NET. An applet can get access to the ASP.NET session by cheating. In my case, we added the session id as a parameter to the applet, which the applet then adds as a cookie in it's requests. Seems to work ok. (We encrypted the session id to foil those nasty hacker folk!)</p>

OwnerDisplayName: Aidan

ContentLicense: CC BY-SA 2.5


问:
How to swipe ViewPager images automatically using TimeTask
Hi I am new in android and in my app I have a lot of images in my ArrayList that 's
why I want to swipe those images automatically for every 3 seconds with help of Timetasker and this process is continuously need to repeating up to we close app. Can some body help me please

MainActivity:-

```<code>public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;

    Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
    String[] imagesName = {"image1","image2","image3","image4"};

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

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
        viewPager.setAdapter(adapter);
    }
}
</code>```

CustomAdapter:-

```<code>public class CustomAdapter extends PagerAdapter{

    private Activity activity;
    private Integer[] imagesArray;
    private String[] namesArray;

    public CustomAdapter(Activity activity,Integer[] imagesArray,String[] namesArray){

        this.activity = activity;
        this.imagesArray = imagesArray;
        this.namesArray = namesArray;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        LayoutInflater inflater = ((Activity)activity).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imagesArray[position]);
        TextView textView1 = (TextView) viewItem.findViewById(R.id.textview);
        textView1.setText(namesArray[position]);
        ((ViewPager)container).addView(viewItem);

        return viewItem;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return imagesArray.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub
        return view == ((View)object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // TODO Auto-generated method stub
        ((ViewPager) container).removeView((View) object);
    }
}
</code>```

答:
Another version of the answer:-</p>

```<code>                    private int currentPage = -1;
                    // start auto scroll of viewpager
                    final Handler handler = new Handler();
                    final Runnable Update = new Runnable() {
                        public void run() {
                            viewPager.setCurrentItem(++currentPage, true);
                            // go to initial page i.e. position 0
                            if (currentPage == NUM_PAGES -1) {
                                currentPage = -1;
                                // ++currentPage will make currentPage = 0
                            }
                        }
                    };

                    timer = new Timer(); // This will create a new Thread
                    timer.schedule(new TimerTask() { // task to be scheduled

                        @Override
                        public void run() {
                            handler.post(Update);
                        }
                    }, 500, 1500);
</code>```

Body:
Hi I am new in android and in my app I have a lot of images in my ArrayList that 's
why I want to swipe those images automatically for every 3 seconds with help of Timetasker and this process is continuously need to repeating up to we close app. Can some body help me please

MainActivity:-

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;

    Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
    String[] imagesName = {"image1","image2","image3","image4"};

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

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
        viewPager.setAdapter(adapter);
    }
}

CustomAdapter:-

public class CustomAdapter extends PagerAdapter{

    private Activity activity;
    private Integer[] imagesArray;
    private String[] namesArray;

    public CustomAdapter(Activity activity,Integer[] imagesArray,String[] namesArray){

        this.activity = activity;
        this.imagesArray = imagesArray;
        this.namesArray = namesArray;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        LayoutInflater inflater = ((Activity)activity).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imagesArray[position]);
        TextView textView1 = (TextView) viewItem.findViewById(R.id.textview);
        textView1.setText(namesArray[position]);
        ((ViewPager)container).addView(viewItem);

        return viewItem;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return imagesArray.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub
        return view == ((View)object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // TODO Auto-generated method stub
        ((ViewPager) container).removeView((View) object);
    }
}

Body:
Another version of the answer:-

                    private int currentPage = -1;
                    // start auto scroll of viewpager
                    final Handler handler = new Handler();
                    final Runnable Update = new Runnable() {
                        public void run() {
                            viewPager.setCurrentItem(++currentPage, true);
                            // go to initial page i.e. position 0
                            if (currentPage == NUM_PAGES -1) {
                                currentPage = -1;
                                // ++currentPage will make currentPage = 0
                            }
                        }
                    };

                    timer = new Timer(); // This will create a new Thread
                    timer.schedule(new TimerTask() { // task to be scheduled

                        @Override
                        public void run() {
                            handler.post(Update);
                        }
                    }, 500, 1500);


问:
AWS beanstalk wordpress
I was trying to setting up my AWS beanstalk by following the implementation guide provided by AWS.

But when I got to the "Launch an Elastic Beanstalk Environment" section, this message appeared which basically said the app is not created.

Here's the message:

[Instance: i-088472611e1ef4405] Command failed on instance. Return
  code: 1 Output: ln: failed to create symbolic link
  'wp-content/uploads': No such file or directory. container_command
  2link in wordpress-beanstalk/.ebextensions/efs-mount.config failed.
  For more detail, check /var/log/eb-activity.log using console or EB
  CLI.

Does anyone have the same problem or know how to resolve this?

答:
This is the mounting error of EFS .
EB is using EFS storage to store the wordpress files .

Please check the no.7 in documentation .

"Modify the configuration files in the .ebextensions folder with the IDs of your default VPC  and subnets, and your public IP address."

Please edit the efs-create.config file inside the .ebextension folder.

Title: AWS beanstalk wordpress


问:
Sum calculation of excel column - PHP Excel
I need to store sum of columns in a cell .The column is dynamically created.So I can't use the formula

=SUM(K8:K894)

in

```<code>    for($k=9;count($columns);$k++){
         $objPHPExcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($k,4,'=SUM(K8:K894)');
     }
</code>```

Please give me a solution.Please see my screenshot.I need to show the sum of column col1,col2,col3 just 1 row above the headers.

答:
No need to add the for loop.
You can try this: (assuming you want to add value from K8 to some dynamic value)

```<code>$objPHPExcel->getActiveSheet()
    ->setCellValue("<Your Column No from where you want to THE SUM VALUE>",
       "=SUM(<Your Column No from where you want to start adding i.e K>8:<Your Column No from where you want to start adding i.e K>".count($columns).")")
);
</code>```

Body:
I need to store sum of columns in a cell .The column is dynamically created.So I can't use the formula

=SUM(K8:K894)

in

    for($k=9;count($columns);$k++){
         $objPHPExcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($k,4,'=SUM(K8:K894)');
     }

Please give me a solution.Please see my screenshot.I need to show the sum of column col1,col2,col3 just 1 row above the headers.

Body:
No need to add the for loop.
You can try this: (assuming you want to add value from K8 to some dynamic value)

$objPHPExcel->getActiveSheet()
    ->setCellValue("<Your Column No from where you want to THE SUM VALUE>",
       "=SUM(<Your Column No from where you want to start adding i.e K>8:<Your Column No from where you want to start adding i.e K>".count($columns).")")
);


问:
Trying to find a string in an array, but linear/sequential search doesn't work
Below I have code which puts separate lines from a text file into an array. It asks the user to type in a string, and subsequently looks for the string in the array and see if the strings equals an element of the array. If so, it says it does and says which element it equals, and if not it says it could not find it. However, this code always says it can't find the line even though I can clearly see that the input equals an element from the array. What is incorrect here? I have no clue where the problem lies so below is the code for creating the array and the linear search algorithm:</p>

```<code>public static void main(String[] args) throws FileNotFoundException
{

File file = new File("text.txt"); //puts separate lines of file into an array
Scanner text = new Scanner(file);
String[] Array = new String[10];

for (int i = 0; i < 10 && text.hasNextLine(); i++)
{
    String line = text.nextLine();
    if (line.isEmpty())
    {
        continue;

    }
    Array[i] = line;
    System.out.printf("Element %d of the array is: %s%n", i, Array[i]);

}

Scanner input = new Scanner(System.in); //performs sequential search based on user input
System.out.println("Type the line you want to find: ");
String line = input.next();
int pos = 0;
boolean found = false;
while (pos < Array.length && !found)
{
    if(Array[pos]== line)
    {
        found = true;
    }
    else
    {
        pos++;
    }

}
 if (found)
 {
     System.out.println("Found at position: " + pos);

 }
 else
 {
     System.out.println("Could not find " + line);

 }

}
</code>```

答:
In your while loop use equals method for String comparison instead of ==

== works on Strings iff they are both constants (created like "XXX"). If they are created like new String("Test") they are not constants so:

new String("A") == new String("A") will produce false, but new String("A").equals(new String("A")) will produce true

"A" == "A" will produce true and "A".equals("A") will produce true aswell

Body:
Below I have code which puts separate lines from a text file into an array. It asks the user to type in a string, and subsequently looks for the string in the array and see if the strings equals an element of the array. If so, it says it does and says which element it equals, and if not it says it could not find it. However, this code always says it can't find the line even though I can clearly see that the input equals an element from the array. What is incorrect here? I have no clue where the problem lies so below is the code for creating the array and the linear search algorithm:

public static void main(String[] args) throws FileNotFoundException
{

File file = new File("text.txt"); //puts separate lines of file into an array
Scanner text = new Scanner(file);
String[] Array = new String[10];

for (int i = 0; i < 10 && text.hasNextLine(); i++)
{
    String line = text.nextLine();
    if (line.isEmpty())
    {
        continue;

    }
    Array[i] = line;
    System.out.printf("Element %d of the array is: %s%n", i, Array[i]);

}

Scanner input = new Scanner(System.in); //performs sequential search based on user input
System.out.println("Type the line you want to find: ");
String line = input.next();
int pos = 0;
boolean found = false;
while (pos < Array.length && !found)
{
    if(Array[pos]== line)
    {
        found = true;
    }
    else
    {
        pos++;
    }

}
 if (found)
 {
     System.out.println("Found at position: " + pos);

 }
 else
 {
     System.out.println("Could not find " + line);

 }

}


问:
How do I select distinct values from multiple mysql columns and put them in one PHP array?
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

```<code>genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz
</code>```

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

答:
Unless you've denormalized (2) genres into the three columns for performance reasons, there should be a separate table relating songs and genres:

```<code>CREATE TABLE SongGenres (
    song INT NOT NULL REFERENCES Songs (id) ON DELETE CASCADE,
    genre VARCHAR(32) NOT NULL,
    UNIQUE INDEX (song, genre),
    INDEX genres (genre) -- improves performance for getting genre names
) Engine=InnoDB;
</code>```

This does away with the requirement for ("Cross Road Blues" can be filed under "Blues" and "Delta Blues", but that's about it) and artificial limitation of (A3's country acid house gospel comes to mind) three genres per song. If you have a limited set of genres, you might want to make the genre column enumerated. The SongGenres table simplifies getting all genres:

```<code>SELECT UNIQUE genre FROM SongGenres;
</code>```

Alternatively, you could normalize further and create a separate table for genres:

```<code>CREATE TABLE Genres (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(32) NOT NULL,
    UNIQUE INDEX (name)
) Engine=InnoDB;

CREATE TABLE SongGenres (
    song INT NOT NULL REFERENCES Songs (id) ON DELETE CASCADE,
    genre INT NOT NULL REFERENCES Genres (id) ON DELETE RESTRICT,
    UNIQUE INDEX (song, genre)
) Engine=InnoDB;
</code>```

which simplifies getting all genre names even more (though this is only a secondary advantage):

```<code>SELECT name FROM Genres;
</code>```

A primary advantage to a Genres table is data correctness: if someone misspells a genre, it won't be found in the Genres table. A potential disadvantage is that it limits the valid genres to those in the table. Of course, it makes sense to give the user accounts that have INSERT privileges on SongGenres, so this limitation isn't a serious one. Once you start adding new genres, you're faced with the same problem as when there wasn't a Genre tables: typos. Rather than adding new genres that aren't found in the Genres table, look for similar ones (using e.g. the Levenshtein distance or SOUNDS LIKE) and, if any are found, ask the user if they want to replace the genre with one of what was found or keep the original genre (and add it to the genre list).

Here's what the data would look like in the first case (two tables, Songs and SongGenres):

```mysql> SELECT * FROM Songs;
+----+---------------------+--------+----
| id | title               | artist | ...
+----+---------------------+--------+----
|  1 | Cross Road Blues    |  ...
|  2 | Peace In the Valley |  ...
+----+---------------------+--------+----
2 rows in set (0.00 sec)

mysql> SELECT * FROM SongGenres;
+------+-------------+
| song | genre       |
+------+-------------+
|    2 | acid        |
|    1 | blues       |
|    2 | country     |
|    1 | delta blues |
|    2 | gospel      |
|    2 | house       |
|    2 | techno      |
+------+-------------+
7 rows in set (0.00 sec)

mysql> SELECT s.title, sg.genre FROM Songs AS s JOIN SongGenres AS sg ON s.id=sg.song;
+---------------------+-------------+
| title               | genre       |
+---------------------+-------------+
| Cross Road Blues    | blues       |
| Cross Road Blues    | delta blues |
| Peace In the Valley | acid        |
| Peace In the Valley | country     |
| Peace In the Valley | gospel      |
| Peace In the Valley | house       |
| Peace In the Valley | techno      |
+---------------------+-------------+
7 rows in set (0.00 sec)
```

With a separate Genres table, the data in Songs would look the same, but in the other tables  we'd have something like:

```mysql> SELECT * FROM Genres;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | acid        |
|  2 | blues       |
|  3 | classical   |
|  4 | country     |
|  5 | delta blues |
|  6 | folk        |
|  7 | gospel      |
|  8 | hip-hop     |
|  9 | house       |
...
| 18 | techno      |
+----+-------------+
18 rows in set (0.00 sec)

mysql> SELECT * FROM SongGenres;
+------+-------+
| song | genre |
+------+-------+
|    1 |     2 |
|    1 |     5 |
|    2 |     1 |
|    2 |     4 |
|    2 |     7 |
|    2 |     9 |
|    2 |    18 |
+------+-------+
7 rows in set (0.00 sec)

mysql> SELECT s.title, g.name AS genre
    ->   FROM Songs AS s
    ->     JOIN SongGenres AS sg ON s.id=sg.song
    ->     JOIN Genres AS g ON sg.genre=g.id;
+---------------------+-------------+
| title               | genre       |
+---------------------+-------------+
| Cross Road Blues    | blues       |
| Cross Road Blues    | delta blues |
| Peace In the Valley | acid        |
| Peace In the Valley | country     |
| Peace In the Valley | gospel      |
| Peace In the Valley | house       |
| Peace In the Valley | techno      |
+---------------------+-------------+
7 rows in set (0.00 sec)
```

Body:
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

Body:
Unless you've denormalized (2) genres into the three columns for performance reasons, there should be a separate table relating songs and genres:

CREATE TABLE SongGenres (
    song INT NOT NULL REFERENCES Songs (id) ON DELETE CASCADE,
    genre VARCHAR(32) NOT NULL,
    UNIQUE INDEX (song, genre),
    INDEX genres (genre) -- improves performance for getting genre names
) Engine=InnoDB;

This does away with the requirement for ("Cross Road Blues" can be filed under "Blues" and "Delta Blues", but that's about it) and artificial limitation of (A3's country acid house gospel comes to mind) three genres per song. If you have a limited set of genres, you might want to make the genre column enumerated. The SongGenres table simplifies getting all genres:

SELECT UNIQUE genre FROM SongGenres;

Alternatively, you could normalize further and create a separate table for genres:

CREATE TABLE Genres (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(32) NOT NULL,
    UNIQUE INDEX (name)
) Engine=InnoDB;

CREATE TABLE SongGenres (
    song INT NOT NULL REFERENCES Songs (id) ON DELETE CASCADE,
    genre INT NOT NULL REFERENCES Genres (id) ON DELETE RESTRICT,
    UNIQUE INDEX (song, genre)
) Engine=InnoDB;

which simplifies getting all genre names even more (though this is only a secondary advantage):

SELECT name FROM Genres;

A primary advantage to a Genres table is data correctness: if someone misspells a genre, it won't be found in the Genres table. A potential disadvantage is that it limits the valid genres to those in the table. Of course, it makes sense to give the user accounts that have INSERT privileges on SongGenres, so this limitation isn't a serious one. Once you start adding new genres, you're faced with the same problem as when there wasn't a Genre tables: typos. Rather than adding new genres that aren't found in the Genres table, look for similar ones (using e.g. the Levenshtein distance or SOUNDS LIKE) and, if any are found, ask the user if they want to replace the genre with one of what was found or keep the original genre (and add it to the genre list).

Here's what the data would look like in the first case (two tables, Songs and SongGenres):

mysql> SELECT * FROM Songs;
+----+---------------------+--------+----
| id | title               | artist | ...
+----+---------------------+--------+----
|  1 | Cross Road Blues    |  ...
|  2 | Peace In the Valley |  ...
+----+---------------------+--------+----
2 rows in set (0.00 sec)

mysql> SELECT * FROM SongGenres;
+------+-------------+
| song | genre       |
+------+-------------+
|    2 | acid        |
|    1 | blues       |
|    2 | country     |
|    1 | delta blues |
|    2 | gospel      |
|    2 | house       |
|    2 | techno      |
+------+-------------+
7 rows in set (0.00 sec)

mysql> SELECT s.title, sg.genre FROM Songs AS s JOIN SongGenres AS sg ON s.id=sg.song;
+---------------------+-------------+
| title               | genre       |
+---------------------+-------------+
| Cross Road Blues    | blues       |
| Cross Road Blues    | delta blues |
| Peace In the Valley | acid        |
| Peace In the Valley | country     |
| Peace In the Valley | gospel      |
| Peace In the Valley | house       |
| Peace In the Valley | techno      |
+---------------------+-------------+
7 rows in set (0.00 sec)

With a separate Genres table, the data in Songs would look the same, but in the other tables  we'd have something like:

mysql> SELECT * FROM Genres;
+----+-------------+
| id | name        |
+----+-------------+
|  1 | acid        |
|  2 | blues       |
|  3 | classical   |
|  4 | country     |
|  5 | delta blues |
|  6 | folk        |
|  7 | gospel      |
|  8 | hip-hop     |
|  9 | house       |
...
| 18 | techno      |
+----+-------------+
18 rows in set (0.00 sec)

mysql> SELECT * FROM SongGenres;
+------+-------+
| song | genre |
+------+-------+
|    1 |     2 |
|    1 |     5 |
|    2 |     1 |
|    2 |     4 |
|    2 |     7 |
|    2 |     9 |
|    2 |    18 |
+------+-------+
7 rows in set (0.00 sec)

mysql> SELECT s.title, g.name AS genre
    ->   FROM Songs AS s
    ->     JOIN SongGenres AS sg ON s.id=sg.song
    ->     JOIN Genres AS g ON sg.genre=g.id;
+---------------------+-------------+
| title               | genre       |
+---------------------+-------------+
| Cross Road Blues    | blues       |
| Cross Road Blues    | delta blues |
| Peace In the Valley | acid        |
| Peace In the Valley | country     |
| Peace In the Valley | gospel      |
| Peace In the Valley | house       |
| Peace In the Valley | techno      |
+---------------------+-------------+
7 rows in set (0.00 sec)


问:
How do I screen out NaNs when comparing floats in Ruby?
I'm using Rails 5 wiht Ruby 2.4.  How do I determine if a variable is a number?  I thought is_a?(Numeric) was the way to go, but apparently not with me.  I have this code

```<code>      puts "guesses arr: #{guesses_arr}"
      guesses_arr.map!{|str| str.is_a?(Numeric) && str == guesses_arr.max ? str : 0}
</code>```

which dies with

```<code>guesses arr: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
ArgumentError: comparison of Float with NaN failed
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `max'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `block (2 levels) in guess_headers_from_data_cols'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `map!'
</code>```

I'm unable to reproduce this in a console because I can't seem to produce an array with all those "NaN" values.  The point is, how do I make sure those don't get compared in my loop?

答:
You can produce an array of NaN values in the console like so:

```<code>[ 0.0 / 0.0 ] * 3
# => [NaN, NaN, NaN]
</code>```

It's not entirely clear what your code is doing, but it might be worth noting that it's the max which is throwing the exception, and not the equality test. Incidentally, if you are trying to compare each array value against the maximum value - you might want to max outside of the map, to avoid having to evaluate it multiple times.

Building on top the other answer here on rejecting NaNs, you can put it all together to get something like:

```<code># set up dummy data - 2 values and 3 NaNs
guesses_arr = [ 0.0 / 0.0 ] * 3 + [ 2.0, 3.0 ]
puts "guesses arr: #{guesses_arr}"
# => [NaN, NaN, NaN, 2.0, 3.0]

# remove NaNs in place
guesses_arr.reject!(&:nan?)
maximum = guesses_arr.max
guesses_arr.map!{|str| str.is_a?(Numeric) && str == maximum ? str : 0}
# => [ 0, 3.0 ]
</code>```

Edit: if you have integers mixed up in the array, try converting them into floats first:

```<code># set up dummy data - including floats and integers
guesses_arr = [ 0.0 / 0.0 ] * 3 + [ 2.0, 3.0, 0 ]
guesses_arr.map!(&:to_f).reject!(&:nan?)
# => [ 2.0, 3.0, 0.0 ]
</code>```

Body:
I'm using Rails 5 wiht Ruby 2.4.  How do I determine if a variable is a number?  I thought is_a?(Numeric) was the way to go, but apparently not with me.  I have this code

      puts "guesses arr: #{guesses_arr}"
      guesses_arr.map!{|str| str.is_a?(Numeric) && str == guesses_arr.max ? str : 0}

which dies with

guesses arr: [NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN]
ArgumentError: comparison of Float with NaN failed
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `max'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `block (2 levels) in guess_headers_from_data_cols'
    from /Users/davea/Documents/workspace/myproject/app/services/text_table_to_race_time_converter_service.rb:2121:in `map!'

I'm unable to reproduce this in a console because I can't seem to produce an array with all those "NaN" values.  The point is, how do I make sure those don't get compared in my loop?

Body:
You can produce an array of NaN values in the console like so:

[ 0.0 / 0.0 ] * 3
# => [NaN, NaN, NaN]

It's not entirely clear what your code is doing, but it might be worth noting that it's the max which is throwing the exception, and not the equality test. Incidentally, if you are trying to compare each array value against the maximum value - you might want to max outside of the map, to avoid having to evaluate it multiple times.

Building on top the other answer here on rejecting NaNs, you can put it all together to get something like:

# set up dummy data - 2 values and 3 NaNs
guesses_arr = [ 0.0 / 0.0 ] * 3 + [ 2.0, 3.0 ]
puts "guesses arr: #{guesses_arr}"
# => [NaN, NaN, NaN, 2.0, 3.0]

# remove NaNs in place
guesses_arr.reject!(&:nan?)
maximum = guesses_arr.max
guesses_arr.map!{|str| str.is_a?(Numeric) && str == maximum ? str : 0}
# => [ 0, 3.0 ]

Edit: if you have integers mixed up in the array, try converting them into floats first:

# set up dummy data - including floats and integers
guesses_arr = [ 0.0 / 0.0 ] * 3 + [ 2.0, 3.0, 0 ]
guesses_arr.map!(&:to_f).reject!(&:nan?)
# => [ 2.0, 3.0, 0.0 ]


问:
Adding a complete row to a table from a DAO.Recordset
I have an access table containing product information with 100 Columns (it is a bought system so not of my creation). I want to be able to copy a row and insert it as a new row with 3 fields updated. I am using VBA on an access DB.

I am selecting the row I want to copy (Select Product.* FROM .....) and putting it into a DAO.Recordset. This works fine. I then want to insert this data back into the table as a new row with all the same data apart from the Product ID (key) and the Product short description.

As there is 100 columns I am trying to avoid typing in all the column names and assigning the values individually. Is there a way to insert from a DAO.Recordset so I can avoid typing in all the columns?  if not is there another way to avoid typing in all the columns and all the values? It would save me a very big insert statement!

Many thanks

Tony

答:
You can loop the Fields collection of the recordset to do this.

This approach may be more maintainable then a giant INSERT statement if the table structure changes from time to time.

If the table is static, I would rather use a saved INSERT query with parameters for the columns that are modified.

Sub CopyProductRow()

    Dim rsSrc As DAO.Recordset
    Dim rsTgt As DAO.Recordset
    Dim fld As DAO.Field
    Dim sFld As String

    Set rsSrc = CurrentDb.OpenRecordset("SELECT * FROM Products WHERE ProductID = 4711", dbOpenSnapshot)
    Set rsTgt = CurrentDb.OpenRecordset("Products", dbOpenDynaset, dbAppendOnly)

    rsTgt.AddNew

    For Each fld In rsSrc.Fields
        sFld = fld.Name
        Select Case sFld
            ' special cases
            Case "ProductID": rsTgt(sFld).Value = GetNewProductID()
                              ' or if ProductID is AutoNumber, don't assign anything
            Case "ProductDesc": rsTgt(sFld).Value = "my new description"
            ' all other field values are simply copied
            Case Else: rsTgt(sFld).Value = fld.Value
        End Select
    Next fld

    rsTgt.Update
    rsTgt.Close
    rsSrc.Close

End Sub
```


问:
View transition on scroll view
I have set up a view containing a scrollview, I am attempting to allow the user to close the view by swiping down on the scroll view.

I have used the code below which as you can see dismisses the view controller when the scrollview y position is greater than -150.

When it reaches that point the view disappears, but ideally what I would like is for the view to continue moving downwards until it is out of view.

How would I go about this?

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y < 0) {
        self.view.frame.origin.y = abs(scrollView.contentOffset.y) * 2
    }
    if (scrollView.contentOffset.y < -150) {
        dismiss(animated: false, completion: nil)
    }
}
</code>```

答: It's much better to add a constraint and on swipe down change constraint value to -ve and animate it using UIViewAnimation</p>

Title: View transition on scroll view

Body:
I have set up a view containing a scrollview, I am attempting to allow the user to close the view by swiping down on the scroll view.

I have used the code below which as you can see dismisses the view controller when the scrollview y position is greater than -150.

When it reaches that point the view disappears, but ideally what I would like is for the view to continue moving downwards until it is out of view.

How would I go about this?

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.y < 0) {
        self.view.frame.origin.y = abs(scrollView.contentOffset.y) * 2
    }
    if (scrollView.contentOffset.y < -150) {
        dismiss(animated: false, completion: nil)
    }
}


问:
How to pull strings out of JSON object
Here is the code

```<code>$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);
</code>```

output:

```<code>  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )
</code>```

my question how can i pull individual values and insert them into the database
 fullname, role and username

答:
By default json_decode turns a JSON object into a PHP object, so you'll need to access it like:

```<code>$data->myObject[0]->fullname;
</code>```

When storing your data in a mysql query:

```<code>$query = "INSERT INTO table SET fullname = '{$data->myObject[0]->fullname}'";
</code>```

If you prefer to use an array instead of an object, you can use:

```<code>$data = json_decode($jsonString, true); //notice the 2nd parameter
</code>```

That way you can access your variables with an array like the two other posters described.

EDIT

You don't really need to use a for loop, you would just set:

```<code>$data = json_decode($jsonString, true);
$users = $data['myObject'];
</code>```

Since you already have a perfectly valid array in $data['myObject'].

Title: How to pull strings out of JSON object

Body:
Here is the code

$jsonString = urldecode($json);
$jsonString = str_replace("\\", "", $jsonString);
$data = JSON_decode($jsonString);
mysql_select_db($database) or die('Cannot connect to database.');
print_r($data);

output:

  stdClass Object ( [myObject] => Array ( [0] => stdClass Object ( [fullname] => abc [role] => ADMIN [username] => xyz ) ) )

my question how can i pull individual values and insert them into the database
 fullname, role and username

Body:
By default json_decode turns a JSON object into a PHP object, so you'll need to access it like:

$data->myObject[0]->fullname;

When storing your data in a mysql query:

$query = "INSERT INTO table SET fullname = '{$data->myObject[0]->fullname}'";

If you prefer to use an array instead of an object, you can use:

$data = json_decode($jsonString, true); //notice the 2nd parameter

That way you can access your variables with an array like the two other posters described.

EDIT

You don't really need to use a for loop, you would just set:

$data = json_decode($jsonString, true);
$users = $data['myObject'];

Since you already have a perfectly valid array in $data['myObject'].


问:
How to use Exception Handling in Selenium Webdriver?
The Scenario is as follows:
When the code driver.get(url); runs, if the URL is not able to access (if server is not reachable) then it should throw an exception that server is not reachable and the code should stop executing the next line

driver.findElement(By.id("loginUsername")).sendKeys(username);
```

<p>The following code I'm running in eclipse as follows:</p>

<pre class="lang-java prettyprint-override"><code>import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class A {

    static Properties p= new Properties();
    String url=p.getProperty("url");
    private static Logger Log = Logger.getLogger(A.class.getName());

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, InterruptedException {
        WebDriver driver = new FirefoxDriver();
        A a = new A();

        Actions actions = new Actions(driver);
        DOMConfigurator.configure("src/log4j.xml");
        String url = a.readXML("logindetails","url");
        String username = a.readXML("logindetails","username");
        String password = a.readXML("logindetails","password");

        //use username for webdriver specific actions
        Log.info("Sign in to the OneReports website");
        driver.manage().window().maximize();
        driver.get(url);// In this line after opens the browser it gets the URL from my **D://NewFile.xml* file and try to open in the browser. If the Server is not reachable then it should stop here. else it takes the username and password from the same file then it will open the page in browser.
        Thread.sleep(5000);
        Log.info("Enter Username");
        driver.findElement(By.id("loginUsername")).sendKeys(username);
        Log.info("Enter Password");
        driver.findElement(By.id("loginPassword")).sendKeys(password);
        //submit
        Log.info("Submitting login details");
        waitforElement(driver,120 , "//*[@id='submit']");
        driver.findElement(By.id("submit")).submit();
        Thread.sleep(5000);

    }

    private static void waitforElement(WebDriver driver, int i, String string) {
        // TODO Auto-generated method stub

    }

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{
        String ele = null;
        File fXmlFile = new File("D://NewFile.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName(searchelement);
        Node nNode = nList.item(0);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            ele=eElement.getElementsByTagName(tag).item(0).getTextContent();
        }
        return ele;
    }

}
</code>```

I tried this try block method as well. But it's not catching the exception just moving to the

driver.findElement(By.id("loginUsername")).sendKeys(username);

Error in code

line and I'm getting error as follows in the console:Unable to locate
  element: {"method":"id","selector":"loginUsername"} Command duration
  or timeout: 262 milliseconds

try
    {
        driver.get(url);
    }
    catch(Exception e)
    {
        Reporter.log("network server is slow..check internet connection");
        Log.info("Unable to open the website");
        throw new Error("network server is slow..check internet connection");
    }
```

答:
Try this one:

```<code>try {
    driver.get(url);
} catch (Exception e) {
    logger.log(Level.SEVERE, "Exception Occured:", e);
}
</code>```

Body:
The Scenario is as follows:
When the code driver.get(url); runs, if the URL is not able to access (if server is not reachable) then it should throw an exception that server is not reachable and the code should stop executing the next line

driver.findElement(By.id("loginUsername")).sendKeys(username);

The following code I'm running in eclipse as follows:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class A {

    static Properties p= new Properties();
    String url=p.getProperty("url");
    private static Logger Log = Logger.getLogger(A.class.getName());

    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, InterruptedException {
        WebDriver driver = new FirefoxDriver();
        A a = new A();

        Actions actions = new Actions(driver);
        DOMConfigurator.configure("src/log4j.xml");
        String url = a.readXML("logindetails","url");
        String username = a.readXML("logindetails","username");
        String password = a.readXML("logindetails","password");

        //use username for webdriver specific actions
        Log.info("Sign in to the OneReports website");
        driver.manage().window().maximize();
        driver.get(url);// In this line after opens the browser it gets the URL from my **D://NewFile.xml* file and try to open in the browser. If the Server is not reachable then it should stop here. else it takes the username and password from the same file then it will open the page in browser.
        Thread.sleep(5000);
        Log.info("Enter Username");
        driver.findElement(By.id("loginUsername")).sendKeys(username);
        Log.info("Enter Password");
        driver.findElement(By.id("loginPassword")).sendKeys(password);
        //submit
        Log.info("Submitting login details");
        waitforElement(driver,120 , "//*[@id='submit']");
        driver.findElement(By.id("submit")).submit();
        Thread.sleep(5000);

    }

    private static void waitforElement(WebDriver driver, int i, String string) {
        // TODO Auto-generated method stub

    }

    public String readXML(String searchelement,String tag) throws SAXException, IOException, ParserConfigurationException{
        String ele = null;
        File fXmlFile = new File("D://NewFile.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName(searchelement);
        Node nNode = nList.item(0);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) nNode;
            ele=eElement.getElementsByTagName(tag).item(0).getTextContent();
        }
        return ele;
    }

}

I tried this try block method as well. But it's not catching the exception just moving to the

driver.findElement(By.id("loginUsername")).sendKeys(username);

Error in code

line and I'm getting error as follows in the console:Unable to locate
  element: {"method":"id","selector":"loginUsername"} Command duration
  or timeout: 262 milliseconds

try
    {
        driver.get(url);
    }
    catch(Exception e)
    {
        Reporter.log("network server is slow..check internet connection");
        Log.info("Unable to open the website");
        throw new Error("network server is slow..check internet connection");
    }

Body:
Try this one:

try {
    driver.get(url);
} catch (Exception e) {
    logger.log(Level.SEVERE, "Exception Occured:", e);
}


问:
How to convert this apache rewrite rule to nginx
I've been struggling to convert my past apache rewrite rule to nginx (also not sure if I'm placing it in the right place so would appreciate if you can tell me where to place it).

Basically this was apache rewrite rule on my .htaccess file on Wordpress:

```<code><IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^/?hosts/(.*)$ /user/$1 [R,L]
</IfModule>
</code>```

As you can see, I'm using this rule in order redirect from example.com/hosts/username to example.com/user/username

I've used this converting tool https://labs.gidix.de/nginx/ and it outputs this conversion: rewrite ^/?hosts/(.*)$ /user/$1 last; - however I tried placing this in Ajenti's(control panel) advanced custom configuration but it's not working.

答:
You probably need to make this an external redirect so that WordPress will take notice. The cleanest solution would be to place it into a location of its own:

```<code>location ^~ /hosts/ {
    rewrite ^/hosts(.*)$ /user$1 permanent;
}
</code>```

See this document for more.

Body:
I've been struggling to convert my past apache rewrite rule to nginx (also not sure if I'm placing it in the right place so would appreciate if you can tell me where to place it).

Basically this was apache rewrite rule on my .htaccess file on Wordpress:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^/?hosts/(.*)$ /user/$1 [R,L]
</IfModule>

As you can see, I'm using this rule in order redirect from example.com/hosts/username to example.com/user/username

I've used this converting tool https://labs.gidix.de/nginx/ and it outputs this conversion: rewrite ^/?hosts/(.*)$ /user/$1 last; - however I tried placing this in Ajenti's(control panel) advanced custom configuration but it's not working.

Body:
You probably need to make this an external redirect so that WordPress will take notice. The cleanest solution would be to place it into a location of its own:

location ^~ /hosts/ {
    rewrite ^/hosts(.*)$ /user$1 permanent;
}

See this document for more.


问:
PHP Mail adding BCC
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

```<code>$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
</code>```

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons

答: You need to concatenate the header strings. Replace 'header =' by 'header .=' in your code</p>

Title: PHP Mail adding BCC

Body:
I have a form that populates a PHP mail to be sent to our clients, I want to BCC most of the clients due to privacy. I have the following code

$to = "******@e-track.co.za"; //To recipients
$email_from = '*****@etrackbureau.co.za';//<== update the email address
$email_subject = "New Overdue Loaded";
$email_body = "A new High Risk Client has been loaded by $name $company.\n".
    "\n Client Name: $driver_name $driver_surname\n
    \n Client ID or Passport Number: $driver_id\n
    \n Nationality: $driver_nationality\n
    \n Reason for Loading Client: $type\n
    \n Notes: $notes\n
    ".
$headers = "From: $email_from \r\n";
$headers = "Bcc: ******@e-track.co.za;*****@e-track.co.za;******@e-track.co.za\r\n";
//$headers = "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);

I have added the BCC as a $headers but once I add this it doesn't send mails at all when I remove it I get the mail to the $to recipient.

I have tried spacing between the BCC mails as well. I have replaced the mail names with **** for spamming reasons


答: That tutorial is about encoding the output in the eclipse console, you are using GUIs from java swing, on the other hand, what you are doing is not enough, the gui label is printing EXACTLY the value that the string literal is holding... you need to set the encoding utf-8 to files too:

Title: Why are chinese characters still not showing in eclipse?

Body:
Even after using the guide from here to set the UTF-8 encoding, I went on and restarted eclipse but the text are still showing as weird characters like in my screenshot below.

Please advise what else can I do.


问:
Obtain ALL children of a given node in TreeMap
I am using java 8. I found out there is an object TreeMap pre-implimented in java.
I am wondering how I can obtain children nodes of a certain node.

I have written the following recursive code, but it does not work.

```<code>static TreeMap<String,SimpleNode> tree = new TreeMap<String,SimpleNode>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    Stack nodesToDelete = new Stack();
    nodesToDelete.add(parentNode.getId());
    SimpleNode children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

        findChildrenToDelete(children.get(i));

     return  nodesToDelete;
}
</code>```

I mean the method should provide a stack of children nodes

I saw the methods of the class and i didn't find a straight forward solution.

答:
The reason why it does not work is because you don't do anything with the result of the recursive call. You have to append these children to the result.

```<code>static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    Stack nodesToDelete = new Stack();
    nodesToDelete.add(parentNode.getId());
    ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

    for(int i=0;i<children.size();i++){
        // add recursive children to the result
        <b>nodesToDelete.addAll(</b>findChildrenToDelete(children.get(i))<b>)</b>;
    }
    return nodesToDelete;
}</code>```

Alternatively you can pass a reference to the collection you are building and add to the collection during the recursion:

```<code>static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    <b>return findChildrenToDelete(parentNode,new Stack());</b>
}
public Stack findChildrenToDelete(SimpleNode parentNode<b>, Stack nodesToDelete</b>){
    nodesToDelete.add(parentNode.getId());
    ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

    for(int i=0;i<children.size();i++){
        // pass a reference to the collection recursively
        findChildrenToDelete(children.get(i)<b>,nodesToDelete</b>);
    }
    return nodesToDelete;
}</code>```

Body:
I am using java 8. I found out there is an object TreeMap pre-implimented in java.
I am wondering how I can obtain children nodes of a certain node.

I have written the following recursive code, but it does not work.

static TreeMap<String,SimpleNode> tree = new TreeMap<String,SimpleNode>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    Stack nodesToDelete = new Stack();
    nodesToDelete.add(parentNode.getId());
    SimpleNode children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

        findChildrenToDelete(children.get(i));

     return  nodesToDelete;
}

I mean the method should provide a stack of children nodes

I saw the methods of the class and i didn't find a straight forward solution.

Body:
The reason why it does not work is because you don't do anything with the result of the recursive call. You have to append these children to the result.

static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    Stack nodesToDelete = new Stack();
    nodesToDelete.add(parentNode.getId());
    ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

    for(int i=0;i<children.size();i++){
        // add recursive children to the result
        nodesToDelete.addAll(findChildrenToDelete(children.get(i)));
    }
    return nodesToDelete;
}

Alternatively you can pass a reference to the collection you are building and add to the collection during the recursion:

static TreeMap<String,ArrayList<SimpleNode>> tree = new TreeMap<String,ArrayList<SimpleNode>>();

public Stack findChildrenToDelete(SimpleNode parentNode){
    return findChildrenToDelete(parentNode,new Stack());
}
public Stack findChildrenToDelete(SimpleNode parentNode, Stack nodesToDelete){
    nodesToDelete.add(parentNode.getId());
    ArrayList<SimpleNode> children=tree.get(keyMaker(parentNode.getId(), parentNode.getType()));

    for(int i=0;i<children.size();i++){
        // pass a reference to the collection recursively
        findChildrenToDelete(children.get(i),nodesToDelete);
    }
    return nodesToDelete;
}


问:
GoogleSignInAccount getIdToken() is null
Hey I am using the Firebase auth and enabled the Google login feature.
The Google log in is working well and I get all informations. But when I want to save the user in the Firebase user-list the getIdToken() is null:

```<code>private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

    //here the acct.getIdToken() is null

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    firebaseAuth.signInWithCredential(credential)
      .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
              if (!task.isSuccessful()) {
                  Toast.makeText(SignIn.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
              }

              // [START_EXCLUDE]
              progressDialog.hide();
              // [END_EXCLUDE]
          }
      });

}
</code>```

答:
You need to override onActivityResult method in your activity. Add this code:

```<code>if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        }
    }
</code>```

And this how your handleSignInResult method should look like:

```<code>private void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount googleSignInAccount = result.getSignInAccount();
        if (googleSignInAccount != null) {
            String userId = googleSignInAccount.getId();
        }
        updateUI(true);
    } else {
        updateUI(false);
    }
}
</code>```

You need also to enable in your Firebase account, in Authentication -> SIGN-IN METHOD -> the provider. You need to enable the one your are using, Email/Password, Google and so on.

You need also to put compile 'com.google.firebase:firebase-auth:10.2.0' in your build.gradle file.

In your AndroidManifest, you have to set this 2 permissions: <uses-permission android:name="android.permission.INTERNET"/>' and '<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

You need also to set your SHA1. Here you can take a look at how can be done. In the end, don't forget to put your google-services.json again in the right location.

And this how firebaseAuthWithGoogle method should look like:

```<code>private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    System.out.println("firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    auth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("signInWithCredential:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("signInWithCredential" + task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
</code>```

And very important, dont't forget to add this code in onStart method:

```<code>@Override
public void onStart() {
    super.onStart();

    OptionalPendingResult<GoogleSignInResult> optionalPendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
    if (optionalPendingResult.isDone()) {
        GoogleSignInResult googleSignInResult = optionalPendingResult.get();
        handleSignInResult(googleSignInResult);
    } else {
        optionalPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
                handleSignInResult(googleSignInResult);
            }
        });
    }
    auth.addAuthStateListener(authListener);
}
</code>```

Hope it helps!

Body:
Hey I am using the Firebase auth and enabled the Google login feature.
The Google log in is working well and I get all informations. But when I want to save the user in the Firebase user-list the getIdToken() is null:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

    //here the acct.getIdToken() is null

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    firebaseAuth.signInWithCredential(credential)
      .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
              if (!task.isSuccessful()) {
                  Toast.makeText(SignIn.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
              }

              // [START_EXCLUDE]
              progressDialog.hide();
              // [END_EXCLUDE]
          }
      });

}

Body:
You need to override onActivityResult method in your activity. Add this code:

if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);
        }
    }

And this how your handleSignInResult method should look like:

private void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount googleSignInAccount = result.getSignInAccount();
        if (googleSignInAccount != null) {
            String userId = googleSignInAccount.getId();
        }
        updateUI(true);
    } else {
        updateUI(false);
    }
}

You need also to enable in your Firebase account, in Authentication -> SIGN-IN METHOD -> the provider. You need to enable the one your are using, Email/Password, Google and so on.

You need also to put compile 'com.google.firebase:firebase-auth:10.2.0' in your build.gradle file.

In your AndroidManifest, you have to set this 2 permissions: <uses-permission android:name="android.permission.INTERNET"/>' and '<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

You need also to set your SHA1. Here you can take a look at how can be done. In the end, don't forget to put your google-services.json again in the right location.

And this how firebaseAuthWithGoogle method should look like:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    System.out.println("firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    auth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    System.out.println("signInWithCredential:onComplete:" + task.isSuccessful());

                    if (!task.isSuccessful()) {
                        System.out.println("signInWithCredential" + task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

And very important, dont't forget to add this code in onStart method:

@Override
public void onStart() {
    super.onStart();

    OptionalPendingResult<GoogleSignInResult> optionalPendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
    if (optionalPendingResult.isDone()) {
        GoogleSignInResult googleSignInResult = optionalPendingResult.get();
        handleSignInResult(googleSignInResult);
    } else {
        optionalPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
            @Override
            public void onResult(@NonNull GoogleSignInResult googleSignInResult) {
                handleSignInResult(googleSignInResult);
            }
        });
    }
    auth.addAuthStateListener(authListener);
}

Hope it helps!


问:
Syntax error when trying to redirect the output of my python script
'Trying to redirect the output of my python script:

```<code>print('Hi')
python /path/to/script/script.py > /path/to/output/myfile.txt
</code>```

However I am being told that '/' before path/to/output/myfile.txt is a syntax error

(I'm doing coursework and I need to export all my print statements into a .txt file)

(also some of my print statements are in For loops)

答:
Python file is not bash interpreter, so you have to type you wnat to use output file as stdout in bash/cmd.

EDIT: As you are using windows, type this in your cmd.exe (Start -> Run -> cmd.exe)

python /path/to/script/script.py > /path/to/output/myfile.txt

Body:
'Trying to redirect the output of my python script:

print('Hi')
python /path/to/script/script.py > /path/to/output/myfile.txt

However I am being told that '/' before path/to/output/myfile.txt is a syntax error

(I'm doing coursework and I need to export all my print statements into a .txt file)

(also some of my print statements are in For loops)