问:
how to filter an object and get the desired output in javascript array?
I have an array of object like this,

```<code>[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]
</code>```

Desired output = ["A", "B", "D"];

答:
You could always create a proxy to handle the cases when you need the properties with some sort of priority. Though for this case I would not recommend it. This answer is simply an example.

// get handler arguments (t,p) is t for target (the arr) and p for property is the property
// of array we are trying to get. this could be 0 as an index or a function name
const arr =[{a: "A"},{a: "B"}, {a: "C", b: "D"} ];
const arrP = new Proxy(arr,{ // add get proxy name to return map of names
        get : (t, p)=> p==="names" ? t.map(o => o.b ? o.b : o.a ): t[p]
    }
);
console.log(arrP.names);

    ```
</div>
</div>
</p>

<p>Or you can use  <code>Proxy.revocable</code>    </p>

```const arrPr = Proxy.revocable(arr,{
    get : (t, p)=> p==="names" ? t.map(o => o.b ? o.b : o.a ): t[p]
});
console.log(arrPr.proxy.names);
arrPr.revoke();  // can use anymore will throw if you try.
```

Body:
I have an array of object like this,

[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]

Desired output = ["A", "B", "D"];

Body:
You could always create a proxy to handle the cases when you need the properties with some sort of priority. Though for this case I would not recommend it. This answer is simply an example.

// get handler arguments (t,p) is t for target (the arr) and p for property is the property
// of array we are trying to get. this could be 0 as an index or a function name
const arr =[{a: "A"},{a: "B"}, {a: "C", b: "D"} ];
const arrP = new Proxy(arr,{ // add get proxy name to return map of names
        get : (t, p)=> p==="names" ? t.map(o => o.b ? o.b : o.a ): t[p]
    }
);
console.log(arrP.names);

Or you can use  Proxy.revocable

const arrPr = Proxy.revocable(arr,{
    get : (t, p)=> p==="names" ? t.map(o => o.b ? o.b : o.a ): t[p]
});
console.log(arrPr.proxy.names);
arrPr.revoke();  // can use anymore will throw if you try.


来源: stackexchange

问:
Request.Cookies["cookieName"] is null in web service method
This is how I'am saving cookie in my code which is a web service method. I tried to change the cookie expire time but still it is not working for me. Is there any issue with Context.Response to write cookie or Context.Request to read it??

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}
</code>```

for retrieving this cookie on next page

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}
</code>```

but my object getCookie is always null

答:
I got this by storing cookies as

```<code>HttpContext.Current.Response.Cookies.Add(formCookie);
</code>```

And reading this as

```<code>var getCookie=HttpContext.Current.Request.Cookies["UserData"];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is how I'am saving cookie in my code which is a web service method. I tried to change the cookie expire time but still it is not working for me. Is there any issue with Context.Response to write cookie or Context.Request to read it??

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}

for retrieving this cookie on next page

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}

but my object getCookie is always null

Body:
I got this by storing cookies as

HttpContext.Current.Response.Cookies.Add(formCookie);

And reading this as

var getCookie=HttpContext.Current.Request.Cookies["UserData"];


问:
Can you create a language specific extension command?
When developing VSCode extensions, is it possible to create an extension command that is only available for certain languages?

In your package.json manifest, you can activate your extension per language:

"activationEvents": [
    "onLanguage:html"
]
```

<p>However, a command is still there in the command palette for all extensions. It just won't work until the extension has been activated.</p>

<p>I can't figure out how to make a command, only appear for specific languages... You can define a command like this:</p>

<pre class="lang-json prettyprint-override"><code>"contributes": {
    "commands": [{
        "command": "extension.sayHello",
        "title": "Hello World"
    }]
}
</code>```

But this command is available for all languages in the command palette. The specific command I want to create really only makes sense, in my example, for the HTML language. The command specifically queries an API somewhere and then inserts some HTML into the current file. So obviously it wouldn't make sense to use this command for other languages like python or ruby etc.

Is it possible to do this?

答:
Support for this was added in VSCode 1.10: https://code.visualstudio.com/updates/v1_10#_context-specific-visibility-of-command-palette-menu-items

In your package.json:

"commands": [{
    "command": "extension.sayHello",
    "title": "Hello World"
}],
"menus": {
    "commandPalette": [{
        "command": "extension.sayHello",
        "when": "editorLangId == html"
    }]
}
```

ContentLicense: CC BY-SA 4.0

Body:
When developing VSCode extensions, is it possible to create an extension command that is only available for certain languages?

In your package.json manifest, you can activate your extension per language:

"activationEvents": [
    "onLanguage:html"
]

However, a command is still there in the command palette for all extensions. It just won't work until the extension has been activated.

I can't figure out how to make a command, only appear for specific languages... You can define a command like this:

"contributes": {
    "commands": [{
        "command": "extension.sayHello",
        "title": "Hello World"
    }]
}

But this command is available for all languages in the command palette. The specific command I want to create really only makes sense, in my example, for the HTML language. The command specifically queries an API somewhere and then inserts some HTML into the current file. So obviously it wouldn't make sense to use this command for other languages like python or ruby etc.

Is it possible to do this?


问:
ImportError:'save_weights' requires h5py
When I save weights during training my CNN model using keras, it says ImportError:'save_weights' requires h5py, but I have already installed h5py.

I would greatly appreciate if someone could explain how to fix this issue.

答:
Have you tried directly installing h5py? http://docs.h5py.org/en/latest/build.html

Try running:

pip install h5py
or
sudo apt-get install libhdf5


问:
tensorflow: what's wrong with my .tfrecords file?
Today I make a .tfrecords file with my images. The width of the image is 2048 and the height is 1536. All the images are almost 5.1GB, but when I use it to make .tfrecords, it;s almost 137 GB! More importantlt, when I use it to train, I get an error like CUDA_ERROR_OUT_OF_MEMORY.
Here is the error:

```<code>Total memory: 10.91GiB
Free memory: 10.45GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:01:00.0)
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 61835259904 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 61835259904
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
.........
</code>```

I use the smallest batch_size, but it's still wrong. Does anyone know why? Is there something wrong with my tfrecords file?
The code that I make tfrecords with is here:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import tensorflow as tf
import numpy as np
import cv2
import os
import os.path
from PIL import Image
train_file = 'train.txt'
name = 'trainxx'
output_directory = './tfrecords'
resize_height = 1536
resize_width = 2048
def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def load_file(examples_list_file):
    lines = np.genfromtxt(examples_list_file, delimiter=" ", dtype=[('col1', 'S120'), ('col2', 'i8')])
    examples = []
    labels = []
    for example, label in lines:
        examples.append(example)
        labels.append(label)
    return np.asarray(examples), np.asarray(labels), len(lines)
def extract_image(filename, resize_height, resize_width):
    image = cv2.imread(filename)
    image = cv2.resize(image, (resize_height, resize_width))
    b, g, r = cv2.split(image)
    rgb_image = cv2.merge([r, g, b])
    return rgb_image
def transform2tfrecord(train_file, name, output_directory, resize_height, resize_width):
    if not os.path.exists(output_directory) or os.path.isfile(output_directory):
        os.makedirs(output_directory)
    _examples, _labels, examples_num = load_file(train_file)
    filename = output_directory + "/" + name + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(filename)
    for i, [example, label] in enumerate(zip(_examples, _labels)):
        print('No.%d' % (i))
        image = extract_image(example, resize_height, resize_width)
        print('shape: %d, %d, %d, label: %d' % (image.shape[0], image.shape[1], image.shape[2], label))
        image_raw = image.tostring()
        example = tf.train.Example(features=tf.train.Features(feature={
            'image_raw': _bytes_feature(image_raw),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'depth': _int64_feature(image.shape[2]),
            'label': _int64_feature(label)
        }))
        writer.write(example.SerializeToString())
    writer.close()
def disp_tfrecords(tfrecord_list_file):
    filename_queue = tf.train.string_input_producer([tfrecord_list_file])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'height': tf.FixedLenFeature([], tf.int64),
            'width': tf.FixedLenFeature([], tf.int64),
            'depth': tf.FixedLenFeature([], tf.int64),
            'label': tf.FixedLenFeature([], tf.int64)
        }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    # print(repr(image))
    height = features['height']
    width = features['width']
    depth = features['depth']
    label = tf.cast(features['label'], tf.int32)
    init_op = tf.initialize_all_variables()
    resultImg = []
    resultLabel = []
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(21):
            image_eval = image.eval()
            resultLabel.append(label.eval())
            image_eval_reshape = image_eval.reshape([height.eval(), width.eval(), depth.eval()])
            resultImg.append(image_eval_reshape)
            pilimg = Image.fromarray(np.asarray(image_eval_reshape))
            pilimg.show()
        coord.request_stop()
        coord.join(threads)
        sess.close()
    return resultImg, resultLabel
def read_tfrecord(filename_queuetemp):
    filename_queue = tf.train.string_input_producer([filename_queuetemp])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'width': tf.FixedLenFeature([], tf.int64),
            'depth': tf.FixedLenFeature([], tf.int64),
            'label': tf.FixedLenFeature([], tf.int64)
        }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    # image
    tf.reshape(image, [256, 256, 3])
    # normalize
    image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
    # label
    label = tf.cast(features['label'], tf.int32)
    return image, label
def test():
    transform2tfrecord(train_file, name, output_directory, resize_height, resize_width)
    img, label = disp_tfrecords(output_directory + '/' + name + '.tfrecords')
    img, label = read_tfrecord(output_directory + '/' + name + '.tfrecords') 数
    print label
if __name__ == '__main__':
    test()
```

答:
Why has your dataset grown in size

I didn't go through all your code, but I think I found the reason for the explosion in size of your dataset.

Your conversion process looks like this:

Get the filenames list

Open the image file and reorder the channels

Process the image file (rescaling)

Write out the data bytes as a string in the .tfrecord file <-- the problematic point

Image files are normally compressed. Either lossy or lossless, they are stored in a space-efficient way. You're throwing that efficiency away when you decode the image and save the raw bytes as (uncompressed) text.

Why is your code eating up your host RAM

Note: I don't know how your input pipeline is set up so I'm making some assumptions here, but I believe I'm getting them right.

The problem here is that, thanks to your decoded image in the tfrecord file, every example you have is rather big in size. When you set up an input pipeline, data is read and queued so that further stages of the pipeline can process it. My idea is that your examples queue gets so big that goes out of memory, because of the size of each single example.

What a typical .tfrecord conversion pipeline looks like

There is a simple change you need to make to fix your problem: storing the raw data of the compressed file in your .tfrecord and then decode directly in Tensorflow.
The process should look as follows:

Get the filenames list

Open the binary file and read out its content as a byte string:

```<code>with(my_image_filename, 'rb') as fp:
    raw_image = fp.read()
</code>```

Write the raw_image byte string to the .tfrecord file

In your Tensorflow input pipeline, you'll read the 'raw_image' byte string tensor and feed it to tf.image.decode_image() or one of its more specific variants.

This way, you won't store anywhere the decoded image until you actually need it, so your queues will stay a reasonable size and your tfrecord file too.

Other notes on your setup

You're mixing OpenCV and Tensorflow, but this is not necessary. Tensorflow has all you need to convert your dataset to .tfrecord files first and decoded images afterwards and it's IMO much simpler to just stick to Tensorflow's API.
Here's the guide on how to set the conversion and the input pipeline, which shows the "typical .tfrecord conversion pipeline" I described above, plus a few more tricks if you have other needs (like reading the filenames from the .csv file).

Body:
Today I make a .tfrecords file with my images. The width of the image is 2048 and the height is 1536. All the images are almost 5.1GB, but when I use it to make .tfrecords, it;s almost 137 GB! More importantlt, when I use it to train, I get an error like CUDA_ERROR_OUT_OF_MEMORY.
Here is the error:

Total memory: 10.91GiB
Free memory: 10.45GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:01:00.0)
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 61835259904 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 61835259904
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
E tensorflow/stream_executor/cuda/cuda_driver.cc:1034] failed to alloc 68705845248 bytes on host: CUDA_ERROR_OUT_OF_MEMORY
W ./tensorflow/core/common_runtime/gpu/pool_allocator.h:195] could not allocate pinned host memory of size: 68705845248
.........

I use the smallest batch_size, but it's still wrong. Does anyone know why? Is there something wrong with my tfrecords file?
The code that I make tfrecords with is here:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import tensorflow as tf
import numpy as np
import cv2
import os
import os.path
from PIL import Image
train_file = 'train.txt'
name = 'trainxx'
output_directory = './tfrecords'
resize_height = 1536
resize_width = 2048
def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def load_file(examples_list_file):
    lines = np.genfromtxt(examples_list_file, delimiter=" ", dtype=[('col1', 'S120'), ('col2', 'i8')])
    examples = []
    labels = []
    for example, label in lines:
        examples.append(example)
        labels.append(label)
    return np.asarray(examples), np.asarray(labels), len(lines)
def extract_image(filename, resize_height, resize_width):
    image = cv2.imread(filename)
    image = cv2.resize(image, (resize_height, resize_width))
    b, g, r = cv2.split(image)
    rgb_image = cv2.merge([r, g, b])
    return rgb_image
def transform2tfrecord(train_file, name, output_directory, resize_height, resize_width):
    if not os.path.exists(output_directory) or os.path.isfile(output_directory):
        os.makedirs(output_directory)
    _examples, _labels, examples_num = load_file(train_file)
    filename = output_directory + "/" + name + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(filename)
    for i, [example, label] in enumerate(zip(_examples, _labels)):
        print('No.%d' % (i))
        image = extract_image(example, resize_height, resize_width)
        print('shape: %d, %d, %d, label: %d' % (image.shape[0], image.shape[1], image.shape[2], label))
        image_raw = image.tostring()
        example = tf.train.Example(features=tf.train.Features(feature={
            'image_raw': _bytes_feature(image_raw),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'depth': _int64_feature(image.shape[2]),
            'label': _int64_feature(label)
        }))
        writer.write(example.SerializeToString())
    writer.close()
def disp_tfrecords(tfrecord_list_file):
    filename_queue = tf.train.string_input_producer([tfrecord_list_file])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'height': tf.FixedLenFeature([], tf.int64),
            'width': tf.FixedLenFeature([], tf.int64),
            'depth': tf.FixedLenFeature([], tf.int64),
            'label': tf.FixedLenFeature([], tf.int64)
        }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    # print(repr(image))
    height = features['height']
    width = features['width']
    depth = features['depth']
    label = tf.cast(features['label'], tf.int32)
    init_op = tf.initialize_all_variables()
    resultImg = []
    resultLabel = []
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(21):
            image_eval = image.eval()
            resultLabel.append(label.eval())
            image_eval_reshape = image_eval.reshape([height.eval(), width.eval(), depth.eval()])
            resultImg.append(image_eval_reshape)
            pilimg = Image.fromarray(np.asarray(image_eval_reshape))
            pilimg.show()
        coord.request_stop()
        coord.join(threads)
        sess.close()
    return resultImg, resultLabel
def read_tfrecord(filename_queuetemp):
    filename_queue = tf.train.string_input_producer([filename_queuetemp])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'image_raw': tf.FixedLenFeature([], tf.string),
            'width': tf.FixedLenFeature([], tf.int64),
            'depth': tf.FixedLenFeature([], tf.int64),
            'label': tf.FixedLenFeature([], tf.int64)
        }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    # image
    tf.reshape(image, [256, 256, 3])
    # normalize
    image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
    # label
    label = tf.cast(features['label'], tf.int32)
    return image, label
def test():
    transform2tfrecord(train_file, name, output_directory, resize_height, resize_width)
    img, label = disp_tfrecords(output_directory + '/' + name + '.tfrecords')
    img, label = read_tfrecord(output_directory + '/' + name + '.tfrecords') 数
    print label
if __name__ == '__main__':
    test()

Body:
Why has your dataset grown in size

I didn't go through all your code, but I think I found the reason for the explosion in size of your dataset.

Your conversion process looks like this:

Get the filenames list

Open the image file and reorder the channels

Process the image file (rescaling)

Write out the data bytes as a string in the .tfrecord file <-- the problematic point

Image files are normally compressed. Either lossy or lossless, they are stored in a space-efficient way. You're throwing that efficiency away when you decode the image and save the raw bytes as (uncompressed) text.

Why is your code eating up your host RAM

Note: I don't know how your input pipeline is set up so I'm making some assumptions here, but I believe I'm getting them right.

The problem here is that, thanks to your decoded image in the tfrecord file, every example you have is rather big in size. When you set up an input pipeline, data is read and queued so that further stages of the pipeline can process it. My idea is that your examples queue gets so big that goes out of memory, because of the size of each single example.

What a typical .tfrecord conversion pipeline looks like

There is a simple change you need to make to fix your problem: storing the raw data of the compressed file in your .tfrecord and then decode directly in Tensorflow.
The process should look as follows:

Get the filenames list

Open the binary file and read out its content as a byte string:

with(my_image_filename, 'rb') as fp:
    raw_image = fp.read()

Write the raw_image byte string to the .tfrecord file

In your Tensorflow input pipeline, you'll read the 'raw_image' byte string tensor and feed it to tf.image.decode_image() or one of its more specific variants.

This way, you won't store anywhere the decoded image until you actually need it, so your queues will stay a reasonable size and your tfrecord file too.

Other notes on your setup

You're mixing OpenCV and Tensorflow, but this is not necessary. Tensorflow has all you need to convert your dataset to .tfrecord files first and decoded images afterwards and it's IMO much simpler to just stick to Tensorflow's API.
Here's the guide on how to set the conversion and the input pipeline, which shows the "typical .tfrecord conversion pipeline" I described above, plus a few more tricks if you have other needs (like reading the filenames from the .csv file).


问:
How can I use .htaccess rewrite to redirect root URL to subdirectory?
Trying to get

```<code>www.example.com
</code>```

to go directly to

```<code>www.example.com/store
</code>```

I have tried multiple bits of code and none work.

What I've tried:

```<code>Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(.+)\www.example\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]
</code>```

What am I doing wrong?

答:
Two ways out of possible solutions to achieve this are:
1. Create a .htaccess file in root folder as under (just replace example.com and my_dir with your corresponding values):

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L]
</IfModule>
</code>```

Use RedirectMatch to only redirect the root URL “/” to another folder or URL,

RedirectMatch ^/$ http://www.example.com/my_dir

OwnerDisplayName: AlphaSmith

Body:
Trying to get

www.example.com

to go directly to

www.example.com/store

I have tried multiple bits of code and none work.

What I've tried:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(.+)\www.example\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]

What am I doing wrong?

Body:
Two ways out of possible solutions to achieve this are:
1. Create a .htaccess file in root folder as under (just replace example.com and my_dir with your corresponding values):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_dir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_dir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_dir/index.php [L]
</IfModule>

Use RedirectMatch to only redirect the root URL “/” to another folder or URL,

RedirectMatch ^/$ http://www.example.com/my_dir


问:
Need to duplicate the same element in the DOM 4 times using Jquery
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

```<code>function Pin(caixaPin){
 var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('<div></div>');
</code>```

Thanks !!

答:
Here you go with jsfiddle https://jsfiddle.net/eL3usbxb/

```<code>function Pin(caixaPin){
    for(var i=0; i<4; i++){
        var $temp;
        $temp = $("<div></div>");
        $temp.addClass("caixaPin");
        $temp.html(caixaPin);
        $("body").append($temp);
    }
}

Pin('<div></div>');
</code>```

Another way
Just call Pin function inside a loop

```<code>for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}
</code>```

Body:
Im using jquery to insert html in the dom. Everything is working fine, now i need to duplicate an element 4 times, and i don't know how.

this is how i use Jquery to insert the element into the DOM.

function Pin(caixaPin){
 var $temp;
  $temp = $("

");
  $temp.addClass("caixaPin");
  $temp.html(caixaPin);
  $("body").append($temp);
}

Pin('

');

Thanks !!

Body:
Here you go with jsfiddle https://jsfiddle.net/eL3usbxb/

function Pin(caixaPin){
    for(var i=0; i<4; i++){
        var $temp;
        $temp = $("<div></div>");
        $temp.addClass("caixaPin");
        $temp.html(caixaPin);
        $("body").append($temp);
    }
}

Pin('<div></div>');

Another way
Just call Pin function inside a loop

for (var i = 0; i < 4; i++){
    Pin('<div></div>');
}


问:
How to Change one controller value into another Control
```<code>var getAgentBalanceAmount = function (ClientId, UserId) {
    $http({
        method: 'GET',
        url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
    })
    .then(function success(response) {
        $scope.getBalAmount = response.data[0].BalanceAmount;
    }, function error(response) {
        alert('Error');
    });
};
</code>```

In this method  $scope.getBalAmount have some value and bind into index.html page.here index page act as a master page.i want to change this value on other pages(in content page.) is it possible.Thanks in advance.

答:
Set in rootscope or using session or local storage methods.  :

```<code>var getAgentBalanceAmount = function (ClientId, UserId) {
        $http({
            method: 'GET',
            url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
        })
        .then(function success(response) {
            $rootscope.getBalAmount = response.data[0].BalanceAmount;
        }, function error(response) {
            alert('Error');
        });
    };

var getAgentBalanceAmount = function (ClientId, UserId) {
        $http({
            method: 'GET',
            url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
        })
        .then(function success(response) {
           $window.sessionStorage.token=response.data[0].BalanceAmount;
        }, function error(response) {
            alert('Error');
        });
    };
</code>```

Get another page using directly in-session storage with this code:
console.log($window.sessionStorage.token) access in all pages

Body:
var getAgentBalanceAmount = function (ClientId, UserId) {
    $http({
        method: 'GET',
        url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
    })
    .then(function success(response) {
        $scope.getBalAmount = response.data[0].BalanceAmount;
    }, function error(response) {
        alert('Error');
    });
};

In this method  $scope.getBalAmount have some value and bind into index.html page.here index page act as a master page.i want to change this value on other pages(in content page.) is it possible.Thanks in advance.

Body:
Set in rootscope or using session or local storage methods.  :

var getAgentBalanceAmount = function (ClientId, UserId) {
        $http({
            method: 'GET',
            url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
        })
        .then(function success(response) {
            $rootscope.getBalAmount = response.data[0].BalanceAmount;
        }, function error(response) {
            alert('Error');
        });
    };

var getAgentBalanceAmount = function (ClientId, UserId) {
        $http({
            method: 'GET',
            url: $scope.ip + '/getAgentBalanceAmount?ClientId=' + ClientId + '&AgentId=' + UserId + ''
        })
        .then(function success(response) {
           $window.sessionStorage.token=response.data[0].BalanceAmount;
        }, function error(response) {
            alert('Error');
        });
    };

Get another page using directly in-session storage with this code:
console.log($window.sessionStorage.token) access in all pages


问:
including npm module in google cloud functions
I am trying to include local npm package in a cloud function. I used the following commands:

$ npm pack
$ npm install --save tarball-output.tgz
```

<p>How do I include a packed npm package in app.js? I used: </p>

<pre class="lang-js prettyprint-override"><code>let mypackage = require('my_package');
</code>```

I getting the following error when trying to deploy:

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,
message=Function load error: Code in file app.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'my_package'
```

答:
Your package.json must point to your tarball, like this:</p>

```<code>{
  "dependencies": {
    "my_package": "file:tarball-output.tgz"
  }
}
</code>```

Body:
I am trying to include local npm package in a cloud function. I used the following commands:

$ npm pack
$ npm install --save tarball-output.tgz

How do I include a packed npm package in app.js? I used:

let mypackage = require('my_package');

I getting the following error when trying to deploy:

ERROR: (gcloud.beta.functions.deploy) OperationError: code=3,
message=Function load error: Code in file app.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'my_package'

Body:
Your package.json must point to your tarball, like this:

{
  "dependencies": {
    "my_package": "file:tarball-output.tgz"
  }
}


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
I will go through your code and suggest some refactoring.

```<code> if (a.nextInt()=='+'){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='-'){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='*'){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
}
</code>```

You read operation each time if it is not equal to what you coded. So if user wants to enter opearation -, they have to enter first time operation different from +, and then -.

Second, it is a good practice to move hardcoded constants into private static fields (or public static if they are used in other classes).

Instead of if-else, prefer to use switch (for primitives, strings, enums) - better style and performance (JVM optimizes switch).

This is how I would code this

Taschenrechner

```<code>public class Taschenrechner {

    private static final char ADD = '+';
    private static final char SUB = '-';
    private static final char MUL = '*';
    private static final char DIV = '/';

    public static void calculate() {
        Scanner reader = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = reader.nextInt();
        int y = reader.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        final char operation = reader.next(".").charAt(0); //See explanation bellow.
        float result = calculateResult(x, y, operation);
        System.out.println("result: " + result);
        reader.close();
    }

    private static float calculateResult(float x, float y, char operation) {
        switch (operation) {
            case ADD:
                return x + y;

            case DIV:
                return x / y;

            case SUB:
                return x - y;

            case MUL:
                return x * y;

            default:
                throw new UnsupportedOperationException(operation + " is not suported."); //Terminate the program with an error. Read about exception handling to understand when it can be used.
        }
    }

    public static void main(String[] args) {
        calculate();
    }
}
</code>```

final char operation = reader.next(".").charAt(0);
I want to read only one character.
https://stackoverflow.com/a/13942707/4587961

I also renamed method calculator into calculate. I am a big fan of Clean Code practices. Methods' names are verbs, while classes names are nouns.

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
I will go through your code and suggest some refactoring.

 if (a.nextInt()=='+'){
        float result = x + y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='-'){
        float result = x - y;
        System.out.println("result: " + result);
    }
    else if (a.nextInt()=='*'){
        float result = x * y;
        System.out.println("result: " + result);
    }
    else{
        float result = x / y;
        System.out.println("result: " + result);
        }
    a.close();
}

You read operation each time if it is not equal to what you coded. So if user wants to enter opearation -, they have to enter first time operation different from +, and then -.

Second, it is a good practice to move hardcoded constants into private static fields (or public static if they are used in other classes).

Instead of if-else, prefer to use switch (for primitives, strings, enums) - better style and performance (JVM optimizes switch).

This is how I would code this

Taschenrechner

public class Taschenrechner {

    private static final char ADD = '+';
    private static final char SUB = '-';
    private static final char MUL = '*';
    private static final char DIV = '/';

    public static void calculate() {
        Scanner reader = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = reader.nextInt();
        int y = reader.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        final char operation = reader.next(".").charAt(0); //See explanation bellow.
        float result = calculateResult(x, y, operation);
        System.out.println("result: " + result);
        reader.close();
    }

    private static float calculateResult(float x, float y, char operation) {
        switch (operation) {
            case ADD:
                return x + y;

            case DIV:
                return x / y;

            case SUB:
                return x - y;

            case MUL:
                return x * y;

            default:
                throw new UnsupportedOperationException(operation + " is not suported."); //Terminate the program with an error. Read about exception handling to understand when it can be used.
        }
    }

    public static void main(String[] args) {
        calculate();
    }
}

final char operation = reader.next(".").charAt(0);
I want to read only one character.
https://stackoverflow.com/a/13942707/4587961

I also renamed method calculator into calculate. I am a big fan of Clean Code practices. Methods' names are verbs, while classes names are nouns.


问:
Accessing NeDB find() results
I'm making an app with Angular 2 and Electron and using NeDB as a data storage.

The search service is intended to handle operations with DB, for now I want it to load whole database and return it.

search.service.ts

```<code>import { Injectable } from '@angular/core';

import * as Datastore from 'nedb';
import * as path from 'path';

@Injectable()
export class SearchService {

  constructor() { }
  getData(){
    var db = new Datastore( {
      filename: path.resolve('src/assets/db.json'),
      autoload: true,
    });
    var result;
    db.find({}, function(err, docs) {
      result = docs;
     });
    console.log(result);
    return result;
  }

}
</code>```

In my component I use a method to call getData() method of service upon initialization of component with ngOnInit hook.

But when I log results I get undefined.

While tinkering with search ervice I found out that docs I have in find() method are not accessible from outside the method and it seems like result = docs does nothing. So I was thinking that I need some async magic to make this work. I wanted to do this with Observables but couldn't achieve anything, probably was doing it incorrectly.

答:
The find method is asynchronous and the callback function is not immediately executed, you can use promises like below:

```<code>getData() {
    var db = new Datastore({
        filename: path.resolve('src/assets/db.json'),
        autoload: true,
    });
    return new Promise((resolve, reject) => {
        db.find({}, function(err, docs) {
            if(err) reject(err);
            resolve(docs);
        });
    })
}

someOtherFunc() {
  this.getData()
  .then((docs) => console.log(docs)) // here you will get it
  .catch((err) => console.error(err));
}
</code>```

You can learn more about promises here

In case you want to use Observables, you can do it like this:

```<code>getData() {
    return new Rx.Observable(subscriber => {
        var db = new Datastore({
            filename: path.resolve('src/assets/db.json'),
            autoload: true,
        });
        db.find({}, function(err, docs) {
            if (err) subscriber.error(err);
            subscriber.next(docs);
        });
    })

}

someOtherFunc() {
    this.getData().subscribe(
        data => console.log("success", data),
        err => console.error("error", err)
    )
}
</code>```

Title: Accessing NeDB find() results

Body:
I'm making an app with Angular 2 and Electron and using NeDB as a data storage.

The search service is intended to handle operations with DB, for now I want it to load whole database and return it.

search.service.ts

import { Injectable } from '@angular/core';

import * as Datastore from 'nedb';
import * as path from 'path';

@Injectable()
export class SearchService {

  constructor() { }
  getData(){
    var db = new Datastore( {
      filename: path.resolve('src/assets/db.json'),
      autoload: true,
    });
    var result;
    db.find({}, function(err, docs) {
      result = docs;
     });
    console.log(result);
    return result;
  }

}

In my component I use a method to call getData() method of service upon initialization of component with ngOnInit hook.

But when I log results I get undefined.

While tinkering with search ervice I found out that docs I have in find() method are not accessible from outside the method and it seems like result = docs does nothing. So I was thinking that I need some async magic to make this work. I wanted to do this with Observables but couldn't achieve anything, probably was doing it incorrectly.

Body:
The find method is asynchronous and the callback function is not immediately executed, you can use promises like below:

getData() {
    var db = new Datastore({
        filename: path.resolve('src/assets/db.json'),
        autoload: true,
    });
    return new Promise((resolve, reject) => {
        db.find({}, function(err, docs) {
            if(err) reject(err);
            resolve(docs);
        });
    })
}

someOtherFunc() {
  this.getData()
  .then((docs) => console.log(docs)) // here you will get it
  .catch((err) => console.error(err));
}

You can learn more about promises here

In case you want to use Observables, you can do it like this:

getData() {
    return new Rx.Observable(subscriber => {
        var db = new Datastore({
            filename: path.resolve('src/assets/db.json'),
            autoload: true,
        });
        db.find({}, function(err, docs) {
            if (err) subscriber.error(err);
            subscriber.next(docs);
        });
    })

}

someOtherFunc() {
    this.getData().subscribe(
        data => console.log("success", data),
        err => console.error("error", err)
    )
}


问:
Linux socket programming in C, server socket cannot get closed
I am learning socket programming in linux and I have a problem.

I am trying to set up a really simple client-server socket connection with TCP sockets. However, I think I am unable to close the server socket because, when I restarted the server, it cannot bind to the same IP address and port number.

I also don't know how to debug issue. I have read that errno would be set when an error ocurs in man pages of bind. I don't know how to look at that errno.

Here is my all code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char* argv[]) {

    int serverSocket, clientSocket, portno;
    socklen_t clientLength;
    struct sockaddr_in serverAddress, clientAddress;
    int n;
    char buffer[256];

    if (argc < 2) {
        fprintf(stderr, "ERROR too few arguments.\n");
        exit(-1);
    }

    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0) {
        fprintf(stderr, "ERROR creating socket!\n");
        exit(1);
    }

    bzero((char*) &serverAddress, sizeof(serverAddress));
    portno = atoi(argv[1]);

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(portno);

    if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { //This bind will fail, after re-run.
        fprintf(stderr, "ERROR binding socket\n");
        exit(2);
    }

    listen(serverSocket, 5);
    clientLength = sizeof(clientAddress);

    clientSocket = accept(serverSocket, (struct sockaddr*) &clientSocket, &clientLength);
    if (clientSocket < 0) {
        fprintf(stderr, "ERROR on accept\n");
        exit(3);
    }

    bzero(buffer, 256);
    n = read(clientSocket, buffer, 256);
    char* ack = "I got your message";
    fprintf(stdout, "Here is the message %s\n", buffer);

    n = write(clientSocket, ack, strlen(ack));

    close(clientSocket);
    close(serverSocket);
    return 0;
}
</code>```

As far as I understand, the socket, which is a file descriptor, cannot get closed immediately. So when the program terminates and I run again within 30 seconds, it cannot bind to the address. But if I wait for, like, a minute, it has no problem binding to address.

What causes this issue?

答:
You can use perror() to view the readable error message, and set serverSocket reusable. The snippet is listed here:

```<code>serverAddress.sin_port = htons(portno);
int opt = 1;
setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) {
    //This bind will fail, after re-run.
    perror("bind ");
    fprintf(stderr, "ERROR binding socket\n");
    exit(2);
}
</code>```

Body:
I am learning socket programming in linux and I have a problem.

I am trying to set up a really simple client-server socket connection with TCP sockets. However, I think I am unable to close the server socket because, when I restarted the server, it cannot bind to the same IP address and port number.

I also don't know how to debug issue. I have read that errno would be set when an error ocurs in man pages of bind. I don't know how to look at that errno.

Here is my all code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char* argv[]) {

    int serverSocket, clientSocket, portno;
    socklen_t clientLength;
    struct sockaddr_in serverAddress, clientAddress;
    int n;
    char buffer[256];

    if (argc < 2) {
        fprintf(stderr, "ERROR too few arguments.\n");
        exit(-1);
    }

    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0) {
        fprintf(stderr, "ERROR creating socket!\n");
        exit(1);
    }

    bzero((char*) &serverAddress, sizeof(serverAddress));
    portno = atoi(argv[1]);

    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(portno);

    if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { //This bind will fail, after re-run.
        fprintf(stderr, "ERROR binding socket\n");
        exit(2);
    }

    listen(serverSocket, 5);
    clientLength = sizeof(clientAddress);

    clientSocket = accept(serverSocket, (struct sockaddr*) &clientSocket, &clientLength);
    if (clientSocket < 0) {
        fprintf(stderr, "ERROR on accept\n");
        exit(3);
    }

    bzero(buffer, 256);
    n = read(clientSocket, buffer, 256);
    char* ack = "I got your message";
    fprintf(stdout, "Here is the message %s\n", buffer);

    n = write(clientSocket, ack, strlen(ack));

    close(clientSocket);
    close(serverSocket);
    return 0;
}

As far as I understand, the socket, which is a file descriptor, cannot get closed immediately. So when the program terminates and I run again within 30 seconds, it cannot bind to the address. But if I wait for, like, a minute, it has no problem binding to address.

What causes this issue?

Body:
You can use perror() to view the readable error message, and set serverSocket reusable. The snippet is listed here:

serverAddress.sin_port = htons(portno);
int opt = 1;
setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if (bind(serverSocket, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) {
    //This bind will fail, after re-run.
    perror("bind ");
    fprintf(stderr, "ERROR binding socket\n");
    exit(2);
}


问:
Why undo for canvas don't work?
I have a canvas which I can use to draw on it and I add an undo button. I am saving the canvas in an array (as in the code) and I am calling it click on the undo button.
on console.log you can see that the src is changing but the canvas isn't.

What am I doing wrong?
(the second code is what I am having problem with but I added most of the code because my question always get closed for not giving enough information)

var mousePressed = false;
var lastX, lastY;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");

function InitThis() {

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush()
        }
    });

    $('#myCanvas').mouseleave(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush()
        }
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x;
    lastY = y;
}

var cPushArray = [""];
var cStep = -1;

function cPush() {
    cStep++;
    if (cStep < cPushArray.length) { cPushArray.length = cStep; }
    image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    cPushArray.push(image);
}
function cUndo() {
    if (cStep > 0) {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() { ctx.drawImage(canvasPic, 0, 0); };
        console.log(canvasPic);
    }
}
function cRedo() {
    if (cStep < cPushArray.length - 1) {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() { ctx.drawImage(canvasPic, 0, 0); }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {

    border: 2px solid black;

}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="style.css">

        <canvas id="myCanvas" width="500" height="200"></canvas>

        <button onclick="javascript:clearArea(); return false;">Clear Area</button>
        Line width : <select id="selWidth">
            <option value="1">1</option>
            <option value="3" selected="selected">3</option>
            <option value="5">5</option>
            <option value="7">7</option>
            <option value="9">9</option>
            <option value="11">11</option>
        </select>

        Color : <select id="selColor">
            <option value="black" selected="selected">black</option>
            <option value="blue">blue</option>
            <option value="red">red</option>
            <option value="green">green</option>
            <option value="yellow">yellow</option>
            <option value="gray">gray</option>
        </select>

        <button onclick="javascript:cUndo();return false;">Undo</button>
        <button onclick="javascript:cRedo();return false;">Redo</button>

```

答:
You need to clear the canvas before drawing the saved image, when undoing ...

```<code>function cUndo() {
   if (cStep > 0) {
      cStep--;
      var canvasPic = new Image();
      canvasPic.onload = function() {
         ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
         ctx.drawImage(canvasPic, 0, 0);
      };
      canvasPic.src = cPushArray[cStep];
      console.log(canvasPic);
   }
}
</code>```

Use clearRect() method to clear the canvas.

Title: Why undo for canvas don't work?

Body:
I have a canvas which I can use to draw on it and I add an undo button. I am saving the canvas in an array (as in the code) and I am calling it click on the undo button.
on console.log you can see that the src is changing but the canvas isn't.

What am I doing wrong?
(the second code is what I am having problem with but I added most of the code because my question always get closed for not giving enough information)

var mousePressed = false;
var lastX, lastY;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");

function InitThis() {

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush()
        }
    });

    $('#myCanvas').mouseleave(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush()
        }
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x;
    lastY = y;
}

var cPushArray = [""];
var cStep = -1;

function cPush() {
    cStep++;
    if (cStep < cPushArray.length) { cPushArray.length = cStep; }
    image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    cPushArray.push(image);
}
function cUndo() {
    if (cStep > 0) {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() { ctx.drawImage(canvasPic, 0, 0); };
        console.log(canvasPic);
    }
}
function cRedo() {
    if (cStep < cPushArray.length - 1) {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function() { ctx.drawImage(canvasPic, 0, 0); }
    }
}

canvas {

    border: 2px solid black;

}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="style.css">

        <canvas id="myCanvas" width="500" height="200"></canvas>

        <button onclick="javascript:clearArea(); return false;">Clear Area</button>
        Line width : <select id="selWidth">
            <option value="1">1</option>
            <option value="3" selected="selected">3</option>
            <option value="5">5</option>
            <option value="7">7</option>
            <option value="9">9</option>
            <option value="11">11</option>
        </select>

        Color : <select id="selColor">
            <option value="black" selected="selected">black</option>
            <option value="blue">blue</option>
            <option value="red">red</option>
            <option value="green">green</option>
            <option value="yellow">yellow</option>
            <option value="gray">gray</option>
        </select>

        <button onclick="javascript:cUndo();return false;">Undo</button>
        <button onclick="javascript:cRedo();return false;">Redo</button>

Body:
You need to clear the canvas before drawing the saved image, when undoing ...

function cUndo() {
   if (cStep > 0) {
      cStep--;
      var canvasPic = new Image();
      canvasPic.onload = function() {
         ctx.clearRect(0, 0, canvas.width, canvas.height); //clear canvas
         ctx.drawImage(canvasPic, 0, 0);
      };
      canvasPic.src = cPushArray[cStep];
      console.log(canvasPic);
   }
}

Use clearRect() method to clear the canvas.


问:
'sm' was not declared in this scope
What is wrong in below reference usage and what is the correct usage. I want to assign a reference to smaller size vector.</p>

```<code>vector<int> R = {3,4,6,3,6,2,3};
vector<int> P = {5,9,8};

        if (P.size()>=R.size())
            vector<int>& sm = R;
        else
            vector<int>& sm= P;
</code>```

答:
There is nothing wrong in this part. But you cannot use sm later, as its scope will be the if or else part only.

You should use something like this:

```<code>vector<int>& sm = (P.size()>=R.size()) ? R : P;
</code>```

Title: 'sm' was not declared in this scope

Body:
What is wrong in below reference usage and what is the correct usage. I want to assign a reference to smaller size vector.

vector<int> R = {3,4,6,3,6,2,3};
vector<int> P = {5,9,8};

        if (P.size()>=R.size())
            vector<int>& sm = R;
        else
            vector<int>& sm= P;

Body:
There is nothing wrong in this part. But you cannot use sm later, as its scope will be the if or else part only.

You should use something like this:

vector<int>& sm = (P.size()>=R.size()) ? R : P;


问:
Check if user hits back button in browser
I'm trying to use the javascript onbeforeunload event to ask the user if they want to exit the page, but I don't want the event to fire (EDIT: "the event" being the dialog box that pops up asking the user to click ok to leave the site or click cancel to stay on the current page) if the user hits the back button since they will be most likely be staying on my site.

So is there a way to tell if a user has hit the back button using javascript or PHP?

I've gotten a solution using a hidden iframe that only works in IE, but I need something that can work for Firefox, Chrome, and Safari if possible.

EDIT: My IE solution works because when the user hits the back button the iframe is sent back but the parent page remains at the same spot. From this I can tell that the user has indeed hit the back button, so I then use history.back(). This little hack doesn't work in any other browser (to my knowledge), so I'm looking for a cross-browser solution.

tl;dr I'm using window.onbeforeunload to pop up a dialog asking users if they want to leave my site or not. I don't want this to pop up when the user hits the back button. How can I tell that the user has hit the back button in their browser?

Thanks,
Rick

答:
Short answer:

No.

Long answer:

Noooooooooooooooooooooooooooo.

please don't try to keep users on your website unless you have a very good reason to. Saving form fields would be an example of a good use. Checking if they're moving on to another website would be a bad use.

People don't travel from page-to-page as much as they did in the early days of the web. Instead they use google and social networks to find interesting pages, and consume separate distinct pieces of information.

ContentLicense: CC BY-SA 2.5


问:
Center of the center with Flexbox
I am trying to get the logo in the centre of the page, but then I want the text to be in the middle (centre) of the logo and the bottom of the page. So it is in the centre of the centred logo and bottom of the page. So in effect, the logo is in the centre of the page, but the text is in the centre, between the logo and bottom of the page. Here is the JSFiddle that I made and below is the code. I can get everything centred but not the way I want where the logo is in the centre and the text is in the centre, between the logo and bottom of the page.

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.centered {
  align-self: center;
}

.center-center {
  align-self: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.</h3>
  </div>
</div></code>```

答:
Add display: flex to center-center and use flex properties to center the text in the remaining space:

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.center-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.</h3>
  </div>
</div></code>```

Title: Center of the center with Flexbox

Body:
I am trying to get the logo in the centre of the page, but then I want the text to be in the middle (centre) of the logo and the bottom of the page. So it is in the centre of the centred logo and bottom of the page. So in effect, the logo is in the centre of the page, but the text is in the centre, between the logo and bottom of the page. Here is the JSFiddle that I made and below is the code. I can get everything centred but not the way I want where the logo is in the centre and the text is in the centre, between the logo and bottom of the page.

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.centered {
  align-self: center;
}

.center-center {
  align-self: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

LOADING

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.

Body:
Add display: flex to center-center and use flex properties to center the text in the remaining space:

/* FRONT PAGE LOADER */

.loader {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: white;
  text-align: center;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  flex-direction: column;
}

.center-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-img {
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

/*SPIN THE LOGO */

@-moz-keyframes spin {
  0% {
    -moz-transform: rotate(0deg);
  }
  100% {
    -moz-transform: rotate(360deg);
  }
}

@-o-keyframes spin {
  0% {
    -o-transform: rotate(0deg);
  }
  100% {
    -o-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<div class="loader">
  <div class="centered" id="blank2"><img class="img-responsive loading-img" src="https://upload.wikimedia.org/wikipedia/commons/d/d0/Newscycle-Circle.png" />
    <p id="blank3">LOADING</p>
  </div>
  <div class="center-center">
    <h3 id="blank1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ultricies risus. Sed pulvinar leo non ligula luctus aliquet.</h3>
  </div>
</div>


问:
EXT JS 5 local grid filtering with client side paging
I want to add filter to my grid that is paged locally.

The problem that I am facing is that this implementation only filters on the current page of the grid and not the whole store data associated with the grid.

Is there any work around by using a filter on a proxy ? or any way to make it filter work on the complete store data.

Thanks in advance.

Below is my Grid:

```<code>Ext.define('MyApp.view.grid.FAQGrid', {
    extend: 'Ext.grid.Panel',

    xtype: 'faqQuesGrid',
    store: 'faqQuestionsStore',
    title: 'FAQ',

    columnLines: true,
    stripeRows: true,

    columns: {
        defaults:
        {
            resizable: false
        },
        items:
        [{
            header: 'Title',
            dataIndex: 'title',
            width: '77%'
        },
        {
            header: 'Category',
            dataIndex: 'categoriesName',
            width: '10%',
            renderer: function(value) {
                return '<a href="#">' + value + '</a>';
            }
        },
        {
            header: 'Published Date',
            dataIndex: 'publishedDate',
            width: '11.5%'
        }]
    },

    plugins: [{
        ptype: 'rowexpander',
        pluginId: 'faqRowId',

        rowBodyTpl: new Ext.XTemplate (
            '<p><b>Question: </b> {question}</p>',
            '<p><br/><b>Answer: </b>',
                '<tpl if="writtenAnswer">',
                    '{writtenAnswer}',
                '</tpl>',
                '<tpl if="videoAnswer">',
                    '{videoAnswer}',
                '</tpl>',
            '</p>',
             '<p><br/><i><b>Posted on</b> {publishedDate} | <b>Filed Under</b>: {categoriesName}</i></p>',
            '<tpl if="searchTagsName">',
                '<p><i><b>Tags</b>: ',
                    '<tpl for="searchTagsName">',
                        '{.};',
                    '</tpl>',
                '</i></p>',
            '</tpl>'
        )
    }],

    tools:
    [{
        xtype: 'button',
        text: 'Expand All',
        itemId: 'expandButtonId',
        iconAlign: 'left',
        style: 'margin: 5px'
    },{
        xtype: 'button',
        text: 'Collapse All',
        itemId: 'collapseButtonId',
        iconAlign: 'left',
        style: 'margin: 5px'
    },{
        xtype: 'textfield',
        itemId: 'searchItem',
        allowBlank: false,
        emptyText: 'Search FAQ',
        style: 'margin: 5px'
    },{
        baseCls: 'search-icon',
        itemId: 'searchIconId',
        height: 20,
        iconAlign: 'right',
        tooltip: 'Search Grid',
        style: 'margin: 5px'
    }],

    dockedItems:
    [{
        xtype: 'pagingtoolbar',
        dock: 'bottom',
        store: 'faqQuestionsStore',
        itemId: 'faqPagingToolbarId',
        displayInfo: true,
        displayMsg: 'Displaying questions {0} - {1} of {2}',
        emptyMsg: "No questions to display",
    }],

    listeners: {
        cellclick : function(grid, rowIndex, cellIndex, record, e) {
            if(cellIndex == 2){
                var clickedDataIndex = grid.headerCt.getGridColumns()[cellIndex].dataIndex;
                var clickedCellValue = record.get(clickedDataIndex);
                MyApp.app.getController('MyApp.controller.CategoriesController').getCategoryQuestions(clickedCellValue);
            }
        }
    }
});
</code>```

Store:

```<code>Ext.define('MyApp.store.FAQQuestionsStore', {
    extend: 'Ext.data.Store',
    model: 'MyApp.model.QuestionsModel',
    requires: [
            'MyApp.model.QuestionsModel'
            ],

    storeId: 'faqQuestionsStore',
    autoLoad: false,
    remoteSort: true,
    remoteFilter: false,

    pageSize: 25,

    proxy: {
        type: 'memory',
        enablePaging: true,

        reader: {
            type: 'json'
        }
    }
});
</code>```

I am performing filtering as below:

```<code>this.control({
            'faqQuesGrid #searchItem':{
                change: this.filterQuestions
            }
});

filterQuestions: function(textfield) {
        var grid = textfield.up('panel');
        var store = grid.getStore();
        if(store != null) {
            //clear filters first
            store.remoteFilter = false;
            store.clearFilter(true);

            var filters = new Array();

            //add filter to filter array
            if(textfield.isValid()){
                var searchTxt = textfield.getValue();

                //create filter and add to filters array
                var questionFilter = {
                    property: 'question',
                    anyMatch: true,
                    caseSensitive: false,
                    value   : searchTxt
                };

                filters.push(questionFilter);
            } else{
                 store.read();
            }
            //else condition is necessary to populate the grid correctly when a search query is removed

            //add filters to store
            if(filters.length > 0){
                store.addFilter(filters);
            }
        }
    },

//to remove any filters added when we leave this page to prevent issues with other page functionality
deactivate: function(){
                    var store = Ext.getStore('faqQuesStore');
                    if(store != null){
                        store.clearFilter();
                    }

                }
</code>```

答:
As Evan Trimboli mentioned in the comments to your question, you have to set remoteFilter: true for store to filter entire data set using memory proxy.

The filtering is happening "remotely" in the proxy. It acts like a server. Filtering locally means do the filtering in the store. Remote means have it handled by the proxy.

I want to note that Ext.data.proxy.Memory.read use Ext.util.Filter.createFilterFn to create a filter function based on passed Ext.util.Filter[] (with property-value configs):

```<code>// Filter the resulting array of records
if (filters && filters.length) {
    // Total will be updated by setting records
    resultSet.setRecords(records = Ext.Array.filter(records, Ext.util.Filter.createFilterFn(filters)));
    resultSet.setTotal(records.length);
}
</code>```

So, if you want to use different filter logic, you can override memroy proxy read method and use custom function to create filter function. Check this answer for example.

Body:
I want to add filter to my grid that is paged locally.

The problem that I am facing is that this implementation only filters on the current page of the grid and not the whole store data associated with the grid.

Is there any work around by using a filter on a proxy ? or any way to make it filter work on the complete store data.

Thanks in advance.

Below is my Grid:

Ext.define('MyApp.view.grid.FAQGrid', {
    extend: 'Ext.grid.Panel',

    xtype: 'faqQuesGrid',
    store: 'faqQuestionsStore',
    title: 'FAQ',

    columnLines: true,
    stripeRows: true,

    columns: {
        defaults:
        {
            resizable: false
        },
        items:
        [{
            header: 'Title',
            dataIndex: 'title',
            width: '77%'
        },
        {
            header: 'Category',
            dataIndex: 'categoriesName',
            width: '10%',
            renderer: function(value) {
                return '' + value + '';
            }
        },
        {
            header: 'Published Date',
            dataIndex: 'publishedDate',
            width: '11.5%'
        }]
    },

    plugins: [{
        ptype: 'rowexpander',
        pluginId: 'faqRowId',

        rowBodyTpl: new Ext.XTemplate (
            '
Question:  {question}
',
            '

Answer: ',
                '<tpl if="writtenAnswer">',
                    '{writtenAnswer}',
                '</tpl>',
                '<tpl if="videoAnswer">',
                    '{videoAnswer}',
                '</tpl>',
            '
',
             '

Posted on {publishedDate} | Filed Under: {categoriesName}
',
            '<tpl if="searchTagsName">',
                '
Tags: ',
                    '<tpl for="searchTagsName">',
                        '{.};',
                    '</tpl>',
                '
',
            '</tpl>'
        )
    }],

    tools:
    [{
        xtype: 'button',
        text: 'Expand All',
        itemId: 'expandButtonId',
        iconAlign: 'left',
        style: 'margin: 5px'
    },{
        xtype: 'button',
        text: 'Collapse All',
        itemId: 'collapseButtonId',
        iconAlign: 'left',
        style: 'margin: 5px'
    },{
        xtype: 'textfield',
        itemId: 'searchItem',
        allowBlank: false,
        emptyText: 'Search FAQ',
        style: 'margin: 5px'
    },{
        baseCls: 'search-icon',
        itemId: 'searchIconId',
        height: 20,
        iconAlign: 'right',
        tooltip: 'Search Grid',
        style: 'margin: 5px'
    }],

    dockedItems:
    [{
        xtype: 'pagingtoolbar',
        dock: 'bottom',
        store: 'faqQuestionsStore',
        itemId: 'faqPagingToolbarId',
        displayInfo: true,
        displayMsg: 'Displaying questions {0} - {1} of {2}',
        emptyMsg: "No questions to display",
    }],

    listeners: {
        cellclick : function(grid, rowIndex, cellIndex, record, e) {
            if(cellIndex == 2){
                var clickedDataIndex = grid.headerCt.getGridColumns()[cellIndex].dataIndex;
                var clickedCellValue = record.get(clickedDataIndex);
                MyApp.app.getController('MyApp.controller.CategoriesController').getCategoryQuestions(clickedCellValue);
            }
        }
    }
});

Store:

Ext.define('MyApp.store.FAQQuestionsStore', {
    extend: 'Ext.data.Store',
    model: 'MyApp.model.QuestionsModel',
    requires: [
            'MyApp.model.QuestionsModel'
            ],

    storeId: 'faqQuestionsStore',
    autoLoad: false,
    remoteSort: true,
    remoteFilter: false,

    pageSize: 25,

    proxy: {
        type: 'memory',
        enablePaging: true,

        reader: {
            type: 'json'
        }
    }
});

I am performing filtering as below:

this.control({
            'faqQuesGrid #searchItem':{
                change: this.filterQuestions
            }
});

filterQuestions: function(textfield) {
        var grid = textfield.up('panel');
        var store = grid.getStore();
        if(store != null) {
            //clear filters first
            store.remoteFilter = false;
            store.clearFilter(true);

            var filters = new Array();

            //add filter to filter array
            if(textfield.isValid()){
                var searchTxt = textfield.getValue();

                //create filter and add to filters array
                var questionFilter = {
                    property: 'question',
                    anyMatch: true,
                    caseSensitive: false,
                    value   : searchTxt
                };

                filters.push(questionFilter);
            } else{
                 store.read();
            }
            //else condition is necessary to populate the grid correctly when a search query is removed

            //add filters to store
            if(filters.length > 0){
                store.addFilter(filters);
            }
        }
    },

//to remove any filters added when we leave this page to prevent issues with other page functionality
deactivate: function(){
                    var store = Ext.getStore('faqQuesStore');
                    if(store != null){
                        store.clearFilter();
                    }

                }

Body:
As Evan Trimboli mentioned in the comments to your question, you have to set remoteFilter: true for store to filter entire data set using memory proxy.

The filtering is happening "remotely" in the proxy. It acts like a server. Filtering locally means do the filtering in the store. Remote means have it handled by the proxy.

I want to note that Ext.data.proxy.Memory.read use Ext.util.Filter.createFilterFn to create a filter function based on passed Ext.util.Filter[] (with property-value configs):

// Filter the resulting array of records
if (filters && filters.length) {
    // Total will be updated by setting records
    resultSet.setRecords(records = Ext.Array.filter(records, Ext.util.Filter.createFilterFn(filters)));
    resultSet.setTotal(records.length);
}

So, if you want to use different filter logic, you can override memroy proxy read method and use custom function to create filter function. Check this answer for example.


问:
Kotlin - Is kotlin contain Object class like base class in java?
In my code i defined below variable,

```<code>var obj_str: Object = "NEW" as Object
</code>```

which gives warning This class shouldn't be used in Kotlin. Use kotlin.Any instead

So, i need to know Any is similar to Object in kotlin or any thing else?

Also need to know for wait method like wait(), notify() etc are available in Object class but not in Any, so perform that operation in kotlin?

答:
Yes, Any is the root of the Kotlin class hierarchy exactly like Object is the root of the Java class hierarchy.

In other words, every non-nullable type is a subtype of Any in Kotlin, and all types are subtypes of Any?.

When using Kotlin on the JVM, it's actually just mapped to Object under the hood, so they are the exact same thing.

Body:
In my code i defined below variable,

var obj_str: Object = "NEW" as Object

which gives warning This class shouldn't be used in Kotlin. Use kotlin.Any instead

So, i need to know Any is similar to Object in kotlin or any thing else?

Also need to know for wait method like wait(), notify() etc are available in Object class but not in Any, so perform that operation in kotlin?


问:
colorchange animation for background
I Want to change background color slowly and use this code in css file:

```<code>body {
margin-top:60px;
font-family: sans-serif;
animation: colorchange 50s;
-webkit-animation: colorchange 50s;
     }

@keyframes colorchange{
    0%   {background: #FFCCff;}
   25%  {background: #FFFFCC;}
   50%  {background: #CCCC99;}
   75% {background: #CC9999}
   100%{background:#CCCCFF}
 }

  @-webkit-keyframes colorchange  {
     0%   {background:#FFCCFF;}
     25%  {background: #FFFFCC;}
    50%  {background:  #CCCC99;}
    75% {background: #CC9999;}
    100%{background:#CCCCFF;}
 }
</code>```

But I Want this change never stop ,How I can Do?

答:
Use the infinite option:

```<code>animation: colorchange 50s infinite;
-webkit-animation: colorchange 50s infinite;
</code>```

Title: colorchange animation for background

Body:
I Want to change background color slowly and use this code in css file:

body {
margin-top:60px;
font-family: sans-serif;
animation: colorchange 50s;
-webkit-animation: colorchange 50s;
     }

@keyframes colorchange{
    0%   {background: #FFCCff;}
   25%  {background: #FFFFCC;}
   50%  {background: #CCCC99;}
   75% {background: #CC9999}
   100%{background:#CCCCFF}
 }

  @-webkit-keyframes colorchange  {
     0%   {background:#FFCCFF;}
     25%  {background: #FFFFCC;}
    50%  {background:  #CCCC99;}
    75% {background: #CC9999;}
    100%{background:#CCCCFF;}
 }

But I Want this change never stop ,How I can Do?

Body:
Use the infinite option:

animation: colorchange 50s infinite;
-webkit-animation: colorchange 50s infinite;


问:
Coroutine not starting
I'm using a lightning GameObject prefab to have a visual effect when i'm firing my weapon. When I fire, I enable that lightning object and I have a generic component that deactivates it after a certain delay.

The problem is that the "should wait" log is never reached, and instead of waiting the set delay, it waits much longer and doesn't actually deactivate the GameObject.

Here's the code for the DeactivateAfter component

public class DestroyAfter : MonoBehaviour {

    [SerializeField]
    private float delay;
    private bool firstRun = true;

    void OnEnable () {
        if (firstRun == false) {
            StartCoroutine(DestroyMethod());
        }
        firstRun = false;
    }

    public IEnumerator DestroyMethod() {
        Debug.LogFormat("Should wait; Time: {0}", Time.time);
        yield return new WaitForSeconds(delay);
        Debug.LogFormat("Should deactivate; Time: {0}", Time.time);
        gameObject.SetActive(false);
    }
}
```

答:
The condition never be true, you need to set firstRun condition to true first.

private bool firstRun = **true**;

void OnEnable () {
    if (firstRun == **true**) {
        StartCoroutine(DestroyMethod());
    }
    firstRun = false;
}
```

<p>And i ever like to set flag first and later do what you want:</p>

<pre class="lang-c# prettyprint-override"><code>private bool firstRun = **true**;

void OnEnable () {
    if (firstRun == **true**) {
        firstRun = false;
        StartCoroutine(DestroyMethod());
    }
}
</code>```

Title: Coroutine not starting

Body:
The condition never be true, you need to set firstRun condition to true first.

private bool firstRun = **true**;

void OnEnable () {
    if (firstRun == **true**) {
        StartCoroutine(DestroyMethod());
    }
    firstRun = false;
}

And i ever like to set flag first and later do what you want:

private bool firstRun = **true**;

void OnEnable () {
    if (firstRun == **true**) {
        firstRun = false;
        StartCoroutine(DestroyMethod());
    }
}


问:
Why there are contentions in places with no lockings?
I run a concurrency profile of a software in Visual Studio 2010 and found some contentions on lines of code that are not within locks. Say, a new operation to create an array, or a thread-local DynamicMethod.Invoke call. Some contentions are on simply assignments. I could not figure out why these lines cause intentions because there should be no way they are under any lockings in my code.

Anyone experiences similar problems? I think the contentions displayed in VS2010 concurrency profiler should all be caused by waiting on a lock or entering a piece of mutex section. Thanks.

答: Newing an array and jitting your dynamic method would both allocate memory, so is it possible that it's just contention in the allocator?  Of course, that doesn't explain the assignment lines...</p>


问:
C# event with multiple arguments
How to make multiple arguments more than two? CustomButtonClickEventArgs is shared by many places, I don't want to modify. How to append ActiveRow and ActiveCol arguments which indicated the ComboBox location in a Grid into the ComboBoxCustomButtonClick event like below what I 'expected'?

```<code>private void MyUC1_ComboBoxCustomButtonClick(object sender, MyUC.CustomButtonClickEventArgs e, int ActiveRow, int ActiveCol)
</code>```

declares:

```<code>public class CustomButtonClickEventArgs : EventArgs
    {
        public readonly int Index;

        public readonly string Key;

        public readonly string Tag;

        public readonly Keys ModifierKeys;

        public CustomButtonClickEventArgs(int index, string key, string tag, Keys modifierKeys)
        {
            this.Index = index;
            this.Key = key;
            this.Tag = tag;
            this.ModifierKeys = modifierKeys;
        }
    }

public delegate void CustomButtonClickEventHandler(object sender, CustomButtonClickEventArgs e);
</code>```

ComboBox located in Grid Cell(1,1)

答:
my new CustomButtonClickEventHandler defined as the below.</p>

```<code>public delegate void ComboBoxCustomButtonClickEventHandler(object Sender, int ComboBoxCol, int ActiveRow, int ActiveCol, CustomButtonClickEventArgs e);

[Category("ComboBox"), Description("Occurs when a custom button of the ComboBox is clicked.")]
public event ComboBoxCustomButtonClickEventHandler ComboBoxCustomButtonClick;
</code>```

Title: C# event with multiple arguments

Body:
How to make multiple arguments more than two? CustomButtonClickEventArgs is shared by many places, I don't want to modify. How to append ActiveRow and ActiveCol arguments which indicated the ComboBox location in a Grid into the ComboBoxCustomButtonClick event like below what I 'expected'?

private void MyUC1_ComboBoxCustomButtonClick(object sender, MyUC.CustomButtonClickEventArgs e, int ActiveRow, int ActiveCol)

declares:

public class CustomButtonClickEventArgs : EventArgs
    {
        public readonly int Index;

        public readonly string Key;

        public readonly string Tag;

        public readonly Keys ModifierKeys;

        public CustomButtonClickEventArgs(int index, string key, string tag, Keys modifierKeys)
        {
            this.Index = index;
            this.Key = key;
            this.Tag = tag;
            this.ModifierKeys = modifierKeys;
        }
    }

public delegate void CustomButtonClickEventHandler(object sender, CustomButtonClickEventArgs e);

ComboBox located in Grid Cell(1,1)

Body:
my new CustomButtonClickEventHandler defined as the below.

public delegate void ComboBoxCustomButtonClickEventHandler(object Sender, int ComboBoxCol, int ActiveRow, int ActiveCol, CustomButtonClickEventArgs e);

[Category("ComboBox"), Description("Occurs when a custom button of the ComboBox is clicked.")]
public event ComboBoxCustomButtonClickEventHandler ComboBoxCustomButtonClick;