问:
One button to fire toggle functions? Press button -> toggleOn(), press again -> toggleOff(), press again -> toggleOn()
Is it possible to use the same onClick from a button to make it a "toggle"?

I have a button, <button>Toggle</button> and basically toggling it on should execute either toggleOn() or toggleOff().

How do I do this with just onClick property?

答:
You will need to maintain some state as to whether the button is "on" or "off".  I would do this by creating a closure over a buttonState variable:

const setText = ( text ) => () => {
    document.getElementById('toggled').innerHTML = text;
};

const toggleOff = setText('off');
const toggleOn = setText('on');

const makeClickhandler = () => {
        let buttonState = false;
        return () => {
            buttonState ? toggleOff() : toggleOn();
            buttonState = !buttonState;
        }
    };

document.getElementById('yourbuttonid').addEventListener('click', makeClickhandler());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id='yourbuttonid'>Toggle</button>
<span id='toggled'>off</span></code>```

Body:
You will need to maintain some state as to whether the button is "on" or "off".  I would do this by creating a closure over a buttonState variable:

const setText = ( text ) => () => {
    document.getElementById('toggled').innerHTML = text;
};

const toggleOff = setText('off');
const toggleOn = setText('on');

const makeClickhandler = () => {
        let buttonState = false;
        return () => {
            buttonState ? toggleOff() : toggleOn();
            buttonState = !buttonState;
        }
    };

document.getElementById('yourbuttonid').addEventListener('click', makeClickhandler());

<button id='yourbuttonid'>Toggle</button>
<span id='toggled'>off</span>


来源: stackexchange

问:
open a window(wpf) on the foreground from a page(wpf)
I am working at a WPF desktop application, in this application I open a wpf page which contains a listbox of contacts on a frame.

When I double-click on a contact, a window opens to modify it. The problem is that the window is opened in the back and I want it on the foreground , I used this code

```<code>private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   if (listBox.SelectedItem != null)
   {
       modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
       window.Owner=this;
       window.Show();
    }
}
</code>```

It didn't work because it's and not a window
So what can I do to make my opened on the foreground ?

答:
```<code>private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
    if (listBox.SelectedItem != null)
    {
        modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
        window.Owner = MainWindow.GetWindow(this);
        window.Show();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working at a WPF desktop application, in this application I open a wpf page which contains a listbox of contacts on a frame.

When I double-click on a contact, a window opens to modify it. The problem is that the window is opened in the back and I want it on the foreground , I used this code

private void HandleDoubleClick(object sender, MouseButtonEventArgs e)
{
   if (listBox.SelectedItem != null)
   {
       modify_contact window = new modify_contact(list[listBox.SelectedIndex]);
       window.Owner=this;
       window.Show();
    }
}

It didn't work because it's and not a window
So what can I do to make my opened on the foreground ?


问:
Change img src by clicking li item CSS
I have a ul of images and a main image. Is it possible to change the src of the main image by clicking one of the ul just by CSS?</p>

答:
I have a ul of images and a main image. Is it possible to change the
  src of the main image by clicking one of the ul just by CSS?

It is possible to achieve something approaching what you describe using just CSS.

You can take advantage of the fact that elements which have the tabindex attribute can take focus. Then you can use the :focus pseudo-class in your style rules.

However... it goes without saying: once you remove focus from the element which has it, the style rule invoking :focus will no longer have any effect.

Working Example:

div, div img {
display: inline-block;
width: 50px;
height: 50px;
margin: 0 0 2px;
padding: 0;
cursor: pointer;
}

.display-image {
position: relative;
margin-left: 12px;
vertical-align: top;
cursor: default;
}

.display-image img {
position: absolute;
width: 200px;
height: 200px;
opacity: 0;
cursor: default;
transition: opacity 1s ease-out;
}

div:nth-of-type(1):focus ~ .display-image img:nth-of-type(1),
div:nth-of-type(2):focus ~ .display-image img:nth-of-type(2),
div:nth-of-type(3):focus ~ .display-image img:nth-of-type(3),
div:nth-of-type(4):focus ~ .display-image img:nth-of-type(4),
div:nth-of-type(5):focus ~ .display-image img:nth-of-type(5) {
opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Click on any of the thumbnail images</h2>
<div tabindex="0"><img src="http://placekitten.com/205/205" /></div>
<div tabindex="0"><img src="http://placekitten.com/209/209/" /></div>
<div tabindex="0"><img src="http://placekitten.com/210/210/" /></div>
<div tabindex="0"><img src="http://placekitten.com/211/211/" /></div>
<div tabindex="0"><img src="http://placekitten.com/212/212/" /></div>

<div class="display-image">
<img src="http://placekitten.com/205/205" />
<img src="http://placekitten.com/209/209/" />
<img src="http://placekitten.com/210/210/" />
<img src="http://placekitten.com/211/211/" />
<img src="http://placekitten.com/212/212/" />
</div></code>```

Title: Change img src by clicking li item CSS

Body:
I have a ul of images and a main image. Is it possible to change the
  src of the main image by clicking one of the ul just by CSS?

It is possible to achieve something approaching what you describe using just CSS.

You can take advantage of the fact that elements which have the tabindex attribute can take focus. Then you can use the :focus pseudo-class in your style rules.

However... it goes without saying: once you remove focus from the element which has it, the style rule invoking :focus will no longer have any effect.

Working Example:

div, div img {
display: inline-block;
width: 50px;
height: 50px;
margin: 0 0 2px;
padding: 0;
cursor: pointer;
}

.display-image {
position: relative;
margin-left: 12px;
vertical-align: top;
cursor: default;
}

.display-image img {
position: absolute;
width: 200px;
height: 200px;
opacity: 0;
cursor: default;
transition: opacity 1s ease-out;
}

div:nth-of-type(1):focus ~ .display-image img:nth-of-type(1),
div:nth-of-type(2):focus ~ .display-image img:nth-of-type(2),
div:nth-of-type(3):focus ~ .display-image img:nth-of-type(3),
div:nth-of-type(4):focus ~ .display-image img:nth-of-type(4),
div:nth-of-type(5):focus ~ .display-image img:nth-of-type(5) {
opacity: 1;
}

<h2>Click on any of the thumbnail images</h2>
<div tabindex="0"><img src="http://placekitten.com/205/205" /></div>
<div tabindex="0"><img src="http://placekitten.com/209/209/" /></div>
<div tabindex="0"><img src="http://placekitten.com/210/210/" /></div>
<div tabindex="0"><img src="http://placekitten.com/211/211/" /></div>
<div tabindex="0"><img src="http://placekitten.com/212/212/" /></div>

<div class="display-image">
<img src="http://placekitten.com/205/205" />
<img src="http://placekitten.com/209/209/" />
<img src="http://placekitten.com/210/210/" />
<img src="http://placekitten.com/211/211/" />
<img src="http://placekitten.com/212/212/" />
</div>


问:
Sum in an ArrayList with HashMap or with other method
I can't figure it out.

```<code>List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});
</code>```

I would like to put in an other ArrayList sum by breed and rank

```<code>List<String[]> dogTotal = new ArrayList<String[]>();
</code>```

To get an output like this if i iterate over dogTotal

```<code>"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"
</code>```

I have tried to use HashMap without success.

答:
You need to create a Class Dog.

Once you have a Dog class you can do this:

```<code>Dog d2 =  new Dog("t4639", "Akita", "First", "Marshal");
Dog d3 = new Dog( "t4638", "Akita", "First", "Tom");
Dog d4 =  new Dog("t4637", "Beagle", "First", "Eddy");
Dog d5 =new Dog("t4636", "Beagle", "Second", "Franky");

List<Dog> dogs = Arrays.asList(d2, d3, d4, d5);
</code>```

And then there are some nifty things you can use with stream.  The below will create a hashmap that you can group anything by.  See here:  Group by in Java 8 on multiple fields with aggregations

```<code>dogs.stream()
    .collect(Collectors.groupingBy(Dog::getBreed,
                 Collectors.groupingBy(Dog::getRank, Collectors.counting())));
</code>```

Look how much cleaner this code is.  This is using declarative style rather than imperative.

Returns:

```<code>{Akita={First=2}, Beagle={Second=1, First=1}}
</code>```

Body:
I can't figure it out.

List<String[]> dogList = new ArrayList<String[]>();

dogList.add(new String[] { "id_tag", "breed", "rank", "nickname"});
dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});

I would like to put in an other ArrayList sum by breed and rank

List<String[]> dogTotal = new ArrayList<String[]>();

To get an output like this if i iterate over dogTotal

"Akita", "First", "2"
"Beagle", "First", "1"
"Beagle", "Second", "1"

I have tried to use HashMap without success.

Body:
You need to create a Class Dog.

Once you have a Dog class you can do this:

Dog d2 =  new Dog("t4639", "Akita", "First", "Marshal");
Dog d3 = new Dog( "t4638", "Akita", "First", "Tom");
Dog d4 =  new Dog("t4637", "Beagle", "First", "Eddy");
Dog d5 =new Dog("t4636", "Beagle", "Second", "Franky");

List<Dog> dogs = Arrays.asList(d2, d3, d4, d5);

And then there are some nifty things you can use with stream.  The below will create a hashmap that you can group anything by.  See here:  Group by in Java 8 on multiple fields with aggregations

dogs.stream()
    .collect(Collectors.groupingBy(Dog::getBreed,
                 Collectors.groupingBy(Dog::getRank, Collectors.counting())));

Look how much cleaner this code is.  This is using declarative style rather than imperative.

Returns:

{Akita={First=2}, Beagle={Second=1, First=1}}


问:
Passing two queues to Tensorflow training
I'm trying to create a train operation based on CIFAR10 example from Tensorflow that uses tf.RandomShuffleQueue and my labels comes from the name of the files as mentioned in (Accessing filename from file queue in Tensor Flow). How can I use this code with that?

When I try to run the following code, where path is a directory with many files:

```<code>filenames = [path, f) for f in os.listdir(path)][1:]
file_fifo = tf.train.string_input_producer(filenames,
                                           shuffle=False,
                                           capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
image = tf.image.decode_png(value, channels=3, dtype=tf.uint8)
image.set_shape([config.image_height, config.image_width, config.image_depth])
image = tf.cast(image, tf.float32)
image = tf.divide(image, 255.0)
labels = [int(os.path.basename(f).split('_')[-1].split('.')[0]) for f in filenames]
label_fifo = tf.FIFOQueue(len(filenames), tf.int32, shapes=[[]])
label_enqueue = label_fifo.enqueue_many([tf.constant(labels)])
label = label_fifo.dequeue()
bq = tf.RandomShuffleQueue(capacity=16 * batch_size,
                           min_after_dequeue=8 * batch,
                           dtypes=[tf.float32, tf.int32])
batch_enqueue_op = bq.enqueue([image, label_enqueue])
runner = tf.train.queue_runner.QueueRunner(bq, [batch_enqueue_op] * num_threads)
tf.train.add_queue_runner(runner)

# Read 'batch' labels + images from the example queue.
images, labels = batch_queue.dequeue_many(FLAGS.batch_size)
labels = tf.reshape(labels, [FLAGS.batch_size, 1])
</code>```

I get obvious erros, because I know my code doesn't make much sense. I have two FIFO queues file_fifo and label_fifo, but I don't know how to make my label_fifo input of my tf.RandomShuffleQueue.

Can someone help? Thank you :-)

答:
I changed my code to:

```<code>filenames = [os.path.join(FLAGS.data_path, f) for f in os.listdir(FLAGS.data_path)][1:]
np.random.shuffle(filenames)
file_fifo = tf.train.string_input_producer(filenames, shuffle=False, capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
image = tf.image.decode_png(value, channels=3, dtype=tf.uint8)
image.set_shape([config.image_height, config.image_width, config.image_depth])
image = tf.cast(image, tf.float32)
image = tf.divide(image, 255.0)

labels = [int(os.path.basename(f).split('_')[-1].split('.')[0]) for f in filenames]
label_fifo = tf.FIFOQueue(len(filenames), tf.int32, shapes=[[]])
label_enqueue = label_fifo.enqueue_many([tf.constant(labels)])
label = label_fifo.dequeue()

if is_train:
    images, label_batch = tf.train.shuffle_batch([image, label],
                                                 batch_size=FLAGS.batch_size,
                                                 num_threads=FLAGS.num_threads,
                                                 capacity=16 * FLAGS.batch_size,
                                                 min_after_dequeue=8 * FLAGS.batch_size)
labels = tf.reshape(label_batch, [FLAGS.batch_size, 1])
</code>```

For training I have:

```<code>class _LoggerHook(tf.train.SessionRunHook):
    """Logs loss and runtime."""

    def begin(self):
        self._step = -1

    def before_run(self, run_context):
        self._step += 1
        self._start_time = time.time()
        if self._step % int(config.train_examples / FLAGS.batch_size) == 0 or self._step == 0:
            run_context.session.run(label_enqueue_op)
        return tf.train.SessionRunArgs({'loss': loss, 'net': net})
</code>```

and I run training as:

```<code>with tf.train.MonitoredTrainingSession(
        checkpoint_dir=FLAGS.train_path,
        hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_steps), tf.train.NanTensorHook(loss), _LoggerHook()],
        config=tf.ConfigProto(log_device_placement=FLAGS.log_device_placement)) as mon_sess:
        while not mon_sess.should_stop():
            mon_sess.run(train_op)
</code>```

The training starts, but it runs only for the very first step and hangs - maybe because it's waiting for some queue command

Body:
I'm trying to create a train operation based on CIFAR10 example from Tensorflow that uses tf.RandomShuffleQueue and my labels comes from the name of the files as mentioned in (Accessing filename from file queue in Tensor Flow). How can I use this code with that?

When I try to run the following code, where path is a directory with many files:

filenames = [path, f) for f in os.listdir(path)][1:]
file_fifo = tf.train.string_input_producer(filenames,
                                           shuffle=False,
                                           capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
image = tf.image.decode_png(value, channels=3, dtype=tf.uint8)
image.set_shape([config.image_height, config.image_width, config.image_depth])
image = tf.cast(image, tf.float32)
image = tf.divide(image, 255.0)
labels = [int(os.path.basename(f).split('_')[-1].split('.')[0]) for f in filenames]
label_fifo = tf.FIFOQueue(len(filenames), tf.int32, shapes=[[]])
label_enqueue = label_fifo.enqueue_many([tf.constant(labels)])
label = label_fifo.dequeue()
bq = tf.RandomShuffleQueue(capacity=16 * batch_size,
                           min_after_dequeue=8 * batch,
                           dtypes=[tf.float32, tf.int32])
batch_enqueue_op = bq.enqueue([image, label_enqueue])
runner = tf.train.queue_runner.QueueRunner(bq, [batch_enqueue_op] * num_threads)
tf.train.add_queue_runner(runner)

# Read 'batch' labels + images from the example queue.
images, labels = batch_queue.dequeue_many(FLAGS.batch_size)
labels = tf.reshape(labels, [FLAGS.batch_size, 1])

I get obvious erros, because I know my code doesn't make much sense. I have two FIFO queues file_fifo and label_fifo, but I don't know how to make my label_fifo input of my tf.RandomShuffleQueue.

Can someone help? Thank you :-)

Body:
I changed my code to:

filenames = [os.path.join(FLAGS.data_path, f) for f in os.listdir(FLAGS.data_path)][1:]
np.random.shuffle(filenames)
file_fifo = tf.train.string_input_producer(filenames, shuffle=False, capacity=len(filenames))
reader = tf.WholeFileReader()
key, value = reader.read(file_fifo)
image = tf.image.decode_png(value, channels=3, dtype=tf.uint8)
image.set_shape([config.image_height, config.image_width, config.image_depth])
image = tf.cast(image, tf.float32)
image = tf.divide(image, 255.0)

labels = [int(os.path.basename(f).split('_')[-1].split('.')[0]) for f in filenames]
label_fifo = tf.FIFOQueue(len(filenames), tf.int32, shapes=[[]])
label_enqueue = label_fifo.enqueue_many([tf.constant(labels)])
label = label_fifo.dequeue()

if is_train:
    images, label_batch = tf.train.shuffle_batch([image, label],
                                                 batch_size=FLAGS.batch_size,
                                                 num_threads=FLAGS.num_threads,
                                                 capacity=16 * FLAGS.batch_size,
                                                 min_after_dequeue=8 * FLAGS.batch_size)
labels = tf.reshape(label_batch, [FLAGS.batch_size, 1])

For training I have:

class _LoggerHook(tf.train.SessionRunHook):
    """Logs loss and runtime."""

    def begin(self):
        self._step = -1

    def before_run(self, run_context):
        self._step += 1
        self._start_time = time.time()
        if self._step % int(config.train_examples / FLAGS.batch_size) == 0 or self._step == 0:
            run_context.session.run(label_enqueue_op)
        return tf.train.SessionRunArgs({'loss': loss, 'net': net})

and I run training as:

with tf.train.MonitoredTrainingSession(
        checkpoint_dir=FLAGS.train_path,
        hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_steps), tf.train.NanTensorHook(loss), _LoggerHook()],
        config=tf.ConfigProto(log_device_placement=FLAGS.log_device_placement)) as mon_sess:
        while not mon_sess.should_stop():
            mon_sess.run(train_op)

The training starts, but it runs only for the very first step and hangs - maybe because it's waiting for some queue command


答:
```<code>List<String[]> dogList = new ArrayList<String[]>();

        dogList.add(new String[] { "t4639", "Akita", "First", "Marshal"});
        dogList.add(new String[] { "t4638", "Akita", "First", "Tom"});
        dogList.add(new String[] { "t4637", "Beagle", "First", "Eddy"});
        dogList.add(new String[] { "t4636", "Beagle", "Second", "Franky"});

        HashMap<String, Integer> hmap = new HashMap();

        for(String[] dog : dogList)
        {
            String type = dog[1] + ":" + dog[2];
            if(hmap.containsKey(type))
            {
                hmap.put(type, hmap.get(type) + 1);
            }
            else
            {
                hmap.put(type, 1);
            }
        }

        for (String entry: hmap.keySet()){

            String key =entry.toString();
            String value = hmap.get(entry).toString();
            System.out.println(key + " " + value);
        }
    }
</code>```

Title: Sum in an ArrayList with HashMap or with other method


问:
Using font-awesome in ionic 2
How can i use fontawesome with ionic 2, i've following this tutorial but it's not working.

答:
I tried most of the answers above but they were either too complicated or had a limitation when the core of Ionic2 was upgraded so here is my solution:

It requires manually upgrading of FA when a new version comes out but I don't need to upgrade often as I only use a few select icons.

Ignore the SASS files and copy the contents of \node_modules\font-awesome\fonts to \src\assets\fonts. Also copy \node_modules\font-awesome\css\font-awesome.min.css to the same place.

Reference the csss in your index.html file like this:

```<code>  <!--Custom Fonts-->
  <link href="assets/fonts/comfortaa/comfortaa.css" rel="stylesheet" />
  <link href="assets/fonts/gloriahallelujah/gloriahallelujah.css" rel="stylesheet" />
  <link href="assets/fonts/font-awesome.min.css" rel="stylesheet" />
</code>```

Then to use it, put this into the page's scss:

```<code>  .logo-text {
    font-family: 'comfortaa-bold';
  }
</code>```

and this in the html:

```<code><h4 class="white-text slogan-text">Come bien a la mitad de precio</h4>
</code>```

And that should be it...

Title: Using font-awesome in ionic 2

Body:
I tried most of the answers above but they were either too complicated or had a limitation when the core of Ionic2 was upgraded so here is my solution:

It requires manually upgrading of FA when a new version comes out but I don't need to upgrade often as I only use a few select icons.

Ignore the SASS files and copy the contents of \node_modules\font-awesome\fonts to \src\assets\fonts. Also copy \node_modules\font-awesome\css\font-awesome.min.css to the same place.

Reference the csss in your index.html file like this:

  <!--Custom Fonts-->
  <link href="assets/fonts/comfortaa/comfortaa.css" rel="stylesheet" />
  <link href="assets/fonts/gloriahallelujah/gloriahallelujah.css" rel="stylesheet" />
  <link href="assets/fonts/font-awesome.min.css" rel="stylesheet" />

Then to use it, put this into the page's scss:

  .logo-text {
    font-family: 'comfortaa-bold';
  }

and this in the html:

<h4 class="white-text slogan-text">Come bien a la mitad de precio</h4>

And that should be it...


问:
iphone sdk beyond bounds NSException
I am having an "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 24 beyond bounds [0 .. 23]'"
I'm not sure how to put my .m on here without it being really long. Please let me know how i can assist to get this problem solved.
Thanks in advance!

code:

```<code>#import "RootViewController.h"
#import "FSDAppDelegate.h"
#import "DetailViewController.h"
@implementation RootViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize mainTableView;
@synthesize contentsList;
@synthesize descArray;
@synthesize bannerImages;
@synthesize childController;
@synthesize searchResults;
@synthesize savedSearchTerm;

#pragma mark -
#pragma mark View methods

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Descriptions" ofType:@"plist"];

    NSArray *desc = [[NSArray alloc] initWithContentsOfFile:filePath];
    self.descArray = desc;
    [desc release];

    UIImage *texas = [UIImage imageNamed:@"1andtexas.jpg"];
    UIImage *cali = [UIImage imageNamed:@"2andcalifornia.jpg"];
    UIImage *ny = [UIImage imageNamed:@"3andnewyork.jpg"];
    UIImage *tmark = [UIImage imageNamed:@"1Tmark.jpg"];
    UIImage *walkie = [UIImage imageNamed:@"Walkietalkie.jpg"];
    UIImage *onekh = [UIImage imageNamed:@"Tracingpaper.jpg"];
    UIImage *onetwonine = [UIImage imageNamed:@"diffusion.jpg"];
    UIImage *greycard = [UIImage imageNamed:@"Greycard.jpg"];
    UIImage *oneeighty = [UIImage imageNamed:@"Oneeighty.jpg"];
    UIImage *two = [UIImage imageNamed:@"Two.jpg"];
    UIImage *twofourteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twosixteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwenty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwentynine = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyone = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftytwo = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftythree = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfour = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfive = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftysix = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyseven = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyeight = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *thirtytwohk = [UIImage imageNamed:@"3200k.jpg"];

    NSArray *banners = [[NSArray alloc] initWithObjects:
                        texas,
                        cali,
                        ny,
                        tmark,
                        walkie,
                        onekh,
                        onetwonine,
                        greycard,
                        oneeighty,
                        two,
                        twofourteen,
                        twofifteen,
                        twosixteen,
                        twotwenty,
                        twotwentynine,
                        twofifty,
                        twofiftyone,
                        twofiftytwo,
                        twofiftythree,
                        twofiftyfour,
                        twofiftyfive,
                        twofiftysix,
                        twofiftyseven,
                        twofiftyeight,
                        thirtytwohk,
                        nil];

    self.bannerImages = banners;

    [banners release];

    [super viewDidLoad];

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             @"#1 or NUMBER ONE",
                             @"#2 or NUMBER TWO",
                             @"#3 or NUMBER THREE",
                             @"1 or ONE",
                             @"10-100,10-1,10-200,10-2,10-4 and 20",
                             @"1000H PAPER",
                             @"129 or HEAVY FROST",
                             @"18% GRAY or GREY CARD",
                             @"180 DEGREE RULE",
                             @"2 or TWO",
                             @"214 or FULL TOUGH SPUN",
                             @"215 or HALF TOUGH SPUN",
                             @"216 or FULL WHITE DIFFUSION",
                             @"220 or WHITE FROST",
                             @"229 or QUARTER TOUGH SPUN",
                             @"250 or HALF WHITE DIFFUSION",
                             @"251 or QUARTER WHITE DIFFUSION",
                             @"252 or EIGHTH WHITE DIFFUSION",
                             @"253 or FULL HAMPSHIRE",
                             @"254 or NEW HAMPSHIRE",
                             @"255 or HOLLYWOOD FROST",
                             @"256 or HALF HAMPSHIRE FROST",
                             @"257 or QUARTER HAMPSHIRE FROST",
                             @"258 or EIGHTH HAMPSHIRE FROST",
                             @"3200K or TUNGSTEN",
                             nil];
    [self setContentsList:array];
    [array release], array = nil;

    if ([self savedSearchTerm])
    {
        [[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark Table view datasource methods

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A'; c <= 'Z'; c++) [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger rows;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        rows = [[self searchResults] count];
    else
        rows = [[self contentsList] count];

    return [contentsList count];
    return rows;

    NSLog(@"rows is: %d", rows);
    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger row = [indexPath row];
    NSString *contentForThisRow = nil;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        contentForThisRow = [[self searchResults] objectAtIndex:row];
    else
        contentForThisRow = [[self contentsList] objectAtIndex:row];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    [[cell textLabel] setText:contentForThisRow];

    cell.textLabel.text = [contentsList objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

    return cell;
}

#pragma mark -
#pragma mark Table view delegate methods

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"Film Set Decipher";
}

-(void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    FSDAppDelegate *delegate = (FSDAppDelegate *)[[UIApplication sharedApplication] delegate];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.banner = [bannerImages objectAtIndex:indexPath.row];
    detailVC.description = [descArray objectAtIndex:indexPath.row];
    detailVC.title = [contentsList objectAtIndex:indexPath.row];
    self.childController = detailVC;
    [delegate.navigationController pushViewController:childController animated:YES];

    [detailVC release];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self handleSearchForTerm:searchString];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:nil];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    NSLog(@"Memory warning!");
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [mainTableView release]; mainTableView = nil;
    [contentsList release]; contentsList = nil;
    [descArray release]; descArray = nil;
    [bannerImages release]; bannerImages = nil;
    [childController release]; childController = nil;
    [searchResults release], searchResults = nil;
    [savedSearchTerm release], savedSearchTerm = nil;

    [super dealloc];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewDidUnload {
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    self.mainTableView = nil;
    self.contentsList = nil;
    self.descArray = nil;
    self.bannerImages = nil;
    self.childController = nil;

    [super viewDidUnload];

    [self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

    [self setSearchResults:nil];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

}

- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];

    if ([[self savedSearchTerm] length] != 0)
    {
        for (NSString *currentString in [self contentsList])
        {
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [[self searchResults] addObject:currentString];
            }
        }
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

@end
</code>```

Turns out the problem was that the images weren't all copied into the Target>Copy Bundle Resources folder, and thats what was making it crash!?!? Thanks a million!

答:
Check number of objects in these
bannerImages
descArray
contentsList

these arrays not having number of object equal to number of rows in the table view.

(You must check wher you prepare your arrays then tableview datasource and delegate methods properly).or put all code here if you not getting the solution.

Title: iphone sdk beyond bounds NSException

Body:
I am having an "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 24 beyond bounds [0 .. 23]'"
I'm not sure how to put my .m on here without it being really long. Please let me know how i can assist to get this problem solved.
Thanks in advance!

code:

#import "RootViewController.h"
#import "FSDAppDelegate.h"
#import "DetailViewController.h"
@implementation RootViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize mainTableView;
@synthesize contentsList;
@synthesize descArray;
@synthesize bannerImages;
@synthesize childController;
@synthesize searchResults;
@synthesize savedSearchTerm;

#pragma mark -
#pragma mark View methods

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Descriptions" ofType:@"plist"];

    NSArray *desc = [[NSArray alloc] initWithContentsOfFile:filePath];
    self.descArray = desc;
    [desc release];

    UIImage *texas = [UIImage imageNamed:@"1andtexas.jpg"];
    UIImage *cali = [UIImage imageNamed:@"2andcalifornia.jpg"];
    UIImage *ny = [UIImage imageNamed:@"3andnewyork.jpg"];
    UIImage *tmark = [UIImage imageNamed:@"1Tmark.jpg"];
    UIImage *walkie = [UIImage imageNamed:@"Walkietalkie.jpg"];
    UIImage *onekh = [UIImage imageNamed:@"Tracingpaper.jpg"];
    UIImage *onetwonine = [UIImage imageNamed:@"diffusion.jpg"];
    UIImage *greycard = [UIImage imageNamed:@"Greycard.jpg"];
    UIImage *oneeighty = [UIImage imageNamed:@"Oneeighty.jpg"];
    UIImage *two = [UIImage imageNamed:@"Two.jpg"];
    UIImage *twofourteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twosixteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwenty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwentynine = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyone = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftytwo = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftythree = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfour = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfive = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftysix = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyseven = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyeight = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *thirtytwohk = [UIImage imageNamed:@"3200k.jpg"];

    NSArray *banners = [[NSArray alloc] initWithObjects:
                        texas,
                        cali,
                        ny,
                        tmark,
                        walkie,
                        onekh,
                        onetwonine,
                        greycard,
                        oneeighty,
                        two,
                        twofourteen,
                        twofifteen,
                        twosixteen,
                        twotwenty,
                        twotwentynine,
                        twofifty,
                        twofiftyone,
                        twofiftytwo,
                        twofiftythree,
                        twofiftyfour,
                        twofiftyfive,
                        twofiftysix,
                        twofiftyseven,
                        twofiftyeight,
                        thirtytwohk,
                        nil];

    self.bannerImages = banners;

    [banners release];

    [super viewDidLoad];

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             @"#1 or NUMBER ONE",
                             @"#2 or NUMBER TWO",
                             @"#3 or NUMBER THREE",
                             @"1 or ONE",
                             @"10-100,10-1,10-200,10-2,10-4 and 20",
                             @"1000H PAPER",
                             @"129 or HEAVY FROST",
                             @"18% GRAY or GREY CARD",
                             @"180 DEGREE RULE",
                             @"2 or TWO",
                             @"214 or FULL TOUGH SPUN",
                             @"215 or HALF TOUGH SPUN",
                             @"216 or FULL WHITE DIFFUSION",
                             @"220 or WHITE FROST",
                             @"229 or QUARTER TOUGH SPUN",
                             @"250 or HALF WHITE DIFFUSION",
                             @"251 or QUARTER WHITE DIFFUSION",
                             @"252 or EIGHTH WHITE DIFFUSION",
                             @"253 or FULL HAMPSHIRE",
                             @"254 or NEW HAMPSHIRE",
                             @"255 or HOLLYWOOD FROST",
                             @"256 or HALF HAMPSHIRE FROST",
                             @"257 or QUARTER HAMPSHIRE FROST",
                             @"258 or EIGHTH HAMPSHIRE FROST",
                             @"3200K or TUNGSTEN",
                             nil];
    [self setContentsList:array];
    [array release], array = nil;

    if ([self savedSearchTerm])
    {
        [[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark Table view datasource methods

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A'; c <= 'Z'; c++) [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger rows;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        rows = [[self searchResults] count];
    else
        rows = [[self contentsList] count];

    return [contentsList count];
    return rows;

    NSLog(@"rows is: %d", rows);
    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger row = [indexPath row];
    NSString *contentForThisRow = nil;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        contentForThisRow = [[self searchResults] objectAtIndex:row];
    else
        contentForThisRow = [[self contentsList] objectAtIndex:row];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    [[cell textLabel] setText:contentForThisRow];

    cell.textLabel.text = [contentsList objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

    return cell;
}

#pragma mark -
#pragma mark Table view delegate methods

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"Film Set Decipher";
}

-(void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    FSDAppDelegate *delegate = (FSDAppDelegate *)[[UIApplication sharedApplication] delegate];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.banner = [bannerImages objectAtIndex:indexPath.row];
    detailVC.description = [descArray objectAtIndex:indexPath.row];
    detailVC.title = [contentsList objectAtIndex:indexPath.row];
    self.childController = detailVC;
    [delegate.navigationController pushViewController:childController animated:YES];

    [detailVC release];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self handleSearchForTerm:searchString];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:nil];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    NSLog(@"Memory warning!");
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [mainTableView release]; mainTableView = nil;
    [contentsList release]; contentsList = nil;
    [descArray release]; descArray = nil;
    [bannerImages release]; bannerImages = nil;
    [childController release]; childController = nil;
    [searchResults release], searchResults = nil;
    [savedSearchTerm release], savedSearchTerm = nil;

    [super dealloc];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewDidUnload {
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    self.mainTableView = nil;
    self.contentsList = nil;
    self.descArray = nil;
    self.bannerImages = nil;
    self.childController = nil;

    [super viewDidUnload];

    [self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

    [self setSearchResults:nil];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

}

- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];

    if ([[self savedSearchTerm] length] != 0)
    {
        for (NSString *currentString in [self contentsList])
        {
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [[self searchResults] addObject:currentString];
            }
        }
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

@end

Turns out the problem was that the images weren't all copied into the Target>Copy Bundle Resources folder, and thats what was making it crash!?!? Thanks a million!

ContentLicense: CC BY-SA 2.5


问:
Send POST request with Image from Unity3D
I'm trying to send an image to my NodeJS API from Unity but unfortunately I can't make it work. Here is an extract of my c# code:

```<code>private string POSTUrl = "http://myNodeJSAPI.com/upload-image";
private Dictionary<string, string> postHeader = new Dictionary<string, string>();

public WWW POST() {
    WWW www;
    postHeader["content-Type"] = "application/octet-stream";
    postData = File.ReadAllBytes("Assets/Resources/ImageIWantToSend.png");
    www = new WWW(POSTUrl, postData, postHeader);
    StartCoroutine(WaitForRequest(www));
    return www;
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
    }
    else
    {
        Debug.Log("WWW Error: " + www.error);
    }
}
</code>```

and here the relevant part of my nodejs one:

```<code>app.post('/upload-image', rawBody, function (req, res) {
        console.log("File received!");
        if (req.rawBody && req.bodyLength > 0) {
            fs.writeFile("/tmp/ImageIWantToSend.png", req.rawBody, function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log("Image has been saved! Starting other things...");
            })
        }
    }
</code>```

The request is sent but never received by the API (I get 503 bad gateway). I try the same request outside Unity and it seems to work (using Postman: basic post request with image attached as binary).

Did I make a mistake, or is there another way to achieve this?
Thanks!

EDIT: I finally solved the problem by changing application/octet-stream to text/html. If there is a better way to send data to Nodejs I'm still interested

答:
Check out Unity's new UnityWebRequest class.It is a replacement for original WWW.

You can also use C# WebClient or HttpWebRequest class. They work with Unity if you are not using WebGL build.

This is also a good unity plugin to handle requests, though it is not free.

Body:
I'm trying to send an image to my NodeJS API from Unity but unfortunately I can't make it work. Here is an extract of my c# code:

private string POSTUrl = "http://myNodeJSAPI.com/upload-image";
private Dictionary<string, string> postHeader = new Dictionary<string, string>();

public WWW POST() {
    WWW www;
    postHeader["content-Type"] = "application/octet-stream";
    postData = File.ReadAllBytes("Assets/Resources/ImageIWantToSend.png");
    www = new WWW(POSTUrl, postData, postHeader);
    StartCoroutine(WaitForRequest(www));
    return www;
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
    if (www.error == null)
    {
        Debug.Log("WWW Ok!: " + www.text);
    }
    else
    {
        Debug.Log("WWW Error: " + www.error);
    }
}

and here the relevant part of my nodejs one:

app.post('/upload-image', rawBody, function (req, res) {
        console.log("File received!");
        if (req.rawBody && req.bodyLength > 0) {
            fs.writeFile("/tmp/ImageIWantToSend.png", req.rawBody, function (err) {
                if (err) {
                    return console.log(err);
                }
                console.log("Image has been saved! Starting other things...");
            })
        }
    }

The request is sent but never received by the API (I get 503 bad gateway). I try the same request outside Unity and it seems to work (using Postman: basic post request with image attached as binary).

Did I make a mistake, or is there another way to achieve this?
Thanks!

EDIT: I finally solved the problem by changing application/octet-stream to text/html. If there is a better way to send data to Nodejs I'm still interested


问:
How to change the background color of UIStackView?
I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.

How can I change the background color of a UIStackView?

答:
```<code>UIStackView *stackView;
UIView *stackBkg = [[UIView alloc] initWithFrame:CGRectZero];
stackBkg.backgroundColor = [UIColor redColor];
[self.view insertSubview:stackBkg belowSubview:stackView];
stackBkg.translatesAutoresizingMaskIntoConstraints = NO;
[[stackBkg.topAnchor constraintEqualToAnchor:stackView.topAnchor] setActive:YES];
[[stackBkg.bottomAnchor constraintEqualToAnchor:stackView.bottomAnchor] setActive:YES];
[[stackBkg.leftAnchor constraintEqualToAnchor:stackView.leftAnchor] setActive:YES];
[[stackBkg.rightAnchor constraintEqualToAnchor:stackView.rightAnchor] setActive:YES];
</code>```

ContentLicense: CC BY-SA 4.0


问:
Item in RecyclerView not aligning as expected
My app has a chat activity which contains a recyclerview. This recyclerview contains two items that display the messages received by the user and the messages sent by the user.

The messages received by the user is aligning from the left of the recyclerview as expected but the messages sent by the user is not aligning from the right of the recyclerview as expected.

This is how it looks right now:
The blue colored messages are the messages received and the gray colored messages are the messages sent.

How I need the ui to look:
I want the grey colored messages to align from the right of the screen like in the picture below.

CODE

The activity.java file:

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

    private RecyclerView recyclerView;
    private ImAdapter imAdapter;
    private List<ChatMsg> chatMsgList = new ArrayList<>();
    Socket mSocket;
    EditText etIM;
    ImageButton ibSend;
    String otherUserName;
    List<Msg> msgList;
    DBAct db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_im);
        Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
        setSupportActionBar(toolbar);

        etIM = (EditText)findViewById(R.id.et_im);
        recyclerView = (RecyclerView)findViewById(R.id.rv_im);
        imAdapter = new ImAdapter(chatMsgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(imAdapter);

        db = new DBAct(IMActivity.this,otherUserName);
        msgList = db.getAllMessages();
        db.close();
        prepareChatData();
    }

    private void prepareChatData() {

        for (int i=0; i<msgList.size(); i++) {
            ChatMsg chatMsg = new ChatMsg(msgList.get(i).getMessage(),msgList.get(i).getOther());
            chatMsgList.add(chatMsg);
        }
        imAdapter.notifyDataSetChanged();
    }
}
</code>```

The adapter class file:

```<code>public class ImAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {

    private List<ChatMsg> chatMsgList = new ArrayList<ChatMsg>();
    final int VIEW_TYPE_USER = 1;
    final int VIEW_TYPE_OTHER = 0;

    public ImAdapter(List<ChatMsg> chatMsgList){
        this.chatMsgList = chatMsgList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType==VIEW_TYPE_USER){
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_user,parent,false);
            return new ImUserViewHolder(itemView);
        }else {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_other,parent,false);
            return new ImOtherViewHolder(itemView);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder.getItemViewType()==VIEW_TYPE_USER){
            ChatMsg chatMsg = chatMsgList.get(position);
            ImUserViewHolder imUserViewHolder = (ImUserViewHolder)holder;
            imUserViewHolder.msg.setText(chatMsg.getMsg());
        }else {
            ChatMsg chatMsg = chatMsgList.get(position);
            ImOtherViewHolder imOtherViewHolder = (ImOtherViewHolder) holder;
            imOtherViewHolder.msg.setText(chatMsg.getMsg());
        }
    }

    @Override
    public int getItemViewType(int position) {
        ChatMsg chatMsg = chatMsgList.get(position);
        if (chatMsg.getOther().equals("true")){
            return VIEW_TYPE_OTHER;
        }else {
            return VIEW_TYPE_USER;
        }
    }

    @Override
    public int getItemCount() {
        return chatMsgList.size();
    }

    public class ImOtherViewHolder extends RecyclerView.ViewHolder{
        public TextView msg;

        public ImOtherViewHolder(View itemView) {
            super(itemView);
            msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_other);
        }
    }

    public class ImUserViewHolder extends RecyclerView.ViewHolder{
        public TextView msg;

        public ImUserViewHolder(View itemView) {
            super(itemView);
            msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_user);
        }
    }
}
</code>```

The activity layout.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_im"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.abdralabs.talksee.IMActivity"
    android:weightSum="10">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/im_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/im_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/title">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_im"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scrollbars="vertical"
        android:layout_weight="8.7"/>

    <RelativeLayout
        android:id="@+id/rl_im"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp"
        android:orientation="vertical"
        android:layout_weight="1.3">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">

            <EditText
                android:id="@+id/et_im"
                android:layout_width="290dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Enter message..."
                android:inputType="textPersonName">
            </EditText>

            <android.support.v7.widget.AppCompatImageButton
                android:id="@+id/ib_cam_send"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@android:drawable/ic_menu_camera"
                android:layout_gravity="end|center_vertical"/>

        </FrameLayout>

        <ImageButton
            android:id="@+id/ib_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:contentDescription="send"
            app:srcCompat="@android:drawable/ic_menu_send" />

    </RelativeLayout>

</LinearLayout>
</code>```

The xml layout of the messages received (blue colored messages):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_im_chat_msg_other"
    android:paddingBottom="10dp"
    android:paddingTop="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp">

    <TextView
        android:id="@+id/tv_chat_msg_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is other"
        android:textSize="16dp"
        android:layout_alignParentTop="true"
        android:textColor="@color/black"/>

    <TextView
        android:id="@+id/tv_time_chat_msg_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00"
        android:textSize="11dp"
        android:layout_alignLeft="@+id/tv_chat_msg_other"
        android:layout_alignStart="@+id/tv_chat_msg_other"
        android:layout_below="@+id/tv_chat_msg_other"/>

</RelativeLayout>
</code>```

The xml layout of the messages sent (gray colored messages):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="10dp"
    android:background="@drawable/bg_im_chat_msg_user"
    android:gravity="right">

    <TextView
        android:id="@+id/tv_chat_msg_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is me"
        android:background="@drawable/bg_im_chat_msg_user"
        android:textColor="@color/black"
        android:textSize="16dp"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/tv_time_chat_msg_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00"
        android:textSize="11dp"
        android:layout_alignLeft="@+id/tv_chat_msg_user"
        android:layout_alignStart="@+id/tv_chat_msg_user"
        android:layout_below="@+id/tv_chat_msg_user" />

</RelativeLayout>
</code>```

I have set the relative layout's android:gravity="right" so that the gray message will be aligned to the right but apparently this isn't working. I even tried setting the android:layout_gravity="right" but the result is still the same.
Could someone please point out what I'm doing wrong?

答:
You can for example wrap your RelativeLayout in the gray colored message layout in a FrameLayout and change android:gravity="right" to android:layout_gravity="right".

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_im_chat_msg_user"
        android:layout_gravity="right"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="10dp">

        <TextView
            android:id="@+id/tv_chat_msg_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@drawable/bg_im_chat_msg_user"
            android:text="this is me"
            android:textColor="@color/black"
            android:textSize="16dp"/>

        <TextView
            android:id="@+id/tv_time_chat_msg_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/tv_chat_msg_user"
            android:layout_alignStart="@+id/tv_chat_msg_user"
            android:layout_below="@+id/tv_chat_msg_user"
            android:text="00:00"
            android:textSize="11dp"/>

    </RelativeLayout>
</FrameLayout>
</code>```

You could also warp your RelativeLayout in another RelativeLayout and change from android:gravit="right" to android:layout_alignParentRight="true".

Body:
My app has a chat activity which contains a recyclerview. This recyclerview contains two items that display the messages received by the user and the messages sent by the user.

The messages received by the user is aligning from the left of the recyclerview as expected but the messages sent by the user is not aligning from the right of the recyclerview as expected.

This is how it looks right now:
The blue colored messages are the messages received and the gray colored messages are the messages sent.

How I need the ui to look:
I want the grey colored messages to align from the right of the screen like in the picture below.

CODE

The activity.java file:

public class IMActivity extends AppCompatActivity{

    private RecyclerView recyclerView;
    private ImAdapter imAdapter;
    private List<ChatMsg> chatMsgList = new ArrayList<>();
    Socket mSocket;
    EditText etIM;
    ImageButton ibSend;
    String otherUserName;
    List<Msg> msgList;
    DBAct db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_im);
        Toolbar toolbar = (Toolbar)findViewById(R.id.imlist_toolbar);
        setSupportActionBar(toolbar);

        etIM = (EditText)findViewById(R.id.et_im);
        recyclerView = (RecyclerView)findViewById(R.id.rv_im);
        imAdapter = new ImAdapter(chatMsgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(imAdapter);

        db = new DBAct(IMActivity.this,otherUserName);
        msgList = db.getAllMessages();
        db.close();
        prepareChatData();
    }

    private void prepareChatData() {

        for (int i=0; i<msgList.size(); i++) {
            ChatMsg chatMsg = new ChatMsg(msgList.get(i).getMessage(),msgList.get(i).getOther());
            chatMsgList.add(chatMsg);
        }
        imAdapter.notifyDataSetChanged();
    }
}

The adapter class file:

public class ImAdapter extends RecyclerView.Adapter <RecyclerView.ViewHolder> {

    private List<ChatMsg> chatMsgList = new ArrayList<ChatMsg>();
    final int VIEW_TYPE_USER = 1;
    final int VIEW_TYPE_OTHER = 0;

    public ImAdapter(List<ChatMsg> chatMsgList){
        this.chatMsgList = chatMsgList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType==VIEW_TYPE_USER){
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_user,parent,false);
            return new ImUserViewHolder(itemView);
        }else {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_chat_msg_other,parent,false);
            return new ImOtherViewHolder(itemView);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder.getItemViewType()==VIEW_TYPE_USER){
            ChatMsg chatMsg = chatMsgList.get(position);
            ImUserViewHolder imUserViewHolder = (ImUserViewHolder)holder;
            imUserViewHolder.msg.setText(chatMsg.getMsg());
        }else {
            ChatMsg chatMsg = chatMsgList.get(position);
            ImOtherViewHolder imOtherViewHolder = (ImOtherViewHolder) holder;
            imOtherViewHolder.msg.setText(chatMsg.getMsg());
        }
    }

    @Override
    public int getItemViewType(int position) {
        ChatMsg chatMsg = chatMsgList.get(position);
        if (chatMsg.getOther().equals("true")){
            return VIEW_TYPE_OTHER;
        }else {
            return VIEW_TYPE_USER;
        }
    }

    @Override
    public int getItemCount() {
        return chatMsgList.size();
    }

    public class ImOtherViewHolder extends RecyclerView.ViewHolder{
        public TextView msg;

        public ImOtherViewHolder(View itemView) {
            super(itemView);
            msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_other);
        }
    }

    public class ImUserViewHolder extends RecyclerView.ViewHolder{
        public TextView msg;

        public ImUserViewHolder(View itemView) {
            super(itemView);
            msg = (TextView)itemView.findViewById(R.id.tv_chat_msg_user);
        }
    }
}

The activity layout.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_im"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.abdralabs.talksee.IMActivity"
    android:weightSum="10">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/im_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/im_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/title">

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_im"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:scrollbars="vertical"
        android:layout_weight="8.7"/>

    <RelativeLayout
        android:id="@+id/rl_im"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="12dp"
        android:orientation="vertical"
        android:layout_weight="1.3">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">

            <EditText
                android:id="@+id/et_im"
                android:layout_width="290dp"
                android:layout_height="wrap_content"
                android:ems="10"
                android:hint="Enter message..."
                android:inputType="textPersonName">
            </EditText>

            <android.support.v7.widget.AppCompatImageButton
                android:id="@+id/ib_cam_send"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@android:drawable/ic_menu_camera"
                android:layout_gravity="end|center_vertical"/>

        </FrameLayout>

        <ImageButton
            android:id="@+id/ib_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:contentDescription="send"
            app:srcCompat="@android:drawable/ic_menu_send" />

    </RelativeLayout>

</LinearLayout>

The xml layout of the messages received (blue colored messages):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_im_chat_msg_other"
    android:paddingBottom="10dp"
    android:paddingTop="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp">

    <TextView
        android:id="@+id/tv_chat_msg_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is other"
        android:textSize="16dp"
        android:layout_alignParentTop="true"
        android:textColor="@color/black"/>

    <TextView
        android:id="@+id/tv_time_chat_msg_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00"
        android:textSize="11dp"
        android:layout_alignLeft="@+id/tv_chat_msg_other"
        android:layout_alignStart="@+id/tv_chat_msg_other"
        android:layout_below="@+id/tv_chat_msg_other"/>

</RelativeLayout>

The xml layout of the messages sent (gray colored messages):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingBottom="10dp"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="10dp"
    android:background="@drawable/bg_im_chat_msg_user"
    android:gravity="right">

    <TextView
        android:id="@+id/tv_chat_msg_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="this is me"
        android:background="@drawable/bg_im_chat_msg_user"
        android:textColor="@color/black"
        android:textSize="16dp"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/tv_time_chat_msg_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00"
        android:textSize="11dp"
        android:layout_alignLeft="@+id/tv_chat_msg_user"
        android:layout_alignStart="@+id/tv_chat_msg_user"
        android:layout_below="@+id/tv_chat_msg_user" />

</RelativeLayout>

I have set the relative layout's android:gravity="right" so that the gray message will be aligned to the right but apparently this isn't working. I even tried setting the android:layout_gravity="right" but the result is still the same.
Could someone please point out what I'm doing wrong?

Body:
You can for example wrap your RelativeLayout in the gray colored message layout in a FrameLayout and change android:gravity="right" to android:layout_gravity="right".

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_im_chat_msg_user"
        android:layout_gravity="right"
        android:paddingBottom="10dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingTop="10dp">

        <TextView
            android:id="@+id/tv_chat_msg_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="@drawable/bg_im_chat_msg_user"
            android:text="this is me"
            android:textColor="@color/black"
            android:textSize="16dp"/>

        <TextView
            android:id="@+id/tv_time_chat_msg_user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/tv_chat_msg_user"
            android:layout_alignStart="@+id/tv_chat_msg_user"
            android:layout_below="@+id/tv_chat_msg_user"
            android:text="00:00"
            android:textSize="11dp"/>

    </RelativeLayout>
</FrameLayout>

You could also warp your RelativeLayout in another RelativeLayout and change from android:gravit="right" to android:layout_alignParentRight="true".


问:
How to compare enum and int values?
```<code>enum MyEnum
{
    Invalid=0,
    Value1=1,
    Value1=2,
}

void main ()
{
    MyEnum e1 = MyEnum.Value1;
    int i1 = 2;

    // Is there any difference how to compare enumEration values with integers?
    if ( e1==(MyEnum)i1 )... // 1st

    if ( (int)e1==i1 )... // 2nd
</code>```

In each of mentioned cases we have convertion of enum to int or int to enum.

Is there any difference in these conversions (performance, any other)? Or they are exactly the same?

Thanks.

P.S. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.

答:
They are exactly the same. Displaying the generated IL using the Debug, Windows, Disassembly (Ctrl-Alt-D) gives you:</p>

```<code>MyEnum e1 = MyEnum.Value1;
00260834  mov         dword ptr [ebp-3Ch],1
int i1 = 2;
0026083B  mov         dword ptr [ebp-40h],2

// Is there any difference how to compare enumEration values with integers?
if (e1 == (MyEnum) i1)
00260842  mov         eax,dword ptr [ebp-3Ch]
00260845  cmp         eax,dword ptr [ebp-40h]
00260848  sete        al
0026084B  movzx       eax,al
0026084E  mov         dword ptr [ebp-44h],eax
00260851  cmp         dword ptr [ebp-44h],0
00260855  je          00260858
; // 1st
00260857  nop

if ((int)e1 == i1)
00260858  mov         eax,dword ptr [ebp-3Ch]
0026085B  cmp         eax,dword ptr [ebp-40h]
0026085E  sete        al
00260861  movzx       eax,al
00260864  mov         dword ptr [ebp-48h],eax
00260867  cmp         dword ptr [ebp-48h],0
0026086B  je          0026086E
; // 2nd
0026086D  nop
</code>```

Title: How to compare enum and int values?

Body:
enum MyEnum
{
    Invalid=0,
    Value1=1,
    Value1=2,
}

void main ()
{
    MyEnum e1 = MyEnum.Value1;
    int i1 = 2;

    // Is there any difference how to compare enumEration values with integers?
    if ( e1==(MyEnum)i1 )... // 1st

    if ( (int)e1==i1 )... // 2nd

In each of mentioned cases we have convertion of enum to int or int to enum.

Is there any difference in these conversions (performance, any other)? Or they are exactly the same?

Thanks.

P.S. In current example I compare to 'magic number' but in real application I am getting data from integer field from DB.

Body:
They are exactly the same. Displaying the generated IL using the Debug, Windows, Disassembly (Ctrl-Alt-D) gives you:

MyEnum e1 = MyEnum.Value1;
00260834  mov         dword ptr [ebp-3Ch],1
int i1 = 2;
0026083B  mov         dword ptr [ebp-40h],2

// Is there any difference how to compare enumEration values with integers?
if (e1 == (MyEnum) i1)
00260842  mov         eax,dword ptr [ebp-3Ch]
00260845  cmp         eax,dword ptr [ebp-40h]
00260848  sete        al
0026084B  movzx       eax,al
0026084E  mov         dword ptr [ebp-44h],eax
00260851  cmp         dword ptr [ebp-44h],0
00260855  je          00260858
; // 1st
00260857  nop

if ((int)e1 == i1)
00260858  mov         eax,dword ptr [ebp-3Ch]
0026085B  cmp         eax,dword ptr [ebp-40h]
0026085E  sete        al
00260861  movzx       eax,al
00260864  mov         dword ptr [ebp-48h],eax
00260867  cmp         dword ptr [ebp-48h],0
0026086B  je          0026086E
; // 2nd
0026086D  nop


问:
How to run python script as a web service with user provided image?
I have a Python(2.7) script which detects faces in an image which works fine.

```<code>from PIL import Image
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg")

# Find all the faces in the image
face_locations = face_recognition.face_locations(image)

# a = print("Found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:

    # Print the location of each face in this image
  top, right, bottom, left = face_location
  print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    # You can access the actual face itself like this:
  face_image = image[top:bottom, left:right]
  pil_image = Image.fromarray(face_image)
  pil_image.show()
</code>```

Now, I want to make it as a http://localhost:8080/detect so that user can provide an image and clicking on Submit button will display the output. I think there are few ways to do this, either using Flask, Django or Web server. But not sure which is the simplest way to do this and how to go about it. How to take this code and convert into a webservice? What code changes are required? Any code sample will be of great help.

答:
I believe you're asking what a good web framework for python is. Before I was competent, I wrote a Django web server and I found it a bit daunting. But then everything was daunting at that point. I've used Flask in few projects since becoming an OK programmer. It's fairly straight forward, easy to setup, and well documented, as is Django. I used this tutorial when I was learning Flask. As I understand it, this is really an opinion question, so IMHO I would go with Flask, uWSGI, and Nginx as is in the tutorial. Though, I would encourage you to do your own research and see if the other options suit you and your project better.

EDIT: To use this code Flask you either place your code directly in a route's function or even better put it into a function or class and import it. EVEN BETTER create a model, view, and controller(MVC). From a cursory glance, it looks like you'll have to upload the file and save it, and then open it with face_recognition. The face_recognition module doesn't seem to be able to read data from memory, so saving the file and opening it with face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg") seems to be necessary. Just to be sure to delete the file after you load it to clear space. Then once you have your PIL.Image object, you would return that from your code and then send it with the flask.send_file function as demonstrated here. Lots of links and no code, but these links along with the tutorial I linked to initially should get you where you need to go.

Note: In case it wasn't clear, your code should return Image.fromarray(face_image) and not use the show function.

Body:
I have a Python(2.7) script which detects faces in an image which works fine.

from PIL import Image
import face_recognition

# Load the jpg file into a numpy array
image = face_recognition.load_image_file("/PATH_TO_IMAGE/IMAGE.jpg")

# Find all the faces in the image
face_locations = face_recognition.face_locations(image)

# a = print("Found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:

    # Print the location of each face in this image
  top, right, bottom, left = face_location
  print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))

    # You can access the actual face itself like this:
  face_image = image[top:bottom, left:right]
  pil_image = Image.fromarray(face_image)
  pil_image.show()

Now, I want to make it as a http://localhost:8080/detect so that user can provide an image and clicking on Submit button will display the output. I think there are few ways to do this, either using Flask, Django or Web server. But not sure which is the simplest way to do this and how to go about it. How to take this code and convert into a webservice? What code changes are required? Any code sample will be of great help.


问:
Java parsing json array, Error parsing data org.json.JSONException
This is my code, in my log, i'm getting:

E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject

I really need a solution i have been searching for weeks now.

```<code>    @Override
    protected String doInBackground(String... para) {

        List<NameValuePair> params=new ArrayList<NameValuePair>();
        JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);

        try {
            success=json.getInt("success");
            if(success==1){

                drivers=new ArrayList<Driver>();

                JSONArray sounds=json.getJSONArray("location");
                for (int i = 0; i < sounds.length(); i++) {
                    JSONObject jobj=sounds.getJSONObject(i);
                    Driver d=new Driver();
                    d.setId(jobj.getString("id"));
                    d.setName(jobj.getString("name"));
                    d.setEmail(jobj.getString("email"));
                    d.setNumber(jobj.getString("number"));
                    d.setLatitude(jobj.getString("latitude"));
                    d.setLongitude(jobj.getString("longitude"));
                    d.setInfo(jobj.getString("info"));
                    d.setCost(jobj.getString("cost"));
                    drivers.add(d);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
            error=1;
        }catch (Exception e) {
            error=1;
        }
        return null;
    }
</code>```

And this is the JSONParser class

JSONParser.java

```<code>public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method.equals("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}
</code>```

 PHP File

```<code><?php
header('Content-Type: application/json');

$response = array();

// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();

$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));

if (mysqli_num_rows($result)>0) {
    $response["location"] = array();
        while ($row=mysqli_fetch_array($result)) {
            $files=array();
            $files["id"]=$row["id"];
            $files["name"]=$row["name"];
            $files["email"]=$row["email"];
            $files["number"]=$row["number"];
            $files["latitude"]=$row["latitude"];
            $files["longitude"]=$row["longitude"];
            $files["info"]=$row["vehicleinfo"];
            $files["cost"]=$row["costpkm"];

            array_push($response["location"], $files);

    }

    $response["success"]=1;
    echo json_encode($response);
} else {
    $response["success"]=0;
    $response["message"]="No Taxi found";

    echo json_encode($response);
}
?>
</code>```

答:
Solved

the error was due to incorrect url, the xampp apache server was returning an object not found page..error 404, which is an xml file. That's why the return result for makeHttpRequest is an xml object instead of json formated string.

Body:
This is my code, in my log, i'm getting:

E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject

I really need a solution i have been searching for weeks now.

    @Override
    protected String doInBackground(String... para) {

        List<NameValuePair> params=new ArrayList<NameValuePair>();
        JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);

        try {
            success=json.getInt("success");
            if(success==1){

                drivers=new ArrayList<Driver>();

                JSONArray sounds=json.getJSONArray("location");
                for (int i = 0; i < sounds.length(); i++) {
                    JSONObject jobj=sounds.getJSONObject(i);
                    Driver d=new Driver();
                    d.setId(jobj.getString("id"));
                    d.setName(jobj.getString("name"));
                    d.setEmail(jobj.getString("email"));
                    d.setNumber(jobj.getString("number"));
                    d.setLatitude(jobj.getString("latitude"));
                    d.setLongitude(jobj.getString("longitude"));
                    d.setInfo(jobj.getString("info"));
                    d.setCost(jobj.getString("cost"));
                    drivers.add(d);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
            error=1;
        }catch (Exception e) {
            error=1;
        }
        return null;
    }

And this is the JSONParser class

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {
            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method.equals("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

 PHP File

<?php
header('Content-Type: application/json');

$response = array();

// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();

$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));

if (mysqli_num_rows($result)>0) {
    $response["location"] = array();
        while ($row=mysqli_fetch_array($result)) {
            $files=array();
            $files["id"]=$row["id"];
            $files["name"]=$row["name"];
            $files["email"]=$row["email"];
            $files["number"]=$row["number"];
            $files["latitude"]=$row["latitude"];
            $files["longitude"]=$row["longitude"];
            $files["info"]=$row["vehicleinfo"];
            $files["cost"]=$row["costpkm"];

            array_push($response["location"], $files);

    }

    $response["success"]=1;
    echo json_encode($response);
} else {
    $response["success"]=0;
    $response["message"]="No Taxi found";

    echo json_encode($response);
}
?>


问:
How to get total number of commits using GitHub API
I am trying to collect some statistics about our project repositories on GitHub. I am able to get total number of commits for each contributor , but it is for default branch.

curl https://api.github.com/repos/cms-sw/cmssw/stats/contributors

The problem is , how can i get the same info for non-default branches , where i can specify a branch name. Is any such operation possible using GitHub API ?

thanks.

答:
You should be able to use GitHub's GraphQL API to get at this data, although it won't be aggregated for you.

Try the following query in their GraphQL Explorer:

```<code>query($owner:String!, $name:String!) {
  repository(owner:$owner,name:$name) {
    refs(first:30, refPrefix:"refs/heads/") {
      edges {
        cursor
        node {
          name
          target {
            ... on Commit {
              history(first:30) {
                edges {
                  cursor
                  node {
                    author {
                      email
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

With these variables:

```<code>{
  "owner": "rails",
  "name": "rails"
}
</code>```

That will list out each of the author emails for each of the commits of each of the branches in a given repository. It would be up to you to paginate over the data (adding something like cursor: "b7aa251234357f7ddddccabcbce332af39dd95f6" after the first:30 arguments). You'd also have to aggregate the counts on your end.

Hope this helps.

Body:
You should be able to use GitHub's GraphQL API to get at this data, although it won't be aggregated for you.

Try the following query in their GraphQL Explorer:

query($owner:String!, $name:String!) {
  repository(owner:$owner,name:$name) {
    refs(first:30, refPrefix:"refs/heads/") {
      edges {
        cursor
        node {
          name
          target {
            ... on Commit {
              history(first:30) {
                edges {
                  cursor
                  node {
                    author {
                      email
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

With these variables:

{
  "owner": "rails",
  "name": "rails"
}

That will list out each of the author emails for each of the commits of each of the branches in a given repository. It would be up to you to paginate over the data (adding something like cursor: "b7aa251234357f7ddddccabcbce332af39dd95f6" after the first:30 arguments). You'd also have to aggregate the counts on your end.

Hope this helps.


问:
Get hex in fixed position from file in vbscript
So I have multiple files that in hex editor looks like below:

```<code>      Offset(h) 00 01 02 03 04 05

      1o        10 20 02 00 0A 05 (...)

      2o        10 20 53 00 0A 03 (...)

      3o        10 20 22 00 0A 55 (...)

      4o        10 20 12 00 0A 22 (...)
</code>```

How do I get the 0A value and store into a variable, knowing that is a fixed position? (always 5th byte)

I need to get the 0A value so I compare to other value and make a decision.

I need to do this in VBscript.

Thanks in advance and appreciate any help

答:
There are other questions/answers on SO regarding reading binary files in VBSCript, perhaps they will help you.

What's important to remember is that a binary file (as is any file) is a continuous stream of bytes. So rather than thinking about the "5th byte" of each line remember it will be the 5th, 10th, 15th etc. byte you are interested in.

This is why your hex viewer has an "Offset" column to show how far through the stream of bytes you are.

Body:
So I have multiple files that in hex editor looks like below:

      Offset(h) 00 01 02 03 04 05

      1o        10 20 02 00 0A 05 (...)

      2o        10 20 53 00 0A 03 (...)

      3o        10 20 22 00 0A 55 (...)

      4o        10 20 12 00 0A 22 (...)

How do I get the 0A value and store into a variable, knowing that is a fixed position? (always 5th byte)

I need to get the 0A value so I compare to other value and make a decision.

I need to do this in VBscript.

Thanks in advance and appreciate any help