问:
msg: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV4Handler'] Check your credentials
So I am trying to run ansible on my ec2 instances on aws, for the first time on a fresh instance, but every time I try to run a play I can't get around this error message:

```<code>PLAY [localhost]
**************************************************************

TASK: [make one instance]
*****************************************************
failed: [localhost] => {"failed": true} msg: No handler was ready to
authenticate. 1 handlers were checked. ['HmacAuthV4Handler'] Check
your credentials

FATAL: all hosts have already failed -- aborting

PLAY RECAP
********************************************************************
   to retry, use: --limit @/home/ubuntu/ans_test.retry

localhost                  : ok=0    changed=0    unreachable=0
failed=1
</code>```

I think there may be something wrong with the permissions in my IAM user and group.  I have given my IAM user and group ReadOnlyAccess, AdministratorAccess and PowerUserAccess. I have an access id and secret access key that I am setting as environmental variable with the commands:

```<code>   export AWS_ACCESS_KEY_ID='AK123'
   export AWS_SECRET_ACCESS_KEY='abc123'
</code>```

With 'AK123'and 'abc123' replaced with my actual id and key values.  What else do I need to do in order to get the ansible ec2 task working?

UPDATE:

I fixed the problem, I guess I didn't really have a solid understanding of what environmental variables are. I fixed it by just setting my aws_access_key and aws_secret_key inside of my ec2 task, below is my working playbook

```<code>- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
    #this task creates 5 ec2 instances that are all named demo and are copies of the image specified
    - name: Provision a set of instances
      ec2:
         aws_access_key: .....
         aws_secret_key: ....
         key_name: .....
         group: .....
         instance_type: t2.micro
         image: ......
         region: us-east-1
         ec2_url: .......
         wait: true
         exact_count: 5
         count_tag:
            Name: Demo
         instance_tags:
            Name: Demo
      register: ec2
</code>```

I guess now I need to start using ansible vault to just hold my key and ID.

答:
In my case the variables must have been in quotes (single or double it does not matter).

BAD:

```<code>export AWS_ACCESS_KEY_ID=AK123
export AWS_SECRET_ACCESS_KEY=abc123
</code>```

GOOD:

```<code>export AWS_ACCESS_KEY_ID='AK123'
export AWS_SECRET_ACCESS_KEY='abc123'
</code>```

GOOD:

```<code>export AWS_ACCESS_KEY_ID="AK123"
export AWS_SECRET_ACCESS_KEY="abc123"
</code>```

Body:
So I am trying to run ansible on my ec2 instances on aws, for the first time on a fresh instance, but every time I try to run a play I can't get around this error message:

PLAY [localhost]
**************************************************************

TASK: [make one instance]
*****************************************************
failed: [localhost] => {"failed": true} msg: No handler was ready to
authenticate. 1 handlers were checked. ['HmacAuthV4Handler'] Check
your credentials

FATAL: all hosts have already failed -- aborting

PLAY RECAP
********************************************************************
   to retry, use: --limit @/home/ubuntu/ans_test.retry

localhost                  : ok=0    changed=0    unreachable=0
failed=1

I think there may be something wrong with the permissions in my IAM user and group.  I have given my IAM user and group ReadOnlyAccess, AdministratorAccess and PowerUserAccess. I have an access id and secret access key that I am setting as environmental variable with the commands:

   export AWS_ACCESS_KEY_ID='AK123'
   export AWS_SECRET_ACCESS_KEY='abc123'

With 'AK123'and 'abc123' replaced with my actual id and key values.  What else do I need to do in order to get the ansible ec2 task working?

UPDATE:

I fixed the problem, I guess I didn't really have a solid understanding of what environmental variables are. I fixed it by just setting my aws_access_key and aws_secret_key inside of my ec2 task, below is my working playbook

- hosts: localhost
  connection: local
  gather_facts: False

  tasks:
    #this task creates 5 ec2 instances that are all named demo and are copies of the image specified
    - name: Provision a set of instances
      ec2:
         aws_access_key: .....
         aws_secret_key: ....
         key_name: .....
         group: .....
         instance_type: t2.micro
         image: ......
         region: us-east-1
         ec2_url: .......
         wait: true
         exact_count: 5
         count_tag:
            Name: Demo
         instance_tags:
            Name: Demo
      register: ec2

I guess now I need to start using ansible vault to just hold my key and ID.

Body:
In my case the variables must have been in quotes (single or double it does not matter).

BAD:

export AWS_ACCESS_KEY_ID=AK123
export AWS_SECRET_ACCESS_KEY=abc123

GOOD:

export AWS_ACCESS_KEY_ID='AK123'
export AWS_SECRET_ACCESS_KEY='abc123'

GOOD:

export AWS_ACCESS_KEY_ID="AK123"
export AWS_SECRET_ACCESS_KEY="abc123"


来源: stackexchange

问:
|= operator cannot be applied to two NSWindowMask operations
In swift 4 this fails

```<code>self.window.styleMask |= NSWindowStyleMask.fullSizeContentView
</code>```

and I'd also like to undo

```<code>self.window.styleMask ^= NSWindowStyleMask.fullSizeContentView
</code>```

as I would in objective-c

答:
In Swift, NSWindowStyleMask (in Swift 4, NSWindow.StyleMask) is OptionSet. You need to use methods defined for SetAlgebra.

Swift 4:

```<code>self.window!.styleMask.formUnion(NSWindow.StyleMask.fullSizeContentView)

self.window!.styleMask.formSymmetricDifference(NSWindow.StyleMask.fullSizeContentView)
</code>```

The code below compiles both in Swift 3 & Swift 4:

```<code>self.window!.styleMask.formUnion(.fullSizeContentView)

self.window!.styleMask.formSymmetricDifference(.fullSizeContentView)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In swift 4 this fails

self.window.styleMask |= NSWindowStyleMask.fullSizeContentView

and I'd also like to undo

self.window.styleMask ^= NSWindowStyleMask.fullSizeContentView

as I would in objective-c

Body:
In Swift, NSWindowStyleMask (in Swift 4, NSWindow.StyleMask) is OptionSet. You need to use methods defined for SetAlgebra.

Swift 4:

self.window!.styleMask.formUnion(NSWindow.StyleMask.fullSizeContentView)

self.window!.styleMask.formSymmetricDifference(NSWindow.StyleMask.fullSizeContentView)

The code below compiles both in Swift 3 & Swift 4:

self.window!.styleMask.formUnion(.fullSizeContentView)

self.window!.styleMask.formSymmetricDifference(.fullSizeContentView)


问:
What consumes memory in linux
I use atop cmd to check memory usage.
on the screenshot use can I see I have 1gb total, and 300mb free.
how do I found out what consumes other ~700mb?
I tried to use atop cmd, but that doesn't give me much information.

答:
a memory leak occurs when a process doesn't give memory back that it doesn't need anymore
so first run top and type > key to sort by memory utilization or virtual memory utilization
you should review how much swap you are using in /proc/meminfo then check the inactive(anon) if it has high value that is bigger than the swap memory then make your swap is greater than it
finally, run free -m to see the memory details
if you find cache is high run the following command

echo 3 > /proc/sys/vm/drop_caches; sync

then run free -m again to see the changes

Title: What consumes memory in linux


答:
This is ugly

```<code>self.window.styleMask = NSWindowStyleMask(rawValue: NSWindowStyleMask.fullSizeContentView.rawValue + panel.styleMask.rawValue)
</code>```

seems to work?  The net affect is the content shrinks (by title height) when it's toggled.  So I might to back to what I had been using - .borderless

Title: |= operator cannot be applied to two NSWindowMask operations

Body:
This is ugly

self.window.styleMask = NSWindowStyleMask(rawValue: NSWindowStyleMask.fullSizeContentView.rawValue + panel.styleMask.rawValue)

seems to work?  The net affect is the content shrinks (by title height) when it's toggled.  So I might to back to what I had been using - .borderless


问:
Moving a single float to a xmm register
I want to multiply the data stored in one xmm register with a single float value and save the result in a xmm register.
I made a little graphic to explain it a bit better.

As you see I got a xmm0 register with my data in it. For example it contains:

xmm0 = |4.0|2.5|3.5|2.0|

Each floating point is stored in 4 bytes. My xmm0 register is 128 bits, 16 bytes long.

That works pretty good. Now I want to store 0.5 in another xmm register, e.g. xmm1, and multiply this register with the xmm0 register so that each value stored in xmm0 is multiplied with 0.5.

I have absolutely no idea how to store 0.5 in an XMM register.
Any suggestions?

Btw: It's Inline Assembler in C++.

```<code>void filter(image* src_image, image* dst_image)
{
    float* src = src_image->data;
    float* dst = dst_image->data;

    __asm__ __volatile__ (
        "movaps (%%esi), %%xmm0\n"
        // Multiply %xmm0 with a float, e.g. 0.5
        "movaps %%xmm0, (%%edi)\n"

        :
        : "S"(src), "D"(dst) :
    );
}
</code>```

This is the quiet simple version of the thing i want to do. I got some image data stored in a float array. The pointer to these arrays are passed to assembly. movaps takes the first 4 float values of the array, stores these 16 bytes in the xmm0 register. After this xmm0 should be multiplied with e.g. 0.5. Than the "new" values shall be stored in the array from edi.

答:
Here's one way to do it:</p>

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct img {
    float *data;
} image_t;

image_t *src_image;
image_t *dst_image;
void filter(image_t*, image_t*);

int main()
{
    image_t src, dst;
    src.data = malloc(64);
    dst.data = malloc(64);
    src_image=&src;
    dst_image=&dst;

    *src.data = 42.0;
    filter(src_image, dst_image);

    printf("%f\n", *dst.data);
    free(src.data);
    free(dst.data);
    return 0;
}

void filter(image_t* src_image, image_t* dst_image)
{
    float* src = src_image->data;
    float* dst = dst_image->data;

    __asm__ __volatile__ (
        "movd   %%esi, %%xmm0;"
        "movd   %%xmm0, %%edi;"
        : "=D" (*dst)
        : "S" (*src)
    );
}
</code>```

Title: Moving a single float to a xmm register

Body:
I want to multiply the data stored in one xmm register with a single float value and save the result in a xmm register.
I made a little graphic to explain it a bit better.

As you see I got a xmm0 register with my data in it. For example it contains:

xmm0 = |4.0|2.5|3.5|2.0|

Each floating point is stored in 4 bytes. My xmm0 register is 128 bits, 16 bytes long.

That works pretty good. Now I want to store 0.5 in another xmm register, e.g. xmm1, and multiply this register with the xmm0 register so that each value stored in xmm0 is multiplied with 0.5.

I have absolutely no idea how to store 0.5 in an XMM register.
Any suggestions?

Btw: It's Inline Assembler in C++.

void filter(image* src_image, image* dst_image)
{
    float* src = src_image->data;
    float* dst = dst_image->data;

    __asm__ __volatile__ (
        "movaps (%%esi), %%xmm0\n"
        // Multiply %xmm0 with a float, e.g. 0.5
        "movaps %%xmm0, (%%edi)\n"

        :
        : "S"(src), "D"(dst) :
    );
}

This is the quiet simple version of the thing i want to do. I got some image data stored in a float array. The pointer to these arrays are passed to assembly. movaps takes the first 4 float values of the array, stores these 16 bytes in the xmm0 register. After this xmm0 should be multiplied with e.g. 0.5. Than the "new" values shall be stored in the array from edi.

Body:
Here's one way to do it:

#include <stdio.h>
#include <stdlib.h>

typedef struct img {
    float *data;
} image_t;

image_t *src_image;
image_t *dst_image;
void filter(image_t*, image_t*);

int main()
{
    image_t src, dst;
    src.data = malloc(64);
    dst.data = malloc(64);
    src_image=&src;
    dst_image=&dst;

    *src.data = 42.0;
    filter(src_image, dst_image);

    printf("%f\n", *dst.data);
    free(src.data);
    free(dst.data);
    return 0;
}

void filter(image_t* src_image, image_t* dst_image)
{
    float* src = src_image->data;
    float* dst = dst_image->data;

    __asm__ __volatile__ (
        "movd   %%esi, %%xmm0;"
        "movd   %%xmm0, %%edi;"
        : "=D" (*dst)
        : "S" (*src)
    );
}


问:
Mysql sum all columns starting with some letters
I am trying add one column in my Mysql database that sums all the columns starting by 'tokenvalid' which can take the value of 1 or 0.

And let's say I have 50 columns like that in my database (i.e. tokenvalid1, tokenvalid2 ...., tokenvalide50) with other columns between.

Please find below the code I would like to implement. I know that is not correct at all but it is just to give you an idea of what I am trying to do.
Thank you for your help!

```<code>'SELECT *, sum(column_name LIKE "tokenvalid"%) as total FROM points WHERE 1'
</code>```

答:
Something like this should help you.

```<code>SET @colname = (SELECT GROUP_CONCAT(`column_name`) from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='points' AND `column_name` LIKE 'tokenvalid%');
SET @table = 'points';
SET @query = CONCAT('SELECT SUM(',@colname,') FROM ', @table);
PREPARE stmt FROM @query;
EXECUTE stmt;
</code>```

Similar to this answer by RocketDonkey

Body:
I am trying add one column in my Mysql database that sums all the columns starting by 'tokenvalid' which can take the value of 1 or 0.

And let's say I have 50 columns like that in my database (i.e. tokenvalid1, tokenvalid2 ...., tokenvalide50) with other columns between.

Please find below the code I would like to implement. I know that is not correct at all but it is just to give you an idea of what I am trying to do.
Thank you for your help!

'SELECT *, sum(column_name LIKE "tokenvalid"%) as total FROM points WHERE 1'

Body:
Something like this should help you.

SET @colname = (SELECT GROUP_CONCAT(`column_name`) from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='points' AND `column_name` LIKE 'tokenvalid%');
SET @table = 'points';
SET @query = CONCAT('SELECT SUM(',@colname,') FROM ', @table);
PREPARE stmt FROM @query;
EXECUTE stmt;

Similar to this answer by RocketDonkey


问:
How to track Multiple Purchase on a thank you page with Fackbook pixel
Ok so I'm programmatically generating the purchase pixel on my site on the thank you page and I can't find any docs as to if the following works:

```<code><!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version="2.0";n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,"script","https://connect.facebook.net/en_US/fbevents.js");
fbq("init", "##ID##"); // Insert your pixel ID here.
fbq("track", "PageView");
    fbq("track", "Purchase", {value: ##price##, currency: "USD"});
    fbq("track", "Purchase", {value: ##price##, currency: "USD"});
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=##ID##&ev=PageView&noscript=1"
/></noscript>
<!-- DO NOT MODIFY -->
<!-- End Facebook Pixel Code -->
</code>```

Will that generate 2 conversion events in the facebook system, or throw a misconfigured pixel?  Read all through their documentation and can't find anywhere if this will work or not.

答: I believe that would throw an error. Are you trying to measure multiple orders or multiple products in a singular order? </p>

Body:
Ok so I'm programmatically generating the purchase pixel on my site on the thank you page and I can't find any docs as to if the following works:

Will that generate 2 conversion events in the facebook system, or throw a misconfigured pixel?  Read all through their documentation and can't find anywhere if this will work or not.


问:
undefined reference to `forkpty'
So I'm developing my project in Eclipse in Ubuntu 10.04. I have the following lines of code:

```<code>#include <pty.h>

pid_t pid;
int master;

pid = forkpty(&master, NULL, NULL, NULL);
</code>```

But when I try to build it within Eclipse, I get the error:

```<code>undefined reference to 'forkpty'
</code>```

Any idea how to solve this problem?

答:
You need -lutil command line argument (to use libutil shared library).

For Eclipse:
http://zetcode.com/articles/eclipsecdevelopment/

Select Project Properties. Expand the C/C++ Build tab. Select settings. From the Tool Settings tab, expand the GCC C Linker option. Click on libraries. Add the /usr/lib/libutil.so  to the Libraries window. Notice, that this path may be different on your system.

ContentLicense: CC BY-SA 2.5

Title: undefined reference to `forkpty'

Body:
So I'm developing my project in Eclipse in Ubuntu 10.04. I have the following lines of code:

#include <pty.h>

pid_t pid;
int master;

pid = forkpty(&master, NULL, NULL, NULL);

But when I try to build it within Eclipse, I get the error:

undefined reference to 'forkpty'

Any idea how to solve this problem?


问:
How to use material icon in angular 2?
I am trying to use below code. But home icon is not getting displayed.</p>

```<code>       <button md-button routerLink="/">
            <md-icon>home</md-icon>
        </button>
</code>```

答:
Add the angular material icon link in index.html

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

Title: How to use material icon in angular 2?

Body:
I am trying to use below code. But home icon is not getting displayed.

       <button md-button routerLink="/">
            <md-icon>home</md-icon>
        </button>

Body:
Add the angular material icon link in index.html

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">


问:
Is it possible to load content and variables via xmlhttprequest?
is it possible to load content AND variables from a *.php-File with xmlhttprequest?

I have a index.php:

```<code><script>
function loadsite() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("divrequest").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "siterequest.php", true);
    xhttp.send();
}
$(document).ready(loadsite());

</script>

<div id="divrequest"></div>
</code>```

My siterequest.php:

```<code><?php
    echo "some dynamic content";
    echo json_encode(array($var1,$var2,$var3));
    echo "more dynamic content";
?>
</code>```

Am I able to get the variables? Or did I misunderstand the function of XMLHttpRequest?

EDIT:
If I use

```<code>var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);
</code>```

I will get the code of the whole page.

答: XMLHttpRequest sends an HTTP-request to the server to access the desired page. PHP is executed before the response data is sent back to you, in which case it's translated to HTML. Therefore, you can't get the variables using this approach with JavaScript. That happens before you even receive the data.

Body:
is it possible to load content AND variables from a *.php-File with xmlhttprequest?

I have a index.php:

My siterequest.php:

<?php
    echo "some dynamic content";
    echo json_encode(array($var1,$var2,$var3));
    echo "more dynamic content";
?>

Am I able to get the variables? Or did I misunderstand the function of XMLHttpRequest?

EDIT:
If I use

var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);

I will get the code of the whole page.


问:
How to send formatted Rich Text Box as mail signature to some one in c# winform
I have created an email signature using Rich Text Box. I want to sent this to my client through smtp protocol. I know the code to send smtp mail, but how to send this formatted text to the client as mail body?

Thanks in advance.

答:
In order for the body to be formatted like your richtextbox text is formatted, you must write some logic in order to convert the text into html.
 when i say logic i mean that you must locate new lines, bold text, text color etc.. inside your richtextbox and convert it to html.

for example lets say that is the text inside your textbox:

Hello
 I AM ROBOT

you must write the logic in order to convert it to that string:

```<code><span> Hello <br/> I AM <b>ROBOT</b></span>
</code>```

after the text is embedded as html pass it to the .Body property of MailMessage class, also .IsBodyHtml property must be set to TRUE.

here is a a recommended tool for that task: Writing Your Own RTF Converter if you dont want to do it by yourself.

Body:
In order for the body to be formatted like your richtextbox text is formatted, you must write some logic in order to convert the text into html.
 when i say logic i mean that you must locate new lines, bold text, text color etc.. inside your richtextbox and convert it to html.

for example lets say that is the text inside your textbox:

Hello
 I AM ROBOT

you must write the logic in order to convert it to that string:

<span> Hello <br/> I AM <b>ROBOT</b></span>

after the text is embedded as html pass it to the .Body property of MailMessage class, also .IsBodyHtml property must be set to TRUE.

here is a a recommended tool for that task: Writing Your Own RTF Converter if you dont want to do it by yourself.


问:
How do you log an int on Android?
I'm logging this:

```<code>Log.d(getClass().getName(), "BLA BLA BLA");
</code>```

How can I show an int value? What is the equivalent of C's %d?

答:
```<code>String.valueOf()
</code>```

is what you need if you want string representations of various objects.

And by the way, I'd recommend using slf4j for Android. This way, you don't have to pass class name as the first parameter every single time.

ContentLicense: CC BY-SA 4.0

Title: How do you log an int on Android?

Body:
I'm logging this:

Log.d(getClass().getName(), "BLA BLA BLA");

How can I show an int value? What is the equivalent of C's %d?

Body:
String.valueOf()

is what you need if you want string representations of various objects.

And by the way, I'd recommend using slf4j for Android. This way, you don't have to pass class name as the first parameter every single time.


问:
Splitting List into sublists along elements
I have this list (List<String>):

```<code>["a", "b", null, "c", null, "d", "e"]
</code>```

And I'd like something like this:

```<code>[["a", "b"], ["c"], ["d", "e"]]
</code>```

In other words I want to split my list in sublists using the null value as separator, in order to obtain a list of lists (List<List<String>>). I'm looking for a Java 8 solution. I've tried with Collectors.partitioningBy but I'm not sure it is what I'm looking for. Thanks!

答:
I was watching the video on Thinking in Parallel by Stuart. So decided to solve it before seeing his response in the video. Will update the solution with time. for now</p>

```<code>Arrays.asList(IntStream.range(0, abc.size()-1).
filter(index -> abc.get(index).equals("#") ).
map(index -> (index)).toArray()).
stream().forEach( index -> {for (int i = 0; i < index.length; i++) {
                    if(sublist.size()==0){
                        sublist.add(new ArrayList<String>(abc.subList(0, index[i])));
                    }else{

                    sublist.add(new ArrayList<String>(abc.subList(index[i]-1, index[i])));
                    }
                }
    sublist.add(new ArrayList<String>(abc.subList(index[index.length-1]+1, abc.size())));
});
</code>```

Body:
I have this list (List<String>):

["a", "b", null, "c", null, "d", "e"]

And I'd like something like this:

[["a", "b"], ["c"], ["d", "e"]]

In other words I want to split my list in sublists using the null value as separator, in order to obtain a list of lists (List<List<String>>). I'm looking for a Java 8 solution. I've tried with Collectors.partitioningBy but I'm not sure it is what I'm looking for. Thanks!

Body:
I was watching the video on Thinking in Parallel by Stuart. So decided to solve it before seeing his response in the video. Will update the solution with time. for now

Arrays.asList(IntStream.range(0, abc.size()-1).
filter(index -> abc.get(index).equals("#") ).
map(index -> (index)).toArray()).
stream().forEach( index -> {for (int i = 0; i < index.length; i++) {
                    if(sublist.size()==0){
                        sublist.add(new ArrayList<String>(abc.subList(0, index[i])));
                    }else{

                    sublist.add(new ArrayList<String>(abc.subList(index[i]-1, index[i])));
                    }
                }
    sublist.add(new ArrayList<String>(abc.subList(index[index.length-1]+1, abc.size())));
});


问:
Vanilla JS .style working but jQuery .css is not?
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated. </p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="css/index.css" type="text/css">
</head>
<body>

  <div id="header">

    <div id="navimg-holder">
        <img src="images/navimg.jpg" alt="">
    </div>

    <div id="navlist">

        <div class="navelm">
            <a href=""> <p> Home </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Contant </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Experience </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Interests </p> </a>
        </div>

    </div>

    <div id="logo-holder">

    </div>
    <div id="socialmedia-div">

        <div class="socialmedia-holder">
            <a href="https://facebook.com"> <img src="images/social1.jpg" alt="" > </a>
        </div>

        <div class="socialmedia-holder" id="second-socialmedia">
            <a href="https://twitter.com"> <img src="images/social2.jpg" alt="" id="twitter"> </a>
        </div>

        <div class="socialmedia-holder" id="third-socialmedia">
            <a href="https://www.instagram.com"> <img src="images/social3.jpg" alt="" id="insta"> </a>
        </div>

    </div>

  </div>

  <div id="content1">

  </div>

<script src="js/jquery-3.2.1.js"></script>
<script src="js/index.js"></script>
<script>document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script>
</body>
</html>

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}
</code>```

答:
this isn't a jQuery object, it's a plain DOM Node, you have to wrap it in $().

Here's three ways to do this:

```<code>$elements.each(function(i, el){
    $(this).css('key', value);
    //or
    $(el).css('key', value);
    //or
    $(someOtherNodeListOrCollection[i]).css('key', value);
});
</code>```

Keep in mind you can do multiple attributes

```<code>$item.css({
   'key1': value,
   'key2': value2
});
</code>```

Or even better for performance and separating concerns: use a selecting class, with addClass or removeClass.

Body:
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated.

<!DOCTYPE html>

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

 Home

 Contant

 Experience

 Interests

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}

Body:
this isn't a jQuery object, it's a plain DOM Node, you have to wrap it in $().

Here's three ways to do this:

$elements.each(function(i, el){
    $(this).css('key', value);
    //or
    $(el).css('key', value);
    //or
    $(someOtherNodeListOrCollection[i]).css('key', value);
});

Keep in mind you can do multiple attributes

$item.css({
   'key1': value,
   'key2': value2
});

Or even better for performance and separating concerns: use a selecting class, with addClass or removeClass.


问:
Excel formula to find and goto cell
I have a formula that's part of a conditional formatting rule that highlights in green any cell that contains whatever text I type. It works great but I have to scroll to find the row. Is there a way to have the formula goto that cell so I don't have to scroll down.

This is the formula: =SEARCH(input,$B2&$C2&$D2&$E2)

答:
Here is the solution I got from the Microsoft Office forums.</p>

```<code>Public Sub FindRecords()
Dim sFalse As String
Dim iDay As String
Dim i As Long, j As Long

sFalse = "False"

iDay = InputBox("Enter the value you want to scroll to:")

'   Test if input box is empty or cancel is pressed
If iDay = vbNullString Or iDay = sFalse Then GoTo ExitOut

i = Range("A" & Rows.Count).End(xlUp).Row

On Error GoTo Notfound

j = Range("A3:A" & i).Find(what:=iDay, after:=Range("A3")).Row
ActiveWindow.ScrollRow = j
Exit Sub

Notfound:
MsgBox "Your value was not found."
Exit Sub

ExitOut:
Application.DisplayAlerts = True
On Error GoTo 0
End Sub
</code>```

Title: Excel formula to find and goto cell

Body:
Here is the solution I got from the Microsoft Office forums.

Public Sub FindRecords()
Dim sFalse As String
Dim iDay As String
Dim i As Long, j As Long

sFalse = "False"

iDay = InputBox("Enter the value you want to scroll to:")

'   Test if input box is empty or cancel is pressed
If iDay = vbNullString Or iDay = sFalse Then GoTo ExitOut

i = Range("A" & Rows.Count).End(xlUp).Row

On Error GoTo Notfound

j = Range("A3:A" & i).Find(what:=iDay, after:=Range("A3")).Row
ActiveWindow.ScrollRow = j
Exit Sub

Notfound:
MsgBox "Your value was not found."
Exit Sub

ExitOut:
Application.DisplayAlerts = True
On Error GoTo 0
End Sub


问:
Firebase returns array with undefined object after remove
I'm having an issue when I remove an element from a Firebase database. The structure is as follows(just a sample):

```<code>{
  "users":
  [
    {
      "id": 0,
      "name": "Toma Broome"
    },
    {
      "id": 1,
      "name": "Boyd Bolens"
    }
  ]
}
</code>```

I'm getting the users list the connection is like this:

```<code>firebase.database().ref("/users/").on("value", snap => {
    users = snap.val();
    console.log( users ); // pay attention to this line
    usersLoop();
});
</code>```

Then I render the elements on screen and I try to remove one:

```<code>firebase.database().ref(`/users/${targetEl}`).remove();
</code>```

The element is actually removed from the database if I check the Firebase console, but the users array includes undefined values and after deleting some elements it returns an object and not an array.

This is the console after deleting three elements that are in the first position of the database. What I mean is that I get the full list of users (which I'm uploading using a JSON file), I delete the first element, all other elements are then re-rendered in the DOM. Then I remove the first element again and finally when I remove the first element for a third time, I get an object from firebase and obviously nothing is rendered because the code is expecting an array

```<code>(5) [undefined × 1, Object, Object, Object, Object]
(5) [undefined × 2, Object, Object, Object]
Object {3: Object, 4: Object}
</code>```

Also as you can see the array keeps returning a length of 5 when in the database there are less elements.

An option that I'm thinking about is to use Lodash to remove the undefined elements from the collection returned and/or turn it into an array, but that will defy any scalability option of the app looking into the future.

Finally what seems more odd than anything is that all of the sudden the database structure seems to change, when visually keeps looking exactly as it was.

This is the structure of the database on firebase

```<code>-users
 |-0
  |-id:0
  |-name:value
  |-otherprops:value
 |-1
  |-id:1
  |-name:value
  |-otherprops:value
</code>```

答:
The links provided by @cartant gave the answer.

Yes, firebase does tolerates array structures in it's data but is not recommended to use them unless the specific data is not going to mutate too much or at all. In my case (creating some sort of CRUD app) is not recommendable, just use objects end everything is ok. The thing is that if you upload a json file with an array in it, firebase will transform that into an object structure using integers as the key of each element in the array. Then when I started to remove elements and reached this point:

```<code>if (!opt_exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  // convert to array.
  var array = [];
  for (var key in obj)
    array[key] = obj[key];

  return array;
} else {
  if (opt_exportFormat && !this.getPriority().isEmpty()) {
    obj['.priority'] = this.getPriority().val();
  }
  return obj;
}
</code>```

After deleting a specific number of elements the code passed to the else part of the statement, which ultimately result in firebase returning an object creating the whole issue.

I ended up with this type of structure:

```<code>{
  "users":
  {
    "user_00": {
      "id": 0,
      "name": "Toma Broome"
    },
    "user_01": {
      "id": 1,
      "name": "Boyd Bolens"
    }
  }
}
</code>```

And using lodash to loop through the object (or it could be a for in loop) I was able to get the data in the same way I was doing when using an array. Finally using an object structure I didn't got any more collections with undefined elements in it.

@cartant, thanks a lot!!! I definitely learn something with your comments. I hope that you could post an answer so I can mark it as the solution of the problem and upvote it, you earned it sir!!

Body:
I'm having an issue when I remove an element from a Firebase database. The structure is as follows(just a sample):

{
  "users":
  [
    {
      "id": 0,
      "name": "Toma Broome"
    },
    {
      "id": 1,
      "name": "Boyd Bolens"
    }
  ]
}

I'm getting the users list the connection is like this:

firebase.database().ref("/users/").on("value", snap => {
    users = snap.val();
    console.log( users ); // pay attention to this line
    usersLoop();
});

Then I render the elements on screen and I try to remove one:

firebase.database().ref(`/users/${targetEl}`).remove();

The element is actually removed from the database if I check the Firebase console, but the users array includes undefined values and after deleting some elements it returns an object and not an array.

This is the console after deleting three elements that are in the first position of the database. What I mean is that I get the full list of users (which I'm uploading using a JSON file), I delete the first element, all other elements are then re-rendered in the DOM. Then I remove the first element again and finally when I remove the first element for a third time, I get an object from firebase and obviously nothing is rendered because the code is expecting an array

(5) [undefined × 1, Object, Object, Object, Object]
(5) [undefined × 2, Object, Object, Object]
Object {3: Object, 4: Object}

Also as you can see the array keeps returning a length of 5 when in the database there are less elements.

An option that I'm thinking about is to use Lodash to remove the undefined elements from the collection returned and/or turn it into an array, but that will defy any scalability option of the app looking into the future.

Finally what seems more odd than anything is that all of the sudden the database structure seems to change, when visually keeps looking exactly as it was.

This is the structure of the database on firebase

-users
 |-0
  |-id:0
  |-name:value
  |-otherprops:value
 |-1
  |-id:1
  |-name:value
  |-otherprops:value

Body:
The links provided by @cartant gave the answer.

Yes, firebase does tolerates array structures in it's data but is not recommended to use them unless the specific data is not going to mutate too much or at all. In my case (creating some sort of CRUD app) is not recommendable, just use objects end everything is ok. The thing is that if you upload a json file with an array in it, firebase will transform that into an object structure using integers as the key of each element in the array. Then when I started to remove elements and reached this point:

if (!opt_exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  // convert to array.
  var array = [];
  for (var key in obj)
    array[key] = obj[key];

  return array;
} else {
  if (opt_exportFormat && !this.getPriority().isEmpty()) {
    obj['.priority'] = this.getPriority().val();
  }
  return obj;
}

After deleting a specific number of elements the code passed to the else part of the statement, which ultimately result in firebase returning an object creating the whole issue.

I ended up with this type of structure:

{
  "users":
  {
    "user_00": {
      "id": 0,
      "name": "Toma Broome"
    },
    "user_01": {
      "id": 1,
      "name": "Boyd Bolens"
    }
  }
}

And using lodash to loop through the object (or it could be a for in loop) I was able to get the data in the same way I was doing when using an array. Finally using an object structure I didn't got any more collections with undefined elements in it.

@cartant, thanks a lot!!! I definitely learn something with your comments. I hope that you could post an answer so I can mark it as the solution of the problem and upvote it, you earned it sir!!


问:
Overflowing siblings' children the proper way
I have a circular div that represents white circle and the logo. It seems like I wanted it to be.

```<code><div class="whiteCircle">
  <div class="image" style="background-image: url('https://www.postnl.nl/Images/marker-groen-PostNL_tcm10-72617.png?version=1');"></div>
</div>

.whiteCircle {
    width: 65px;
    height: 65px;
    background-color: white;
    border-radius: 50px;
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
}
</code>```

Then, I created another rectangle div as a sibling to whiteBox, for the other contents.

```<code><div class="box">
  <div class="text">
    <h2>Heading</h2>
  </div>
</div>
</code>```

The positioning of both parents looks alright however I couldn't figure out a way to move the Heading above the whiteBox. I played with the combinations of z-index but I read it's not possible to adjust children's z-index and parent at the same time.

What am I doing wrong? What is the proper way of achieving it?

https://codepen.io/anon/pen/mwKrdG

答:
1- Remove the z-index from your parent div.

2- Add z-index to your white-box div, i choose the value 20.

3- Absolute positioning your .text class and make sure the z-index of it is bigger than 20;

The css

```<code>body {
  background-color: lightblue;
}

.whiteBox {
    width: 65px;
    height: 65px;
    background-color: white;
    border-radius: 50px;
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    z-index:20;
}

.image {
    text-align: center;
    height: 100%;
    background: no-repeat center center;
}

.container {
    width: 275px;
    height: 350px;
    background-color: white;
    margin: 0 auto;
    position: absolute;

    left: 0;
    right: 0;
    margin: 0 auto;
    top: 38px
}

.text {
  text-align: center;
      z-index: 25;
    position: absolute;
    left: 35%;
}
</code>```

https://codepen.io/anon/pen/OgEROK

Body:
I have a circular div that represents white circle and the logo. It seems like I wanted it to be.

.whiteCircle {
    width: 65px;
    height: 65px;
    background-color: white;
    border-radius: 50px;
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
}

Then, I created another rectangle div as a sibling to whiteBox, for the other contents.

Heading

The positioning of both parents looks alright however I couldn't figure out a way to move the Heading above the whiteBox. I played with the combinations of z-index but I read it's not possible to adjust children's z-index and parent at the same time.

What am I doing wrong? What is the proper way of achieving it?

https://codepen.io/anon/pen/mwKrdG

Body:
1- Remove the z-index from your parent div.

2- Add z-index to your white-box div, i choose the value 20.

3- Absolute positioning your .text class and make sure the z-index of it is bigger than 20;

The css

body {
  background-color: lightblue;
}

.whiteBox {
    width: 65px;
    height: 65px;
    background-color: white;
    border-radius: 50px;
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    z-index:20;
}

.image {
    text-align: center;
    height: 100%;
    background: no-repeat center center;
}

.container {
    width: 275px;
    height: 350px;
    background-color: white;
    margin: 0 auto;
    position: absolute;

    left: 0;
    right: 0;
    margin: 0 auto;
    top: 38px
}

.text {
  text-align: center;
      z-index: 25;
    position: absolute;
    left: 35%;
}

https://codepen.io/anon/pen/OgEROK


问:
Any C++ libraries for verb/action command line interfaces?
As the title implies I'm trying to find a library (header only would be nice) that makes it easy to implement these nifty little command line interfaces you see in web applications that have the form:

```<code>$ application --general-flag=asdf action --action-specific-flag=asdf positional --more-flags
</code>```

For example:

```<code>$ hugo new site --force --format=toml mysite
</code>```

or

```<code>$ hugo --buildDrafts
</code>```

For Go there are some (in my opinion) very good libraries for this, e.g. cobra or kingpin (github.com/alecthomas/kingpin).
However, I was not able to find a similar library in c++ that I like.
Most solutions seems to be rather complex to use, verbose or still require lots of manual work.

Generally it seems like they're approaching the problem by looking
at how to parse arguments and options instead of how to build a command
line interface.

Templated ones sometimes rely on RTTI being enabled, which has to be disable in my application.
The ones I looked at are: tclap, optionparser (optionparser.sourceforge.net/), cmdline (github.com/tanakh/cmdline), args.hxx (github.com/Taywee/args).

Args.hxx looked the most promising but relies on RTTI.
Do you know any libraries that I might have overlooked? Also sorry for the links, I was not allowed to have more than 2 but still wanted to give some info on what I already tried.

答: Although I never personally used it, you can have a look at Boost.Program_options. I'm not sure if RTTI is needed however.</p>

Body:
As the title implies I'm trying to find a library (header only would be nice) that makes it easy to implement these nifty little command line interfaces you see in web applications that have the form:

$ application --general-flag=asdf action --action-specific-flag=asdf positional --more-flags

For example:

$ hugo new site --force --format=toml mysite

or

$ hugo --buildDrafts

For Go there are some (in my opinion) very good libraries for this, e.g. cobra or kingpin (github.com/alecthomas/kingpin).
However, I was not able to find a similar library in c++ that I like.
Most solutions seems to be rather complex to use, verbose or still require lots of manual work.

Generally it seems like they're approaching the problem by looking
at how to parse arguments and options instead of how to build a command
line interface.

Templated ones sometimes rely on RTTI being enabled, which has to be disable in my application.
The ones I looked at are: tclap, optionparser (optionparser.sourceforge.net/), cmdline (github.com/tanakh/cmdline), args.hxx (github.com/Taywee/args).

Args.hxx looked the most promising but relies on RTTI.
Do you know any libraries that I might have overlooked? Also sorry for the links, I was not allowed to have more than 2 but still wanted to give some info on what I already tried.


问:
How can I validate a copy constructor's parameter?
```<code>public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}
</code>```

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

答:
You can use java.lang.Objects for this, but it will throw NullPointerException (with a message your supply) instead of IllegalArgumentException:

```<code>    public class Rectangle {

    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle rectangle) {
        this(Objects.requiresNotNull(rectangle, "rectangle was null").getWidth(), getHeight(rectangle));
    }
    ...
    }
</code>```

You can also make width and height final if you want to.

Body:
public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Body:
You can use java.lang.Objects for this, but it will throw NullPointerException (with a message your supply) instead of IllegalArgumentException:

    public class Rectangle {

    private int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(Rectangle rectangle) {
        this(Objects.requiresNotNull(rectangle, "rectangle was null").getWidth(), getHeight(rectangle));
    }
    ...
    }

You can also make width and height final if you want to.


问:
How to read and log the raw pixels of image in swift iOS
I need to read pixel values of an image and iterate to print in swift output, I have written this so far and used a RGBAImage class to read out pixels. I'm getting lost from CGContextRef to Iteration. I tried to write from CGImage, getting pixel data from objective C language to swift since I wanted to work in swift.

```<code>func createRGBAPixel(inImage: CGImageRef) -> CGContextRef {
//Image width, height

let pixelWidth = CGImageGetWidth(inImage)
let pixelHeight = CGImageGetHeight(inImage)

//Declaring number of bytes

let bytesPerRow = Int(pixelWidth) * 4
let byteCount = bytesPerRow * Int(pixelHeight)

//RGB color space

let colorSpace = CGColorSpaceCreateDeviceRGB()

//Allocating image data

let mapData = malloc(byteCount)
let mapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)

//Create bitmap context

let context = CGBitmapContextCreate(mapData, pixelWidth, pixelHeight, Int(8), Int(bytesPerRow), colorSpace, mapInfo.rawValue)

let pixelImage = CGBitmapContextCreate(pixels, pixelWidth, pixelHeight, bitsPerComponent, bytesPerRow, colorSpace, mapInfo)
let CGContextRef = pixelImage
let CGContextDrawImage(context, CGRectMake(0, 0, pixelWidth, pixelHeight), inImage)

//Iterating and logging
print("Logging pixel counts")
let pixels = calloc(pixelHeight * pixelWidth, sizeof(UInt32))

let myImage = CGImageRef: inImage
let myRGBA = RGBAImage(image: myImage)! //RGBAImage class to read pixels.

var number = 0
var currentPixel:Int32 = 0
currentPixel = pixels * UInt32
for number in 0..<pixelHeight {
  for number in 0..<pixelWidth {
    var color = color * currentPixel
    print((pixel.red + pixel.green + pixel.blue) / 3.0)
    currentPixel++
  }
}
return context!
}
</code>```

答:
I created small class for this:

```<code>class ImagePixelReader {

    enum Component:Int {
        case r = 0
        case g = 1
        case b = 2
        case alpha = 3
    }

    struct Color {
        var r:UInt8
        var g:UInt8
        var b:UInt8
        var a:UInt8

        var uiColor:UIColor {
            return UIColor(red:CGFloat(r)/255.0,green:CGFloat(g)/255.0,blue:CGFloat(b)/255.0,alpha:CGFloat(alpha)/255.0)
        }

    }

    let image:UIImage

    private var data:CFData
    private let pointer:UnsafePointer<UInt8>
    private let scale:Int

    init?(image:UIImage){

        self.image = image
        guard let cfdata = self.image.cgImage?.dataProvider?.data,
              let pointer = CFDataGetBytePtr(cfdata) else {
            return nil
        }
        self.scale = Int(image.scale)
        self.data = cfdata
        self.pointer = pointer
    }

    func componentAt(_ component:Component,x:Int,y:Int)->UInt8{

        assert(CGFloat(x) < image.size.width)
        assert(CGFloat(y) < image.size.height)

        let pixelPosition = (Int(image.size.width) * y * scale + x) * 4 * scale

        return pointer[pixelPosition + component.rawValue]
    }

    func colorAt(x:Int,y:Int)->Color{

        assert(CGFloat(x) < image.size.width)
        assert(CGFloat(y) < image.size.height)

        let pixelPosition = (Int(image.size.width) * y * scale + x) * 4 * scale

        return Color(r: pointer[pixelPosition + Component.r.rawValue],
                     g: pointer[pixelPosition + Component.g.rawValue],
                     b: pointer[pixelPosition + Component.b.rawValue],
                     a: pointer[pixelPosition + Component.alpha.rawValue])
    }
}
</code>```

How to use:

```<code>if let reader = ImagePixelReader(image: yourImage) {

   //get alpha or color
   let alpha = reader.componentAt(.alpha, x: 10, y:10)
   let color = reader.colorAt(x:10, y: 10).uiColor

   //getting all the pixels you need

   var values = ""

   //iterate over all pixels
   for x in 0 ..< Int(image.size.width){
     for y in 0 ..< Int(image.size.height){

        let color = reader.colorAt(x: x, y: y)
        values += "[\(x):\(y):\(color)] "

     }
     //add new line for every new row
     values += "\n"
   }

   print(values)
}
</code>```

Body:
I need to read pixel values of an image and iterate to print in swift output, I have written this so far and used a RGBAImage class to read out pixels. I'm getting lost from CGContextRef to Iteration. I tried to write from CGImage, getting pixel data from objective C language to swift since I wanted to work in swift.

func createRGBAPixel(inImage: CGImageRef) -> CGContextRef {
//Image width, height

let pixelWidth = CGImageGetWidth(inImage)
let pixelHeight = CGImageGetHeight(inImage)

//Declaring number of bytes

let bytesPerRow = Int(pixelWidth) * 4
let byteCount = bytesPerRow * Int(pixelHeight)

//RGB color space

let colorSpace = CGColorSpaceCreateDeviceRGB()

//Allocating image data

let mapData = malloc(byteCount)
let mapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)

//Create bitmap context

let context = CGBitmapContextCreate(mapData, pixelWidth, pixelHeight, Int(8), Int(bytesPerRow), colorSpace, mapInfo.rawValue)

let pixelImage = CGBitmapContextCreate(pixels, pixelWidth, pixelHeight, bitsPerComponent, bytesPerRow, colorSpace, mapInfo)
let CGContextRef = pixelImage
let CGContextDrawImage(context, CGRectMake(0, 0, pixelWidth, pixelHeight), inImage)

//Iterating and logging
print("Logging pixel counts")
let pixels = calloc(pixelHeight * pixelWidth, sizeof(UInt32))

let myImage = CGImageRef: inImage
let myRGBA = RGBAImage(image: myImage)! //RGBAImage class to read pixels.

var number = 0
var currentPixel:Int32 = 0
currentPixel = pixels * UInt32
for number in 0..<pixelHeight {
  for number in 0..<pixelWidth {
    var color = color * currentPixel
    print((pixel.red + pixel.green + pixel.blue) / 3.0)
    currentPixel++
  }
}
return context!
}

Body:
I created small class for this:

class ImagePixelReader {

    enum Component:Int {
        case r = 0
        case g = 1
        case b = 2
        case alpha = 3
    }

    struct Color {
        var r:UInt8
        var g:UInt8
        var b:UInt8
        var a:UInt8

        var uiColor:UIColor {
            return UIColor(red:CGFloat(r)/255.0,green:CGFloat(g)/255.0,blue:CGFloat(b)/255.0,alpha:CGFloat(alpha)/255.0)
        }

    }

    let image:UIImage

    private var data:CFData
    private let pointer:UnsafePointer<UInt8>
    private let scale:Int

    init?(image:UIImage){

        self.image = image
        guard let cfdata = self.image.cgImage?.dataProvider?.data,
              let pointer = CFDataGetBytePtr(cfdata) else {
            return nil
        }
        self.scale = Int(image.scale)
        self.data = cfdata
        self.pointer = pointer
    }

    func componentAt(_ component:Component,x:Int,y:Int)->UInt8{

        assert(CGFloat(x) < image.size.width)
        assert(CGFloat(y) < image.size.height)

        let pixelPosition = (Int(image.size.width) * y * scale + x) * 4 * scale

        return pointer[pixelPosition + component.rawValue]
    }

    func colorAt(x:Int,y:Int)->Color{

        assert(CGFloat(x) < image.size.width)
        assert(CGFloat(y) < image.size.height)

        let pixelPosition = (Int(image.size.width) * y * scale + x) * 4 * scale

        return Color(r: pointer[pixelPosition + Component.r.rawValue],
                     g: pointer[pixelPosition + Component.g.rawValue],
                     b: pointer[pixelPosition + Component.b.rawValue],
                     a: pointer[pixelPosition + Component.alpha.rawValue])
    }
}

How to use:

if let reader = ImagePixelReader(image: yourImage) {

   //get alpha or color
   let alpha = reader.componentAt(.alpha, x: 10, y:10)
   let color = reader.colorAt(x:10, y: 10).uiColor

   //getting all the pixels you need

   var values = ""

   //iterate over all pixels
   for x in 0 ..< Int(image.size.width){
     for y in 0 ..< Int(image.size.height){

        let color = reader.colorAt(x: x, y: y)
        values += "[\(x):\(y):\(color)] "

     }
     //add new line for every new row
     values += "\n"
   }

   print(values)
}


问:
CakePHP Session Timeout Not as Programmed?
I'm experiencing session timeouts in CakePHP quicker than I code. I have this line:

```<code>'Session' => [
    'defaults' => 'php',
    'timeout'=>24*60*60*30//for one month
],
</code>```

....But it is logging out around 30 minutes of inactivity I believe, at least it feels around there.

Any idea how to fix this or investigate where the problem is happening?

Thanks!

答:
```<code>'Session' => [
'cookie'=>'webapp',
'timeout' => 4320,
'cookieTimeout'=> 4320
],
</code>```

Body:
I'm experiencing session timeouts in CakePHP quicker than I code. I have this line:

'Session' => [
    'defaults' => 'php',
    'timeout'=>24*60*60*30//for one month
],

....But it is logging out around 30 minutes of inactivity I believe, at least it feels around there.

Any idea how to fix this or investigate where the problem is happening?

Thanks!


问:
Non-deterministic errors with python client on streaming inserts
I have a BigQuery table with the following schema:

```<code>    [
    {
        "mode": "REQUIRED",
        "name": "LOTRANS",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "FIRMWARE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "MBATTCHG",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "BATTV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "MINTIMEL",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "STARTTIME",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "NOMBATTV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "DATE",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "MODEL",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "HITRANS",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "TIMELEFT",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "BCHARGE",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "XONBATT",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "TONBATT",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "LINEV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "XOFFBATT",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "ALARMDEL",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "STATUS",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "CUMONBATT",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "CABLE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "UPSMODE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "LASTXFER",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "DRIVER",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "VERSION",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "LOADPCT",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "NOMINV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "ENDAPC",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "SERIALNO",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "HOSTNAME",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "UPSNAME",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "NUMXFERS",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "SENSE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "APC",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "MAXTIME",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "BATTDATE",
        "type": "DATE"
    },
    {
        "mode": "REQUIRED",
        "name": "STATFLAG",
        "type": "INTEGER"
    }
]
</code>```

An example of the data row is as follows:

```<code>{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": "13.7",
    "BCHARGE": "100.0",
    "CABLE": "USB Cable",
    "CUMONBATT": "2758",
    "DATE": "2017-07-04T20:20:26",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-04T20:20:35",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": "139.0",
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": "120.0",
    "LOADPCT": "0.0",
    "LOTRANS": "92.0",
    "MAXTIME": "0",
    "MBATTCHG": "5",
    "MINTIMEL": "3",
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": "12.0",
    "NOMINV": "120",
    "NUMXFERS": "188",
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": "0x05000008",
    "STATUS": "ONLINE",
    "TIMELEFT": "335.8",
    "TONBATT": "0",
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}
</code>```

I tried following the example code, but whenever I try to insert_data with the above dictionary using the python client I get non-deterministic errors such as

```<code>[{'index': 0, 'errors': [{u'debugInfo': u'generic::invalid_argument: Cannot convert value to integer (bad value):MBATTCHG', u'reason': u'invalid', u'message': u'Cannot convert value to integer (bad value):MBATTCHG', u'location': u'mbattchg'}]}]
</code>```

But the error changes on every attempted insert. What are ways to help debug why the errors are not deterministic, and why the converted values tend to be the keys of the dictionary instead of the values?

EDIT

Modified the event to the following, still getting errors

```<code>{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": 13.7,
    "BCHARGE": 100.0,
    "CABLE": "USB Cable",
    "CUMONBATT": 2758,
    "DATE": "2017-07-05T02:41:00",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-05T02:41:07",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": 139.0,
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": 123.0,
    "LOADPCT": 0.0,
    "LOTRANS": 92.0,
    "MAXTIME": 0,
    "MBATTCHG": 5,
    "MINTIMEL": 3.0,
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": 12.0,
    "NOMINV": 120.0,
    "NUMXFERS": "188",
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": 83886088,
    "STATUS": "ONLINE",
    "TIMELEFT": 335.8,
    "TONBATT": 0,
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}
</code>```

I tried to post the same object 2 different times and ended up with the following error messages (different each time)

```<code>[{'index': 0, 'errors': [{u'debugInfo': u'generic::invalid_argument: Cannot convert value to integer (bad value):CUMONBATT', u'reason': u'invalid', u'message': u'Cannot convert value to integer (bad value):CUMONBATT', u'location': u'cumonbatt'}]}]
[{'index': 0, 'errors': [{u'debugInfo': u'generic::out_of_range: Invalid datetime string "LOADPCT"', u'reason': u'invalid', u'message': u'Invalid datetime string "LOADPCT"', u'location': u'endapc'}]}]
</code>```

EDIT 2:

Fixed by using the returned schema for the table to construct an array instead of passing in an object

```<code>e = []
for schema_item in table._schema:
    e.append(d[schema_item.name])

rows = [e]
</code>```

答:
The row you used as example isn't in accordance with your schema indeed. It should be like:

```<code>{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": 13.7,
    "BCHARGE": 100.0,
    "CABLE": "USB Cable",
    "CUMONBATT": 2758,
    "DATE": "2017-07-04T20:20:26",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-04T20:20:35",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": 139.0,
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": 120.0,
    "LOADPCT": 0.0,
    "LOTRANS": 92.0,
    "MAXTIME": 0,
    "MBATTCHG": 5,
    "MINTIMEL": 3,
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": 12.0,
    "NOMINV": 120,
    "NUMXFERS": 188,
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": "0x05000008",
    "STATUS": "ONLINE",
    "TIMELEFT": 335.8,
    "TONBATT": 0,
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}
</code>```

Notice that FLOATS should be represented as a FLOAT number, not as a STRING (19.2 instead of "19.2" for instance).

One problem that would remain is the field STATFLAG, you defined it as an INTEGER but it has the character "x", maybe you'll have to change its type to be a STRING.

[EDIT]:

As for the python code, just remember that you should use the method insert_data from the Table class and for the rows input you should have a list with tuples for each row being insert, for instance:

```<code>rows=[(92.0, '904.W1 .D USB FW:W1', 5, 13.7, 3, '2017-05-23T13:27:07', 12.0, '2017-07-04T20:20:26', 'Back-UPS ES 550G', 139.0, 335.8, 100.0, '2017-07-4T03:55:53', 0, 120.0, '2017-07-04T03:55:55', 'No alarm', 'ONLINE', 758, 'USB Cable', 'Stand Alone', 'Unacceptable line voltage changes', 'USB UPS river', '3.14.12 (29 March 2014) debian', 0.0, 120, '2017-07-4T20:20:35', 'REDACTED', 'raspberrypi-master', 'raspberrypi-master', 88, 'Medium', '001,035,0928', 0, '2016-12-02', 5000008)]
table.insert_data(rows)
</code>```

Body:
I have a BigQuery table with the following schema:

    [
    {
        "mode": "REQUIRED",
        "name": "LOTRANS",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "FIRMWARE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "MBATTCHG",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "BATTV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "MINTIMEL",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "STARTTIME",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "NOMBATTV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "DATE",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "MODEL",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "HITRANS",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "TIMELEFT",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "BCHARGE",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "XONBATT",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "TONBATT",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "LINEV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "XOFFBATT",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "ALARMDEL",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "STATUS",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "CUMONBATT",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "CABLE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "UPSMODE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "LASTXFER",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "DRIVER",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "VERSION",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "LOADPCT",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "NOMINV",
        "type": "FLOAT"
    },
    {
        "mode": "REQUIRED",
        "name": "ENDAPC",
        "type": "DATETIME"
    },
    {
        "mode": "REQUIRED",
        "name": "SERIALNO",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "HOSTNAME",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "UPSNAME",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "NUMXFERS",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "SENSE",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "APC",
        "type": "STRING"
    },
    {
        "mode": "REQUIRED",
        "name": "MAXTIME",
        "type": "INTEGER"
    },
    {
        "mode": "REQUIRED",
        "name": "BATTDATE",
        "type": "DATE"
    },
    {
        "mode": "REQUIRED",
        "name": "STATFLAG",
        "type": "INTEGER"
    }
]

An example of the data row is as follows:

{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": "13.7",
    "BCHARGE": "100.0",
    "CABLE": "USB Cable",
    "CUMONBATT": "2758",
    "DATE": "2017-07-04T20:20:26",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-04T20:20:35",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": "139.0",
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": "120.0",
    "LOADPCT": "0.0",
    "LOTRANS": "92.0",
    "MAXTIME": "0",
    "MBATTCHG": "5",
    "MINTIMEL": "3",
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": "12.0",
    "NOMINV": "120",
    "NUMXFERS": "188",
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": "0x05000008",
    "STATUS": "ONLINE",
    "TIMELEFT": "335.8",
    "TONBATT": "0",
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}

I tried following the example code, but whenever I try to insert_data with the above dictionary using the python client I get non-deterministic errors such as

[{'index': 0, 'errors': [{u'debugInfo': u'generic::invalid_argument: Cannot convert value to integer (bad value):MBATTCHG', u'reason': u'invalid', u'message': u'Cannot convert value to integer (bad value):MBATTCHG', u'location': u'mbattchg'}]}]

But the error changes on every attempted insert. What are ways to help debug why the errors are not deterministic, and why the converted values tend to be the keys of the dictionary instead of the values?

EDIT

Modified the event to the following, still getting errors

{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": 13.7,
    "BCHARGE": 100.0,
    "CABLE": "USB Cable",
    "CUMONBATT": 2758,
    "DATE": "2017-07-05T02:41:00",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-05T02:41:07",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": 139.0,
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": 123.0,
    "LOADPCT": 0.0,
    "LOTRANS": 92.0,
    "MAXTIME": 0,
    "MBATTCHG": 5,
    "MINTIMEL": 3.0,
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": 12.0,
    "NOMINV": 120.0,
    "NUMXFERS": "188",
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": 83886088,
    "STATUS": "ONLINE",
    "TIMELEFT": 335.8,
    "TONBATT": 0,
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}

I tried to post the same object 2 different times and ended up with the following error messages (different each time)

[{'index': 0, 'errors': [{u'debugInfo': u'generic::invalid_argument: Cannot convert value to integer (bad value):CUMONBATT', u'reason': u'invalid', u'message': u'Cannot convert value to integer (bad value):CUMONBATT', u'location': u'cumonbatt'}]}]
[{'index': 0, 'errors': [{u'debugInfo': u'generic::out_of_range: Invalid datetime string "LOADPCT"', u'reason': u'invalid', u'message': u'Invalid datetime string "LOADPCT"', u'location': u'endapc'}]}]

EDIT 2:

Fixed by using the returned schema for the table to construct an array instead of passing in an object

e = []
for schema_item in table._schema:
    e.append(d[schema_item.name])

rows = [e]

Body:
The row you used as example isn't in accordance with your schema indeed. It should be like:

{
    "ALARMDEL": "No alarm",
    "APC": "001,035,0928",
    "BATTDATE": "2016-12-02",
    "BATTV": 13.7,
    "BCHARGE": 100.0,
    "CABLE": "USB Cable",
    "CUMONBATT": 2758,
    "DATE": "2017-07-04T20:20:26",
    "DRIVER": "USB UPS Driver",
    "ENDAPC": "2017-07-04T20:20:35",
    "FIRMWARE": "904.W1 .D USB FW:W1",
    "HITRANS": 139.0,
    "HOSTNAME": "raspberrypi-master",
    "LASTXFER": "Unacceptable line voltage changes",
    "LINEV": 120.0,
    "LOADPCT": 0.0,
    "LOTRANS": 92.0,
    "MAXTIME": 0,
    "MBATTCHG": 5,
    "MINTIMEL": 3,
    "MODEL": "Back-UPS ES 550G",
    "NOMBATTV": 12.0,
    "NOMINV": 120,
    "NUMXFERS": 188,
    "SENSE": "Medium",
    "SERIALNO": "REDACTED",
    "STARTTIME": "2017-05-23T13:27:07",
    "STATFLAG": "0x05000008",
    "STATUS": "ONLINE",
    "TIMELEFT": 335.8,
    "TONBATT": 0,
    "UPSMODE": "Stand Alone",
    "UPSNAME": "raspberrypi-master",
    "VERSION": "3.14.12 (29 March 2014) debian",
    "XOFFBATT": "2017-07-04T03:55:55",
    "XONBATT": "2017-07-04T03:55:53"
}

Notice that FLOATS should be represented as a FLOAT number, not as a STRING (19.2 instead of "19.2" for instance).

One problem that would remain is the field STATFLAG, you defined it as an INTEGER but it has the character "x", maybe you'll have to change its type to be a STRING.

[EDIT]:

As for the python code, just remember that you should use the method insert_data from the Table class and for the rows input you should have a list with tuples for each row being insert, for instance:

rows=[(92.0, '904.W1 .D USB FW:W1', 5, 13.7, 3, '2017-05-23T13:27:07', 12.0, '2017-07-04T20:20:26', 'Back-UPS ES 550G', 139.0, 335.8, 100.0, '2017-07-4T03:55:53', 0, 120.0, '2017-07-04T03:55:55', 'No alarm', 'ONLINE', 758, 'USB Cable', 'Stand Alone', 'Unacceptable line voltage changes', 'USB UPS river', '3.14.12 (29 March 2014) debian', 0.0, 120, '2017-07-4T20:20:35', 'REDACTED', 'raspberrypi-master', 'raspberrypi-master', 88, 'Medium', '001,035,0928', 0, '2016-12-02', 5000008)]
table.insert_data(rows)


问:
If a GET request's response changes, is idempotency respected?
I am reading a lot about rest API and I always stumble upon terms idempotency. Basically GET, HEAD, PUT, DELETE and OPTIONS are all idempotent, and POST is not.

This statement on http://www.restapitutorial.com/lessons/idempotency.html made me doubt my understanding of idempotency.

From a RESTful service standpoint, for an operation (or service call)
  to be idempotent, clients can make that same call repeatedly while
  producing the same result. In other words, making multiple identical
  requests has the same effect as making a single request. Note that
  while idempotent operations produce the same result on the server (no
  side effects), the response itself may not be the same (e.g. a
  resource's state may change between requests).

So does idempotency actually has something to do with server-work or a response?

What confuses me if I have

```<code>GET /users/5
</code>```

returning

```<code>{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}
</code>```

and then do the same request after one minute I would get

```<code>GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 11
}
</code>```

How is this idempotent?

Furthermore if response contains some kind of UUID which is unique for each response, would that break idempotency?

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?

答:
So does idempotency actually has something to do with server-work or a response?

It refers to the server state after subsequent request of the same type.

So, lets suppose that the client makes a request that changes the server's old state, for example S1, to a new state, S2, then makes the same request again.

If the method is idempotent then it is guaranteed that the second request would not change the server's state again, it will remain S2.

But if the method is not idempotent, there is no guarantee that the state would remain the same, S2; it may change to whatever state the server wants for example S3 or S1. So, in this case the client should not send the command again if a communication error occurs because the outcome would not be the same as the first time it sent the command.

GET /users/5
  How is this idempotent?

You may call this url using GET method as many time you want and the server would not change its internal state, i.e. last_name of the user; if it does not change it, then it remains the same so GET is idempotent.

Furthermore if response contains some kind of UUID which is unique for each response, would that break idempotency?

The response has nothing to do with the server's state after subsequent requests of the same type so the response could be unique after each request and the request would still be idempotent. For example, in the GET request from your question, the minutes_active would be greater each minute and this does not make GET not-idempotent.

Other example of idempotent method is DELETE. For example if you delete a user then it is gone/deleted. Because DELETE is idempotent, after a second atempt/request to delete the same user, the user would remain deleted so the state would not change. Of course, the second response could be a little different, something like "warning, user already deleted" but this has nothing to do with idempotency.

Body:
I am reading a lot about rest API and I always stumble upon terms idempotency. Basically GET, HEAD, PUT, DELETE and OPTIONS are all idempotent, and POST is not.

This statement on http://www.restapitutorial.com/lessons/idempotency.html made me doubt my understanding of idempotency.

From a RESTful service standpoint, for an operation (or service call)
  to be idempotent, clients can make that same call repeatedly while
  producing the same result. In other words, making multiple identical
  requests has the same effect as making a single request. Note that
  while idempotent operations produce the same result on the server (no
  side effects), the response itself may not be the same (e.g. a
  resource's state may change between requests).

So does idempotency actually has something to do with server-work or a response?

What confuses me if I have

GET /users/5

returning

{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 10
}

and then do the same request after one minute I would get

GET /users/5
{
"first_name" : "John",
"last_name" : "Doe",
"minutes_active": 11
}

How is this idempotent?

Furthermore if response contains some kind of UUID which is unique for each response, would that break idempotency?

And finally, is idempotency same server-work over and over again, or same results over and over again for the same/single request?


问:
Calling event click with JavaScript
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

```<code>protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }
</code>```

答:
You can use a data- attribute to id the buttons from javascript and then you just attach to the javascript event:

So, from the server side you can do this:

```<code> newButton.Attributes["data-dynamic-button"] = team;
</code>```

And you can implement this on the client side:

```<code>$("[data-dynamic-button]").click(function (event) {
    event.preventDefault()
    alert($(event.currentTarget).data("dynamic-button"));
});
</code>```

Title: Calling event click with JavaScript

Body:
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }

Body:
You can use a data- attribute to id the buttons from javascript and then you just attach to the javascript event:

So, from the server side you can do this:

 newButton.Attributes["data-dynamic-button"] = team;

And you can implement this on the client side:

$("[data-dynamic-button]").click(function (event) {
    event.preventDefault()
    alert($(event.currentTarget).data("dynamic-button"));
});


问:
XML parser only loading first object
I have a xml parser but the function in parser is able to get the first object of the xml file but is not able to get all of the categories of the xml file into the mutable array. Here is the functions :

```<code>    let xmlparser = XmlParser()
    xmlparser.loadRssFeed("FaceMask")
    faceMaskArray = (xmlparser.faceMaskArray.firstObject as! FaceMaskCategories).faceMaskItemArray
    collectionArray = faceMaskArray
</code>```

My xml file is as such

```<code>    <?xml version="1.0" encoding="utf-8"?>
<facemasks>
    <categories>
        <category >
            <id>0</id>
            <title>Animals</title>
            <image_name> leopard</image_name>
            <items>

                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1101</item_id>
                    <mask_title>leopard</mask_title>
                    <mask_image_name>leopard.png</mask_image_name>
                </item>

            </items>
        </category>
        <category >
            <id>1</id>
            <title>Animal</title>
            <image_name>leopard</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1102</item_id>
                    <mask_title>leopard</mask_title>
                    <mask_image_name>leopard.png</mask_image_name>
                </item>
            </items>
        </category>
        <category >
            <id>2</id>
            <title>Animals</title>
            <image_name>tiger</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1103</item_id>
                    <mask_title>tiger</mask_title>
                    <mask_image_name>tiger.png</mask_image_name>
                </item>
            </items>
        </category>
        <category >
            <id>3</id>
            <title>Animals</title>
            <image_name>tiger</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1104</item_id>
                    <mask_title>tigerz</mask_title>
                    <mask_image_name>tiger.png</mask_image_name>
                </item>
            </items>
        </category>
    </categories>
</facemasks>
</code>```

The function is getting only the first object or the last object correctly from the xml file. Can anyone please guide me how can I get all of the categories correctly from the xml file. I am really thankful for the help. Thank you.

答:
Check this code:

```<code>func beginParsing()
{
posts = []
parser = NSXMLParser(contentsOfURL:
(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
parser.delegate = self
parser.parse()
tbData!.reloadData()
}
</code>```

Here is the parser function with is getting the whole array:

```<code>func parser(parser: NSXMLParser, didStartElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?, attributes
attributeDict: [String : String])
{
element = elementName
if (elementName as NSString).isEqualToString("item") // Replace this item with category.
{
elements = NSMutableDictionary()
elements = [:]
title1 = NSMutableString()
title1 = ""
date = NSMutableString()
date = ""
}
}
</code>```

It gets all the items from array, "item" is actually tag or each item in array, just like "category" in your sample XML.

This is the sample XML:

http://images.apple.com/main/rss/hotnews/hotnews.rss#sthash.1Mq673bO.dpuf.

And to parse data from each item:

```<code>func parser(parser: NSXMLParser!, foundCharacters string: String!)
{
 if element.isEqualToString("title") {
title1.appendString(string)
} else if element.isEqualToString("pubDate") {
date.appendString(string)
}
}
</code>```

I am using this tutorial, it's working fine:

http://www.theappguruz.com/blog/xml-parsing-using-nsxmlparse-swift

Title: XML parser only loading first object

Body:
I have a xml parser but the function in parser is able to get the first object of the xml file but is not able to get all of the categories of the xml file into the mutable array. Here is the functions :

    let xmlparser = XmlParser()
    xmlparser.loadRssFeed("FaceMask")
    faceMaskArray = (xmlparser.faceMaskArray.firstObject as! FaceMaskCategories).faceMaskItemArray
    collectionArray = faceMaskArray

My xml file is as such

    <?xml version="1.0" encoding="utf-8"?>
<facemasks>
    <categories>
        <category >
            <id>0</id>
            <title>Animals</title>
            <image_name> leopard</image_name>
            <items>

                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1101</item_id>
                    <mask_title>leopard</mask_title>
                    <mask_image_name>leopard.png</mask_image_name>
                </item>

            </items>
        </category>
        <category >
            <id>1</id>
            <title>Animal</title>
            <image_name>leopard</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1102</item_id>
                    <mask_title>leopard</mask_title>
                    <mask_image_name>leopard.png</mask_image_name>
                </item>
            </items>
        </category>
        <category >
            <id>2</id>
            <title>Animals</title>
            <image_name>tiger</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1103</item_id>
                    <mask_title>tiger</mask_title>
                    <mask_image_name>tiger.png</mask_image_name>
                </item>
            </items>
        </category>
        <category >
            <id>3</id>
            <title>Animals</title>
            <image_name>tiger</image_name>
            <items>
                <item>
                    <landmarks_file_name>leopard</landmarks_file_name>
                    <item_id>1104</item_id>
                    <mask_title>tigerz</mask_title>
                    <mask_image_name>tiger.png</mask_image_name>
                </item>
            </items>
        </category>
    </categories>
</facemasks>

The function is getting only the first object or the last object correctly from the xml file. Can anyone please guide me how can I get all of the categories correctly from the xml file. I am really thankful for the help. Thank you.

Body:
Check this code:

func beginParsing()
{
posts = []
parser = NSXMLParser(contentsOfURL:
(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
parser.delegate = self
parser.parse()
tbData!.reloadData()
}

Here is the parser function with is getting the whole array:

func parser(parser: NSXMLParser, didStartElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?, attributes
attributeDict: [String : String])
{
element = elementName
if (elementName as NSString).isEqualToString("item") // Replace this item with category.
{
elements = NSMutableDictionary()
elements = [:]
title1 = NSMutableString()
title1 = ""
date = NSMutableString()
date = ""
}
}

It gets all the items from array, "item" is actually tag or each item in array, just like "category" in your sample XML.

This is the sample XML:

http://images.apple.com/main/rss/hotnews/hotnews.rss#sthash.1Mq673bO.dpuf.

And to parse data from each item:

func parser(parser: NSXMLParser!, foundCharacters string: String!)
{
 if element.isEqualToString("title") {
title1.appendString(string)
} else if element.isEqualToString("pubDate") {
date.appendString(string)
}
}

I am using this tutorial, it's working fine:

http://www.theappguruz.com/blog/xml-parsing-using-nsxmlparse-swift


问:
Giteye cannot import repository
I am working with the latest version of GitEye and I cannot import local repositories.

When I try that it throws a java.lang.NullPointerException. Does anyone have a solution for that?

As far as I know GitEye uses JGit and is based on eclipse.

Here are the error details:

```<code>eclipse.buildId=unknown
java.version=1.8.0_111
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_DE
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -data @user.home/.giteye

org.eclipse.egit.ui
Error
Tue Jul 04 22:42:45 CEST 2017
Error occurred

java.lang.NullPointerException
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.isDotGit(RepositorySearchDialog.java:525)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.isGitInternal(RepositorySearchDialog.java:508)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.preVisitDirectory(RepositorySearchDialog.java:475)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.preVisitDirectory(RepositorySearchDialog.java:1)
    at java.nio.file.Files.walkFileTree(Unknown Source)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog.findGitDirsRecursive(RepositorySearchDialog.java:557)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog.access$12(RepositorySearchDialog.java:450)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$12.run(RepositorySearchDialog.java:619)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)
</code>```

答:
Check if this is not similar to bug 513744 and bug 509827

NPE if adding existing repository

This was fixed in EGit 4.7 in March 2017, which might not be used by GitEye.

Title: Giteye cannot import repository

Body:
I am working with the latest version of GitEye and I cannot import local repositories.

When I try that it throws a java.lang.NullPointerException. Does anyone have a solution for that?

As far as I know GitEye uses JGit and is based on eclipse.

Here are the error details:

eclipse.buildId=unknown
java.version=1.8.0_111
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_DE
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -data @user.home/.giteye

org.eclipse.egit.ui
Error
Tue Jul 04 22:42:45 CEST 2017
Error occurred

java.lang.NullPointerException
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.isDotGit(RepositorySearchDialog.java:525)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.isGitInternal(RepositorySearchDialog.java:508)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.preVisitDirectory(RepositorySearchDialog.java:475)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$11.preVisitDirectory(RepositorySearchDialog.java:1)
    at java.nio.file.Files.walkFileTree(Unknown Source)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog.findGitDirsRecursive(RepositorySearchDialog.java:557)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog.access$12(RepositorySearchDialog.java:450)
    at org.eclipse.egit.ui.internal.repository.RepositorySearchDialog$12.run(RepositorySearchDialog.java:619)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)