问:
Why emplace_back does matter?
```<code>#include <iostream>
#include <vector>

struct T{
    T(){
        std::cout << "Constructor\n";
    }
    ~T(){
        std::cout << "Destructor\n";
    }
};

int main() {
    std::vector<T> vec;
    vec.push_back(T());
    vec.push_back(T());

    return 0;
}
</code>```

The output is:

```<code>(1)Constructor
(2)Destructor
(3)Constructor
(4)Destructor
(5)Destructor
(6)Destructor
(7)Destructor
</code>```

Why there is so much desructors calls? I see that:

(1) consruct temporary object temp1

(2) destruct temp1

(3) consruct temporary object temp2

(4) destruct temp2

Then it was called copy constructor or move constructor for temp1 and temp 2. So, (5) and (6) are clear. But what about (7)?

答:
Let's expand your structure a bit:

```<code>struct T {
    T() {
        std::cout << "Constructor\n";
    }

    T(const T&) {
        std::cout << "Copy Constructor\n";
    }

    T(T&&) {
        std::cout << "Move Constructor\n";
    }

    ~T() {
        std::cout << "Destructor\n";
    }
};
</code>```

And separate calls to push_back method:

```<code>vec.push_back(T()); // 1
std::cout << "--- --- ---\n";

vec.push_back(T()); // 2
std::cout << "--- --- ---\n";
</code>```

Now the output looks more complete:

```<code>Constructor
Move Constructor
Destructor
--- --- ---
Constructor
Move Constructor
Copy Constructor
Destructor
Destructor
--- --- ---
Destructor
Destructor
</code>```

The first group:

```<code>Constructor
Move Constructor
Destructor
</code>```

corresponds to the first push_back call:

```<code>vec.push_back(T()); // 1
</code>```

The output might be decrypted easily:

```<code>Constructor // Create a temporary
Move Constructor // Move a temporary into the internal vector storage
Destructor // Destroy a temporary
</code>```

The second group:

```<code>Constructor
Move Constructor
Copy Constructor
Destructor
Destructor
</code>```

corresponds to the second push_back call:

```<code>vec.push_back(T()); // 2
</code>```

and a little bit more complicated:

```<code>Constructor // create a temporary
Move Constructor // move it into the newly allocated vector storage
Copy Constructor // copy previously created element into the new storage
Destructor // destroy old storage
Destructor // destroy temporary
</code>```

Here you should remember that vector class allocates its memory internally and then manages it to provide enogh space for all elements. So, if you add more elements, new allocations happen and old elements are copied or moved into the new storage.

In case of known size you might use reserve method, which simply reserves enough memory for a particular number of elements. It allows to avoid unnecessary memory reallocations and copying or moving elements during these reallocations on adding new elements into the vector (at least until you don't exceed the reserved size).

The third group:

```<code>Destructor
Destructor
</code>```

corresponds to the vector vec destructor call at the end of the program.

Title: Why emplace_back does matter?

Body:
#include <iostream>
#include <vector>

struct T{
    T(){
        std::cout << "Constructor\n";
    }
    ~T(){
        std::cout << "Destructor\n";
    }
};

int main() {
    std::vector<T> vec;
    vec.push_back(T());
    vec.push_back(T());

    return 0;
}

The output is:

(1)Constructor
(2)Destructor
(3)Constructor
(4)Destructor
(5)Destructor
(6)Destructor
(7)Destructor

Why there is so much desructors calls? I see that:

(1) consruct temporary object temp1

(2) destruct temp1

(3) consruct temporary object temp2

(4) destruct temp2

Then it was called copy constructor or move constructor for temp1 and temp 2. So, (5) and (6) are clear. But what about (7)?

Body:
Let's expand your structure a bit:

struct T {
    T() {
        std::cout << "Constructor\n";
    }

    T(const T&) {
        std::cout << "Copy Constructor\n";
    }

    T(T&&) {
        std::cout << "Move Constructor\n";
    }

    ~T() {
        std::cout << "Destructor\n";
    }
};

And separate calls to push_back method:

vec.push_back(T()); // 1
std::cout << "--- --- ---\n";

vec.push_back(T()); // 2
std::cout << "--- --- ---\n";

Now the output looks more complete:

Constructor
Move Constructor
Destructor
--- --- ---
Constructor
Move Constructor
Copy Constructor
Destructor
Destructor
--- --- ---
Destructor
Destructor

The first group:

Constructor
Move Constructor
Destructor

corresponds to the first push_back call:

vec.push_back(T()); // 1

The output might be decrypted easily:

Constructor // Create a temporary
Move Constructor // Move a temporary into the internal vector storage
Destructor // Destroy a temporary

The second group:

Constructor
Move Constructor
Copy Constructor
Destructor
Destructor

corresponds to the second push_back call:

vec.push_back(T()); // 2

and a little bit more complicated:

Constructor // create a temporary
Move Constructor // move it into the newly allocated vector storage
Copy Constructor // copy previously created element into the new storage
Destructor // destroy old storage
Destructor // destroy temporary

Here you should remember that vector class allocates its memory internally and then manages it to provide enogh space for all elements. So, if you add more elements, new allocations happen and old elements are copied or moved into the new storage.

In case of known size you might use reserve method, which simply reserves enough memory for a particular number of elements. It allows to avoid unnecessary memory reallocations and copying or moving elements during these reallocations on adding new elements into the vector (at least until you don't exceed the reserved size).

The third group:

Destructor
Destructor

corresponds to the vector vec destructor call at the end of the program.


来源: stackexchange

问:
capturing image from web cam and send it to phone
I am making a windows form to capture image from laptop and send it to phone through email or whatsapp or any other social networking site. Though I got the capturing image code, I couldn't find the code for sending the image. Please help.</p>

答:
You can send email with image with this code:

```<code>using (var client = new SmtpClient())
{
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("you@your.address"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"));
    inlineLogo.ContentId = Guid.NewGuid().ToString();

    string body = string.Format(@"
            <img src=""cid:{0}"" />
        ", inlineLogo.ContentId);

    var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    view.LinkedResources.Add(inlineLogo);
    newMail.AlternateViews.Add(view);

    client.Send(newMail);
}
</code>```

https://stackoverflow.com/a/11000938/5364144

ContentLicense: CC BY-SA 3.0

Body:
You can send email with image with this code:

using (var client = new SmtpClient())
{
    MailMessage newMail = new MailMessage();
    newMail.To.Add(new MailAddress("you@your.address"));
    newMail.Subject = "Test Subject";
    newMail.IsBodyHtml = true;

    var inlineLogo = new LinkedResource(Server.MapPath("~/Path/To/YourImage.png"));
    inlineLogo.ContentId = Guid.NewGuid().ToString();

    string body = string.Format(@"
            <img src=""cid:{0}"" />
        ", inlineLogo.ContentId);

    var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
    view.LinkedResources.Add(inlineLogo);
    newMail.AlternateViews.Add(view);

    client.Send(newMail);
}

https://stackoverflow.com/a/11000938/5364144


问:
How to replace multiple substrings without replacing replaced substrings?
Help or assist as to replace in my case in such variants:

```<code>$string = "This is simple string";

$search = array (
  "This is simple",
  "string",
  "simple",
  "apple"
);

$replace = array (
  "This is red",
  "apple",
  "false",
  "lemon"
);

$result = str_replace($search, $replace, $string);
</code>```

Result must be: This is red apple

Not so: This is false apple OR This is red lemon OR This is false red lemon

If, at each replacement, the changed line is cut into some variable and then returned later, the result may be correct. But I do not know this is my option, but I could not realize it.

答:
Use strtr():

```<code>$string = "This is simple string";

$search = array
(
  "This is simple",
  "string",
  "simple",
  "apple"
);

$replace = array
(
  "This is red",
  "apple",
  "false",
  "lemon"
);

echo strtr($string,array_combine($search, $replace));
</code>```

Output:

```<code>This is red apple
</code>```

Important

I must inform readers that this beautiful function is also a quirky one.  If you've never used this function before, I recommend that you read the manual as well as the comments beneath it.

Importantly for this case (rather, my answer):

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In the OP's coding attempt, the keys ($search) are ordered by descending length.  This aligns the functions behavior with what most people would expect to happen.

However, consider this demonstration where the keys (and their values) are shuffled around slightly:

Code: (Demo)

```<code>$string="This is simple string";
$search=[
   "string",  // listed first, translated second, changed to "apple" which becomes "untouchable"
   "apple",  // this never gets a chance
   "simple",  // this never gets a chance
   "This is simple"  // listed last, but translated first and becomes "untouchable"
];
$replace=[
   "apple",
   "lemon",
   "false",
   "This is red"
];
echo strtr($string,array_combine($search, $replace));
</code>```

You may be surprised to know that this provides the same output: This is red apple

Body:
Help or assist as to replace in my case in such variants:

$string = "This is simple string";

$search = array (
  "This is simple",
  "string",
  "simple",
  "apple"
);

$replace = array (
  "This is red",
  "apple",
  "false",
  "lemon"
);

$result = str_replace($search, $replace, $string);

Result must be: This is red apple

Not so: This is false apple OR This is red lemon OR This is false red lemon

If, at each replacement, the changed line is cut into some variable and then returned later, the result may be correct. But I do not know this is my option, but I could not realize it.

Body:
Use strtr():

$string = "This is simple string";

$search = array
(
  "This is simple",
  "string",
  "simple",
  "apple"
);

$replace = array
(
  "This is red",
  "apple",
  "false",
  "lemon"
);

echo strtr($string,array_combine($search, $replace));

Output:

This is red apple

Important

I must inform readers that this beautiful function is also a quirky one.  If you've never used this function before, I recommend that you read the manual as well as the comments beneath it.

Importantly for this case (rather, my answer):

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In the OP's coding attempt, the keys ($search) are ordered by descending length.  This aligns the functions behavior with what most people would expect to happen.

However, consider this demonstration where the keys (and their values) are shuffled around slightly:

Code: (Demo)

$string="This is simple string";
$search=[
   "string",  // listed first, translated second, changed to "apple" which becomes "untouchable"
   "apple",  // this never gets a chance
   "simple",  // this never gets a chance
   "This is simple"  // listed last, but translated first and becomes "untouchable"
];
$replace=[
   "apple",
   "lemon",
   "false",
   "This is red"
];
echo strtr($string,array_combine($search, $replace));

You may be surprised to know that this provides the same output: This is red apple


问:
Cron job scheduling is not working in ubuntu
1) i have a script sp19.sh in the path /home/killer/Desktop/alok/scripts/test1

```<code>#script to copy file 1 in test dir
a=`ls -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "$a"  "$b"
</code>```

2) i scheduled a task to copy a file named 1 in the same location using the below code in crontab.But this is not working.

```<code>m h  dom mon dow   command
* * * * * /home/killer/Desktop/alok/scripts/test1/sp19.sh
</code>```

3) I have already tested that the sp19.sh is correct and generating the files but cron job is not working.

Thanks

答:
The issue was with the script file
The correct script should be

```<code>#cript to copy file 1 in test dir
a=`ls /home/killer/Desktop/alok/scripts/test1 -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "/home/killer/Desktop/alok/scripts/test1/$a" "/home/killer/Desktop/alok/scripts/test1/$b"
</code>```

Body:
1) i have a script sp19.sh in the path /home/killer/Desktop/alok/scripts/test1

#script to copy file 1 in test dir
a=`ls -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "$a"  "$b"

2) i scheduled a task to copy a file named 1 in the same location using the below code in crontab.But this is not working.

m h  dom mon dow   command
* * * * * /home/killer/Desktop/alok/scripts/test1/sp19.sh

3) I have already tested that the sp19.sh is correct and generating the files but cron job is not working.

Thanks

Body:
The issue was with the script file
The correct script should be

#cript to copy file 1 in test dir
a=`ls /home/killer/Desktop/alok/scripts/test1 -t|cut -c 1,4|head -1`
b=`expr $a + 1`
cp "/home/killer/Desktop/alok/scripts/test1/$a" "/home/killer/Desktop/alok/scripts/test1/$b"


问:
How to remove required attribute from element using only Javascript when radio button is unchecked?
I have a radio button named 'Other/Query' and when it is checked, the textarea below it becomes required using the required attribute.

I would like to remove the required attribute from the textarea element when the 'Other/Query' radio button is unchecked, using only JavaScript.

Is it possible to remove the required attribute when a radio button is unchecked?

I am currently using the JS below which adds the required attribute, but does not remove it when unchecked.

```<code>var gquery = document.getElementById("genquery");
var comment = document.getElementById("comments");
    gquery.addEventListener('change', function(){
    comment.required = this.checked;
});
if(gquery.required = false){
    comment.required = false;
};
</code>```

Any help is greatly appreciated.

答:
You can use this

```<code>gquery.addEventListener('click', function(event){
    if (this.checked) {
    comment.classList.add('required')
    comment.setAttribute('required', 'required')
  }
});

genquerytwo.addEventListener('click', function(event){
    if(this.checked) {
    comment.classList.remove('required')
    comment.removeAttribute('required')
   }
});
</code>```

See it in action -> Fiddle

Updated fiddle -> Updated Fiddle(v2)

Body:
I have a radio button named 'Other/Query' and when it is checked, the textarea below it becomes required using the required attribute.

I would like to remove the required attribute from the textarea element when the 'Other/Query' radio button is unchecked, using only JavaScript.

Is it possible to remove the required attribute when a radio button is unchecked?

I am currently using the JS below which adds the required attribute, but does not remove it when unchecked.

var gquery = document.getElementById("genquery");
var comment = document.getElementById("comments");
    gquery.addEventListener('change', function(){
    comment.required = this.checked;
});
if(gquery.required = false){
    comment.required = false;
};

Any help is greatly appreciated.

Body:
You can use this

gquery.addEventListener('click', function(event){
    if (this.checked) {
    comment.classList.add('required')
    comment.setAttribute('required', 'required')
  }
});

genquerytwo.addEventListener('click', function(event){
    if(this.checked) {
    comment.classList.remove('required')
    comment.removeAttribute('required')
   }
});

See it in action -> Fiddle

Updated fiddle -> Updated Fiddle(v2)


问:
How to send multiple emails from database as CC with PHPMailer?
I have a database. The fields are id, email and city. I want to send some email to all emails in my database.

In e.g case: I live in a city, so I want to send an email to all emails matchting my city.

I have wrote my method code like this:

```<code> $kota = mysql_real_escape_string(stripcslashes( $_POST['kota']));
        $baca_kota = mysql_query("SELECT email FROM conselor WHERE kota='$kota'");
        while($read = mysql_fetch_array($baca_kota))

        {

            $emailcc = $read['email'];
        }

        require '../phpmailer/PHPMailerAutoload.php';
        require '../phpmailer/class.phpmailer.php';

        $mail = new PHPMailer;
        //$mail->SMTPDebug = 3;                               // Enable verbose debug output

        $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'xxxxxxxxxxxxxxxxxx';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'xxxxxxxxxxxxxxx';                 // SMTP username
            $mail->Password = 'xxxxxxxxxxxxxxx';                           // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to

        $mail->setFrom($email,$name);
        $mail->addAddress('stevanlai04@gmail.com');     // Add a recipient
        $mail->addReplyTo($email);
        $mail->addCC($emailcc);
</code>```

答:
all you need to call Send() method from your PHPmailer sdk in your

```<code>while

     $this->mail->IsSMTP();
     $this->mail->SMTPAuth = true;
     $this->mail->Host = 'mail.example.com';
    //$this->mail->SMTPSecure = 'ssl';
     $this->mail->Port =25;

     $this->mail->Username = 'mail@example.com';
     $this->mail->Password = 'your password';

    foreach($listemails as $key=>val){
     $this->mail->SetFrom($val["email address"], 'topic');
$this->mail->Send();
    }
</code>```

Edit: Also you can create a function that function send email and it returns itself! for example

```<code> function sendemail($emailaddres){

    // call your phpmailler medhot
    / and return it
$this->mail->Send()
    return sendemail($val["email address"])
</code>```

Body:
I have a database. The fields are id, email and city. I want to send some email to all emails in my database.

In e.g case: I live in a city, so I want to send an email to all emails matchting my city.

I have wrote my method code like this:

 $kota = mysql_real_escape_string(stripcslashes( $_POST['kota']));
        $baca_kota = mysql_query("SELECT email FROM conselor WHERE kota='$kota'");
        while($read = mysql_fetch_array($baca_kota))

        {

            $emailcc = $read['email'];
        }

        require '../phpmailer/PHPMailerAutoload.php';
        require '../phpmailer/class.phpmailer.php';

        $mail = new PHPMailer;
        //$mail->SMTPDebug = 3;                               // Enable verbose debug output

        $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'xxxxxxxxxxxxxxxxxx';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'xxxxxxxxxxxxxxx';                 // SMTP username
            $mail->Password = 'xxxxxxxxxxxxxxx';                           // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to

        $mail->setFrom($email,$name);
        $mail->addAddress('stevanlai04@gmail.com');     // Add a recipient
        $mail->addReplyTo($email);
        $mail->addCC($emailcc);

Body:
all you need to call Send() method from your PHPmailer sdk in your

while

     $this->mail->IsSMTP();
     $this->mail->SMTPAuth = true;
     $this->mail->Host = 'mail.example.com';
    //$this->mail->SMTPSecure = 'ssl';
     $this->mail->Port =25;

     $this->mail->Username = 'mail@example.com';
     $this->mail->Password = 'your password';

    foreach($listemails as $key=>val){
     $this->mail->SetFrom($val["email address"], 'topic');
$this->mail->Send();
    }

Edit: Also you can create a function that function send email and it returns itself! for example

 function sendemail($emailaddres){

    // call your phpmailler medhot
    / and return it
$this->mail->Send()
    return sendemail($val["email address"])


答:
emplace_back matters for "move only" types (like std::unique_ptr).

This is wrong and an oversimplification. Not all containers are created equally. For your vector example, if we use reserve the implementation can do a move assign rather than a construct, eliding our copy/extraneous destructor:

```<code>std::vector<T> v;
v.reserve(2);
v.emplace_back(1);
v.emplace_back(1);
</code>```

Output:

```<code>Constructor
Constructor
---
Destructor
Destructor
</code>```

For a set:

```<code>std::set<T> s;
s.emplace(1);
s.emplace(1);
</code>```

We get the same output. Why though? A set should theoretically construct only one object since sets are unique right? In actuality, the typical implementation constructs a temporary node in order to perform the comparison, accounting for the extra construct/destruct even though it never enters the container.

Title: Why emplace_back does matter?

Body:
emplace_back matters for "move only" types (like std::unique_ptr).

This is wrong and an oversimplification. Not all containers are created equally. For your vector example, if we use reserve the implementation can do a move assign rather than a construct, eliding our copy/extraneous destructor:

std::vector<T> v;
v.reserve(2);
v.emplace_back(1);
v.emplace_back(1);

Output:

Constructor
Constructor
---
Destructor
Destructor

For a set:

std::set<T> s;
s.emplace(1);
s.emplace(1);

We get the same output. Why though? A set should theoretically construct only one object since sets are unique right? In actuality, the typical implementation constructs a temporary node in order to perform the comparison, accounting for the extra construct/destruct even though it never enters the container.


问:
Unity Daydream CalledFromWrongThreadException
We get error reports from Crashlytics affecting a sizable portion of our users (around 10% of them). It's a CalledFromWrongThreadException.

The problem is I don't know what's causing the issue and I don't have it myself. Here is the log:

```<code>Caused by android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
       at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7282)
       at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1197)
       at android.view.ViewGroup.invalidateChild(ViewGroup.java:5748)
       at android.view.View.invalidateInternal(View.java:15082)
       at android.view.View.invalidate(View.java:15046)
       at android.view.View.invalidate(View.java:15029)
       at android.view.SurfaceView$1.handleMessage(SurfaceView.java:142)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at com.unity3d.player.UnityPlayer$c.run(Unknown Source:20)
</code>```

The com.unity3d.player.UnityPlayer$c.run(Unknown Source:20) is not really helpfull here as the origin is unknown, I guess it could come from a third party library (GVR SDK, Fabric...).

Does anyone have the same issue?

For reference we are using Unity version : 5.6.0f3 and the bug is reported only for Pixel and Pixel XL phones.

答:
I don't have all the details about your project, and the errors that cannot be reproduced in-house are the worst kind. Nevertheless, I'll try to give a few hints as to what's going on. Perhaps these hints can shed some light and help you figure out the root cause of error:

CalledFromWrongThreadException

On Android, a View can only be accessed from the thread that created it. This is actually true for other environments as well (WinForms, WPF, etc). This exception means that something is trying to access some UI element (SurfaceView) from the wrong thread.

com.unity3d.player.UnityPlayer$c.run

The stack trace originates from some custom Unity plumbing code. While this doesn't give a clue where this call comes from (in your C# code), it might mean the code came from C# (using AndroidJavaObject or AndroidJavaClass calls). Unity's scripting thread is not the same as Android's main thread, and so this makes sense together with the exception type you're getting.

As a test, i've used this code to simulate the same exception:

```<code>using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
    var activity = actClass.GetStatic<AndroidJavaObject>("currentActivity");

    // cause an exception to be thrown
    activity.Call("setContentView", 15);
}
</code>```

This resulted in the following exception, which is very similar to the one you're getting (at least at its root).

E/ViewRootImpl(19244): com.test.crash.GameActivity : Only the original
  thread that created a view hierarchy can touch its views.
  E/ViewRootImpl(19244): java.lang.RuntimeException
  E/ViewRootImpl(19244):    at
  android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7105)
  E/ViewRootImpl(19244):    at
  android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1139)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.invalidateChild(ViewGroup.java:5254)
  E/ViewRootImpl(19244):    at
  android.view.View.invalidateInternal(View.java:13669)
  E/ViewRootImpl(19244):    at
  android.view.View.invalidate(View.java:13633) E/ViewRootImpl(19244):
    at android.view.View.onFocusChanged(View.java:6204)
  E/ViewRootImpl(19244):    at
  android.view.View.clearFocusInternal(View.java:6089)
  E/ViewRootImpl(19244):    at android.view.View.unFocus(View.java:6122)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.unFocus(ViewGroup.java:997)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4946)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.removeAllViews(ViewGroup.java:4905)
  E/ViewRootImpl(19244):    at
  com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:410)
  E/ViewRootImpl(19244):    at
  android.app.Activity.setContentView(Activity.java:2423)
  E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer.nativeRender(Native Method)
  E/ViewRootImpl(19244):    at com.unity3d.player.UnityPlayer.a(Unknown
  Source) E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer$c$1.handleMessage(Unknown Source)
  E/ViewRootImpl(19244):    at
  android.os.Handler.dispatchMessage(Handler.java:98)
  E/ViewRootImpl(19244):    at android.os.Looper.loop(Looper.java:173)
  E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer$c.run(Unknown Source)

Summary

As i mentioned before, this only gives you a direction where to look. Hopefully you'll be able to find potential locations that can be the cause of this (probably plugin code). I'd be happy to further assist (in the comments, or feel free to contact me).

Body:
We get error reports from Crashlytics affecting a sizable portion of our users (around 10% of them). It's a CalledFromWrongThreadException.

The problem is I don't know what's causing the issue and I don't have it myself. Here is the log:

Caused by android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
       at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7282)
       at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1197)
       at android.view.ViewGroup.invalidateChild(ViewGroup.java:5748)
       at android.view.View.invalidateInternal(View.java:15082)
       at android.view.View.invalidate(View.java:15046)
       at android.view.View.invalidate(View.java:15029)
       at android.view.SurfaceView$1.handleMessage(SurfaceView.java:142)
       at android.os.Handler.dispatchMessage(Handler.java:105)
       at android.os.Looper.loop(Looper.java:164)
       at com.unity3d.player.UnityPlayer$c.run(Unknown Source:20)

The com.unity3d.player.UnityPlayer$c.run(Unknown Source:20) is not really helpfull here as the origin is unknown, I guess it could come from a third party library (GVR SDK, Fabric...).

Does anyone have the same issue?

For reference we are using Unity version : 5.6.0f3 and the bug is reported only for Pixel and Pixel XL phones.

Body:
I don't have all the details about your project, and the errors that cannot be reproduced in-house are the worst kind. Nevertheless, I'll try to give a few hints as to what's going on. Perhaps these hints can shed some light and help you figure out the root cause of error:

CalledFromWrongThreadException

On Android, a View can only be accessed from the thread that created it. This is actually true for other environments as well (WinForms, WPF, etc). This exception means that something is trying to access some UI element (SurfaceView) from the wrong thread.

com.unity3d.player.UnityPlayer$c.run

The stack trace originates from some custom Unity plumbing code. While this doesn't give a clue where this call comes from (in your C# code), it might mean the code came from C# (using AndroidJavaObject or AndroidJavaClass calls). Unity's scripting thread is not the same as Android's main thread, and so this makes sense together with the exception type you're getting.

As a test, i've used this code to simulate the same exception:

using (var actClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
    var activity = actClass.GetStatic<AndroidJavaObject>("currentActivity");

    // cause an exception to be thrown
    activity.Call("setContentView", 15);
}

This resulted in the following exception, which is very similar to the one you're getting (at least at its root).

E/ViewRootImpl(19244): com.test.crash.GameActivity : Only the original
  thread that created a view hierarchy can touch its views.
  E/ViewRootImpl(19244): java.lang.RuntimeException
  E/ViewRootImpl(19244):    at
  android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7105)
  E/ViewRootImpl(19244):    at
  android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1139)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.invalidateChild(ViewGroup.java:5254)
  E/ViewRootImpl(19244):    at
  android.view.View.invalidateInternal(View.java:13669)
  E/ViewRootImpl(19244):    at
  android.view.View.invalidate(View.java:13633) E/ViewRootImpl(19244):
    at android.view.View.onFocusChanged(View.java:6204)
  E/ViewRootImpl(19244):    at
  android.view.View.clearFocusInternal(View.java:6089)
  E/ViewRootImpl(19244):    at android.view.View.unFocus(View.java:6122)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.unFocus(ViewGroup.java:997)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4946)
  E/ViewRootImpl(19244):    at
  android.view.ViewGroup.removeAllViews(ViewGroup.java:4905)
  E/ViewRootImpl(19244):    at
  com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:410)
  E/ViewRootImpl(19244):    at
  android.app.Activity.setContentView(Activity.java:2423)
  E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer.nativeRender(Native Method)
  E/ViewRootImpl(19244):    at com.unity3d.player.UnityPlayer.a(Unknown
  Source) E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer$c$1.handleMessage(Unknown Source)
  E/ViewRootImpl(19244):    at
  android.os.Handler.dispatchMessage(Handler.java:98)
  E/ViewRootImpl(19244):    at android.os.Looper.loop(Looper.java:173)
  E/ViewRootImpl(19244):    at
  com.unity3d.player.UnityPlayer$c.run(Unknown Source)

Summary

As i mentioned before, this only gives you a direction where to look. Hopefully you'll be able to find potential locations that can be the cause of this (probably plugin code). I'd be happy to further assist (in the comments, or feel free to contact me).


问:
speed of parsing json structures
I want to make a simple database system, amd possibly use JSON as the main data format for importing and exporting (including full database backups) . So my question is: how fast is it to parse JSON, even from big JSON structures (think gigabytes), in comparison to speed when importing from other systems (like (faster) binary files, or (slower) XML)?

EDIT: to clarify, I am wondering how fast it is to parse JSON (into some internal database format), but not how fast it would be as an internal storage mechanism.
So this JSON data would not be queried etc., but just parsed into another format.

Also, my main intent asking this question is I am wondering if JSON is any easier to parse than XML because of smaller delimiters (']' or '}' instead of '' or ''), and if it is maybe even similar in speed to binary formats because of the quite simple delimiters.
(For example, maybe json can be parsed something like this: record delimiter = ascii code xx (xx being a brace or bracket) except where preceded by ascii xx (xx being some escape char).)

答:
It's definitely much, much slower than MySQL (for a server) or SQLite (for a client) which are preferrable.

Also, JSON speed depends almost solely on the implementation. For instance, you could eval() it, but not only that is very risky, it's also slower than a real parser. At any rate, there are probably much better optimized XML parsers than JSON parsers, just because it's a more used format. (So grab a GB-sized XML and imagine the same results but slower).

Seriously, JSON was never meant for big things. Use a real database if possible.

Edit: why is JSON much slower than a database?

Many reasons. I'll try to list a few.

JSON relies on matching sections such as {}s (much like XML's <>s)

This means a parser has to check where's the ending to an object block. There are other of these such as []s and ""s. In a conventional database there's no "ending tag" or "ending bracket" so it's easier to read.

JSON parsers need to read each and every character before being able to understand the whole object structure.

So before you can even read some of the JSON you have to read the whole file. This means waiting a few minutes at best for the sizes you mentioned, and a database is ready to be queried in less than a second (because the hierarchy is stored at the beginning).

In JSON you can't precalculate offsets.

In a database, size is traded for performance. You can make VARCHAR(512) and all strings will be null-padded to occupy 512 bytes. Why? Because that way you can know the 4th value is at offset 2048 for example. You can't do that with JSON hence performance suffers.

JSON is optimized for small filesizes.

...Because it's a web format.

This may look like a pro but it's a con from a performance perspective.

JSON is a JavaScript subset.

So some parsers might allow unnecessary data to be present and considered, such as comments. Chrome's native JSON used to allow comments for example (not anymore).

No database engine uses eval() right?

JSON is meant to have some error resilience.

People might put anything into a JSON file, so parsers are defensive and try to read invalid files sometimes. Database aren't supposed to repair a broken file silently.

You might hand-code a JSON but not a database!

JSON is a new, unsupported and badly tested format

There are bugs in some native parsers (like IE8's) and support for most browsers is very preliminary and slower than, say, the fastest XML parser out there. Simply because XML was being used for ages and Steve Ballmer has an XML fetish so companies please him by making almost anything under the sun XML-compatible. While JSON is one of Crockford's successful weekend pasttimes.

The best JSON parsers are in browsers

If you pick one random open-source JSON parser for your favourite language, what chances are that it's the best possible parser under the sun? Well, for XML you do have awesome parsers like this But what is there for JSON?

Need more reasons why JSON should be relegated to its intended use case?

ContentLicense: CC BY-SA 4.0

Title: speed of parsing json structures

ContentLicense: CC BY-SA 2.5


问:
CSS: wrapping around text inside a drawn circle using CSS
I am using this CSS code to draw circles:

```<code>circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}
</code>```

Using this in html I can draw 3 circles side-by-side with text inside them:

```<code> <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>
</code>```

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

```<code><circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>
</code>```

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

答:
The line-height is causing this. I've adjusted your CSS.

circle span {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 90px;
}
circle {
  background: #f00;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
  margin: 5px;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><circle><span>Text 1</span></circle>
<circle><span>Text 2 and more</span></circle>
<circle><span>Text 3</span></circle></code>```

Body:
I am using this CSS code to draw circles:

circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}

Using this in html I can draw 3 circles side-by-side with text inside them:

 <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

<circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

Body:
The line-height is causing this. I've adjusted your CSS.

circle span {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 90px;
}
circle {
  background: #f00;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
  margin: 5px;
  position: relative;
}

<circle><span>Text 1</span></circle>
<circle><span>Text 2 and more</span></circle>
<circle><span>Text 3</span></circle>


问:
How to install Gulp v4 with NPM v5?
I've installed the new version of npm but now when I try to run the next command the dependency doesn't install:

```<code>npm i -S gulpjs/gulp#4.0

npm ERR! code ETARGET
npm ERR! notarget No matching version found for undefined@4.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
</code>```

NPM Version: v5.0.1

Is there a new way to install npm packages from github branches?

Related question (old NPM version): Depend on a branch or tag using a git URL in a package.json?

NPM Docs about install dependencies: npm install docs

答:
This was a bug fixed in v5.0.2

Related github issue

Title: How to install Gulp v4 with NPM v5?

Body:
I've installed the new version of npm but now when I try to run the next command the dependency doesn't install:

npm i -S gulpjs/gulp#4.0

npm ERR! code ETARGET
npm ERR! notarget No matching version found for undefined@4.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

NPM Version: v5.0.1

Is there a new way to install npm packages from github branches?

Related question (old NPM version): Depend on a branch or tag using a git URL in a package.json?

NPM Docs about install dependencies: npm install docs


问:
Convert a JSON string to Dictionary in Swift 3
as a coding exercise, I wrote a small program to take MySql data frm the web to the iPhone. On the server side. I wrote the php script to get the script to return the json data.

On xcode I have

```<code>[code]
.
.
.
     let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
    print(jsonString!)
    .
    .
    .
[/code]
</code>```

In xcode console, I have this:

```<code>[code]
(
        {
        Address = "1 Infinite Loop Cupertino, CA";
        Latitude = "37.331741";
        Longitude = "-122";
        Name = Apple;
    }
)
[/code]

I have a function
    [code]

func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                }
            }
            return nil
        }
[/code]
</code>```

When I pass the jsonString to convertToDictionary(text:)

```<code>[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]
</code>```

In the console I get an error "Could not cast value of type '__NSSingleObjectArrayI' (0x10369bdb0) to 'NSString' (0x1004eac60)."

but if I hard code the json string then pass it to the convertToDictionary(text:)

```<code>[code]
let hardCodedStr = "{\"Address\":\"1 Infinite Loop Cupertino, CA\",\"Latitude\":\"37.331741\",\"Longitude\":\"-122\",\"Name\":\"Apple\"}"

let dict = convertToDictionary(text: hardCodedStr)
print(dict!)
[/code]
</code>```

It works just fine. Why is that? Thanks

答:
If you look closely at what jsonObject(with:options:) returns, you will see that it is a [String: Any] or a [Any], depending on your JSON.

Therefore, jsonString here actually stores a [String: Any], even thought the compiler thinks it is of type Any:

```<code>let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
print(jsonString!)
</code>```

If you try to pass this to convertToDictionary, which accepts a String, it of course will not work, because a dictionary and String are not compatible types.

How to solve this problem?

The problem is already solved! You don't need convertToDictionary at all. jsonString itself is the dictionary you wanted.

This is what you need to do:

```<code>let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                                                                             ^^^^^^^^^^^^^^^^^
                                                                             Add this part
</code>```

After that you can call dictionary methods on jsonString. I also suggest you to rename jsonString to something else.

Body:
as a coding exercise, I wrote a small program to take MySql data frm the web to the iPhone. On the server side. I wrote the php script to get the script to return the json data.

On xcode I have

[code]
.
.
.
     let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
    print(jsonString!)
    .
    .
    .
[/code]

In xcode console, I have this:

[code]
(
        {
        Address = "1 Infinite Loop Cupertino, CA";
        Latitude = "37.331741";
        Longitude = "-122";
        Name = Apple;
    }
)
[/code]

I have a function
    [code]

func convertToDictionary(text: String) -> [String: Any]? {
            if let data = text.data(using: .utf8) {
                do {
                    return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                } catch {
                    print(error.localizedDescription)
                }
            }
            return nil
        }
[/code]

When I pass the jsonString to convertToDictionary(text:)

[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]

In the console I get an error "Could not cast value of type '__NSSingleObjectArrayI' (0x10369bdb0) to 'NSString' (0x1004eac60)."

but if I hard code the json string then pass it to the convertToDictionary(text:)

[code]
let hardCodedStr = "{\"Address\":\"1 Infinite Loop Cupertino, CA\",\"Latitude\":\"37.331741\",\"Longitude\":\"-122\",\"Name\":\"Apple\"}"

let dict = convertToDictionary(text: hardCodedStr)
print(dict!)
[/code]

It works just fine. Why is that? Thanks

Body:
If you look closely at what jsonObject(with:options:) returns, you will see that it is a [String: Any] or a [Any], depending on your JSON.

Therefore, jsonString here actually stores a [String: Any], even thought the compiler thinks it is of type Any:

let jsonString = try? JSONSerialization.jsonObject(with: data!, options:    [])
print(jsonString!)

If you try to pass this to convertToDictionary, which accepts a String, it of course will not work, because a dictionary and String are not compatible types.

How to solve this problem?

The problem is already solved! You don't need convertToDictionary at all. jsonString itself is the dictionary you wanted.

This is what you need to do:

let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                                                                             ^^^^^^^^^^^^^^^^^
                                                                             Add this part

After that you can call dictionary methods on jsonString. I also suggest you to rename jsonString to something else.


答:
You need to join the two tables:</p>

```<code>SELECT
    S.SaleItemID,
    Format(SUM(R.RecItemQty), "###,##0.00")AS 'Received'
    Format(SUM(S.SaleItemQty), "###,##0.00")AS 'Quantity',
    Format(SUM(S.SaleItemPrice), "###,##0.00")AS 'Amount',
    S.SaleItemDate
 FROM Items_Sales S
 INNER JOIN Items_Rec R
    ON S.SaleItemID = R.RecItemID
    AND S.SalesItemDate = R.RecItemDate
 GROUP BY S.SaleItemID,S.SaleItemDate
</code>```

Title: Query sum other table field and grouping

Body:
I  have a query that sum the item sales by day (Grouping)
but i need now to include in this query the recibed sum quantity by day in the same query
but this field is in other table

this is the representation of the two tables

SALES TABLE named "Item_Sales"

+------------+-------------+---------------+----------------+
| SaleItemID | SaleItemQty | SaleItemPrice |  SaleItemDate  |
+------------+-------------+---------------+----------------+
|     51026  |       18.00 |         11.31 |     07/01/1016 |
+------------+-------------+---------------+----------------+
|     14309  |        7.00 |         22.35 |     07/01/2016 |
+------------+-------------+---------------+----------------+
|     51026  |        6.00 |         11.31 |     07/01/2016 |
+------------+-------------+---------------+----------------+
|     51026  |       10.00 |         11.31 |     07/02/2016 |
+------------+-------------+---------------+----------------+
|     14309  |       14.00 |         22.35 |     07/02/2016 |
+------------+-------------+---------------+----------------+
|     14309  |        9.00 |         22.35 |     07/02/2016 |
+------------+-------------+---------------+----------------+

Recibed Items Table named "Items_Rec"

+-----------+------------+--------------+---------------+
| RecItemID | RecItemQty | RecItemPrice |  RecItemDate  |
+-----------+------------+--------------+---------------+
|    51026  |      10.00 |        11.31 |    07/01/1016 |
+-----------+------------+--------------+---------------+
|    14309  |       5.00 |        22.35 |    07/01/2016 |
+-----------+------------+--------------+---------------+
|    51026  |       5.00 |        11.31 |    07/01/2016 |
+-----------+------------+--------------+---------------+
|    51026  |      10.00 |        11.31 |    07/02/2016 |
+-----------+------------+--------------+---------------+
|    14309  |       5.00 |        22.35 |    07/02/2016 |
+-----------+------------+--------------+---------------+
|    14309  |       5.00 |        22.35 |    07/02/2016 |
+-----------+------------+--------------+---------------+

i have this query but i need to include the RecItemQty SUM From the ITEMS_REC table

SELECT
   S.SaleItemID,
   Format(SUM(S.SaleItemQty), "###,##0.00")AS 'Quantity',
   Format(SUM(S.SaleItemPrice), "###,##0.00")AS 'Amount',
   S.SaleItemDate
FROM Items_Sales
GROUP BY S.SaleItemID,S.SaleItemDate

And this is the result that i need

+------------+-------------+------------+--------------+----------------+
| SaleItemID | SaleItemQty | RecItemQty |SaleItemPrice |  SaleItemDate  |
+------------+-------------+------------+--------------+----------------+
|     51026  |       24.00 |      15.00 |        11.31 |     07/01/1016 |
+------------+-------------+------------+--------------+----------------+
|     14309  |        7.00 |       5.00 |        22.35 |     07/01/1016 |
+------------+-------------+------------+--------------+----------------+
|     51026  |       10.00 |      10.00 |        11.31 |     07/02/1016 |
+------------+-------------+------------+--------------+----------------+
|     14309  |       23.00 |      10.00 |        22.35 |     07/02/1016 |
+------------+-------------+------------+--------------+----------------+

THANKS!!

Body:
You need to join the two tables:

SELECT
    S.SaleItemID,
    Format(SUM(R.RecItemQty), "###,##0.00")AS 'Received'
    Format(SUM(S.SaleItemQty), "###,##0.00")AS 'Quantity',
    Format(SUM(S.SaleItemPrice), "###,##0.00")AS 'Amount',
    S.SaleItemDate
 FROM Items_Sales S
 INNER JOIN Items_Rec R
    ON S.SaleItemID = R.RecItemID
    AND S.SalesItemDate = R.RecItemDate
 GROUP BY S.SaleItemID,S.SaleItemDate


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
perl with the autosplit switch:

```<code>perl -anE'say join " ", map {/(?:0x)?([0-9a-f]{5,})/i ? hex $1 : $_} @F' file | column -t
</code>```

The -n switch provides an implicit loop over the lines of the file.

The -E switch makes available optional features like the say command (useful to print something with an automatic carriage return). -E does also the same thing that the -e switch that executes the code given in parameter (instead of looking for a file to launch).

The -a switch (autosplit) splits each line on whitespace and populates the @F array with the parts (like awk does).

map { } @F processes each elements of @F and returns a new array.

/(?:0x)?([0-9a-f]{5,})/i ? hex($1) : $_ uses the ternary operator condition ? true : false. When the pattern matches it returns the converted capture group 1, when it doesn't the original part.

Note that Perl is a language that takes account of the context. $_ inside the map {} refers to a @F item, and /(?:0x)?([0-9a-f]{5,})/i is the short version for $_ =~ /(?:0x)?([0-9a-f]{5,})/i. (outside of the map {} $_ is the current line)

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
perl with the autosplit switch:

perl -anE'say join " ", map {/(?:0x)?([0-9a-f]{5,})/i ? hex $1 : $_} @F' file | column -t

The -n switch provides an implicit loop over the lines of the file.

The -E switch makes available optional features like the say command (useful to print something with an automatic carriage return). -E does also the same thing that the -e switch that executes the code given in parameter (instead of looking for a file to launch).

The -a switch (autosplit) splits each line on whitespace and populates the @F array with the parts (like awk does).

map { } @F processes each elements of @F and returns a new array.

/(?:0x)?([0-9a-f]{5,})/i ? hex($1) : $_ uses the ternary operator condition ? true : false. When the pattern matches it returns the converted capture group 1, when it doesn't the original part.

Note that Perl is a language that takes account of the context. $_ inside the map {} refers to a @F item, and /(?:0x)?([0-9a-f]{5,})/i is the short version for $_ =~ /(?:0x)?([0-9a-f]{5,})/i. (outside of the map {} $_ is the current line)


问:
java.lang.NullPointerException when using adb to deploy apk to Android N phone
I have an AndroidStudio project, which was originally able to deploy to my phone via adb.

But after I updated the phone to Android N, I could no longer use adb to deploy it.

```<code>$ adb install app-release.apk
Failed to install app-release.apk:
Exception occurred while dumping:
java.lang.NullPointerException: rhs == null
    at java.lang.String.compareTo(Native Method)
    at java.lang.String.compareTo(String.java:1082)
    at java.util.Collections.indexedBinarySearch(Collections.java:299)
    at java.util.Collections.binarySearch(Collections.java:286)
    at com.android.server.pm.Settings.isInApp2sdBlacklist(Settings.java:5622)
    at com.android.server.pm.PackageManagerService.isInApp2sdBlacklist(PackageManagerService.java:21454)
    at android.app.ApplicationPackageManager.isInApp2sdBlacklist(ApplicationPackageManager.java:2534)
    at com.android.internal.content.PackageHelper.resolveInstallVolume(PackageHelper.java:416)
    at com.android.server.pm.PackageInstallerService.createSessionInternal(PackageInstallerService.java:647)
    at com.android.server.pm.PackageInstallerService.createSession(PackageInstallerService.java:566)
    at com.android.server.pm.PackageManagerShellCommand.doCreateSession(PackageManagerShellCommand.java:1141)
    at com.android.server.pm.PackageManagerS
</code>```

What could be the problem?

I have googled the error messsage and had no clue. Also, how to read this error message? It seems like the error is inside Android library or inside java library. (Is it because I updated java to a higher version?)

答:
If you encounter the same problem

You could try following procedures, then maybe you'll figure out what your own problem is.

Generate an .apk file. (Use your AndroidStudio or whatever.)

cd the\folder\containing\apk

adb push  name_of_the.apk  path\on\the\mobile\phone\storage\

Manipulate the phone and manually install the .apk by clicking on the .apk file icon.

The answer to my problem

Although adb install failed on my devices (as the problem statement describes), adb push(step 3 above) worked.

And after I did the step 4 above, an unexpected screen emerged.

It says, 'The system is scanning malicious software.'

So that's the answer to my problem. After I upgraded my phone to Android N version, the system has been added an automated software scanning, which will be triggered even if you're using developer mode and using adb.

And the error message didn't show anything of the clue. The error message just says java.lang.NullPointerException: rhs == null which is in no way related.

Methods I tried but didn't work

Disable instant run in AndroidStudio.

Settings>Build, Execution, Deployment >Instant Run

adb root, adb disable-verity, adb reboot, adb root, adb remount

https://android.stackexchange.com/questions/162902/adb-push-not-working-on-system-read-only

Body:
I have an AndroidStudio project, which was originally able to deploy to my phone via adb.

But after I updated the phone to Android N, I could no longer use adb to deploy it.

$ adb install app-release.apk
Failed to install app-release.apk:
Exception occurred while dumping:
java.lang.NullPointerException: rhs == null
    at java.lang.String.compareTo(Native Method)
    at java.lang.String.compareTo(String.java:1082)
    at java.util.Collections.indexedBinarySearch(Collections.java:299)
    at java.util.Collections.binarySearch(Collections.java:286)
    at com.android.server.pm.Settings.isInApp2sdBlacklist(Settings.java:5622)
    at com.android.server.pm.PackageManagerService.isInApp2sdBlacklist(PackageManagerService.java:21454)
    at android.app.ApplicationPackageManager.isInApp2sdBlacklist(ApplicationPackageManager.java:2534)
    at com.android.internal.content.PackageHelper.resolveInstallVolume(PackageHelper.java:416)
    at com.android.server.pm.PackageInstallerService.createSessionInternal(PackageInstallerService.java:647)
    at com.android.server.pm.PackageInstallerService.createSession(PackageInstallerService.java:566)
    at com.android.server.pm.PackageManagerShellCommand.doCreateSession(PackageManagerShellCommand.java:1141)
    at com.android.server.pm.PackageManagerS

What could be the problem?

I have googled the error messsage and had no clue. Also, how to read this error message? It seems like the error is inside Android library or inside java library. (Is it because I updated java to a higher version?)


问:
Will installing ruby slow down my vps?
I have a vps that's running mostly php sites.

I want to install ruby. Will installing ruby but not doing much with it take away resources from the php sites?

Thanks

答:
No. I assume you're talking about mod_ruby or similar - in this case there will be a few megabytes or so added to the Apache (or otherwise) process, but unless you're actively using it it'll stay out of the way. If you're running Ruby as CGI scripts, Ruby won't even be in play until somebody requests a .rb file in a CGI configured directory.

But you don't need to take our word for it. You can always try it yourself and see if it causes any problems. I don't expect so, though.

Title: Will installing ruby slow down my vps?


问:
Separate data provider from test case class
I want to use PHPUnit to test my PHP class.

Is it possible to put data providers for my test methods in a separate file created only for storing dataproviders? If so how to do that?

Another question is whether it's a good practice or perhaps it's better to keep test and data provider methods in the same test class.

答: Simply use @dataProvider class::method to use a method from a different class than the test case class as a data provider for a test.


问:
Integrating jQuery plugin calls inside AngularJS Directives
I've been working on converting a plain static website into an AngularJS website - just to also improve my skills on that.

So far, I've done routes and looking good so far.

Now on the home page, I made slider images load using ng-repeat directive and it's also working. But I noticed something that the slider itself isn't working its supposed functionality. So I found out that the jQuery functions I made on a separate js file isn't loading at all. And I also found out that this can be achieved by integrating the plugin calls inside a directive.

So, I made this:

```<code>app.directive('featuredSlider', [function() {
return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
        $(elem).owlCarousel({
            itemsCustom: [
                [0, 1],
                [600, 2],
                [1200, 4]
            ],
            autoPlay: 3000
        });
    }
};}]);
</code>```

I'm using OwlCarousel for the slider and it's not being triggered using the one I did above.

By the way, this is how my controller look like:

```<code>app.controller('HomeController', function($scope) {
$scope.featuredImages = []; }
</code>```

The featuredImages array above has the image URLs for the slider.

And then, this is the part where the slider is.

```<code><div class = "featured owl-carousel owl-theme featured-slider">
     <div class = "item" ng-repeat = "featured in featuredImages">
       <img ng-src = "{{featured.img}}" />
     </div>
</div>
</code>```

Anyone who can help me out? I've tried out several methods but still not showing up and working.

答:
Create the dependency in this way:
f.e:

```<code>//Import moment.js into your page as always
<script type="text/javascript"
        src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.js"/>

//Before your main app module is declared, declare a momentjs module
angular.module('momentjs',[])
  //And on the momentjs module, declare the moment service that we want
  // available as an injectable
  .factory('moment', function ($window) {
    if($window.moment){
      //Delete moment from window so it's not globally accessible.
      //  We can still get at it through _thirdParty however, more on why later
      $window._thirdParty = $window._thirdParty || {};
      $window._thirdParty.moment = $window.moment;
      try { delete $window.moment; } catch (e) {$window.moment = undefined;
      /*<IE8 doesn't do delete of window vars, make undefined if delete error*/}
    }
    var moment = $window._thirdParty.moment;
    return moment;
  });
</code>```

and then put the directive in this way to assign their own controller:

```<code> angular.module("example").directive('exampleDirective', [function () {
    return {
        templateUrl: 'path',
        restrict: 'AE',
        transclude:true,
        controller: 'myDirectiveController'
    };
 }]).controller('myDirectiveController',myDirectiveController);

 function myDirectiveController($scope , $element, $attrs, moment ) {
        //and now you can use this thir party library in the directive controller.
    }
</code>```

Body:
I've been working on converting a plain static website into an AngularJS website - just to also improve my skills on that.

So far, I've done routes and looking good so far.

Now on the home page, I made slider images load using ng-repeat directive and it's also working. But I noticed something that the slider itself isn't working its supposed functionality. So I found out that the jQuery functions I made on a separate js file isn't loading at all. And I also found out that this can be achieved by integrating the plugin calls inside a directive.

So, I made this:

app.directive('featuredSlider', [function() {
return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
        $(elem).owlCarousel({
            itemsCustom: [
                [0, 1],
                [600, 2],
                [1200, 4]
            ],
            autoPlay: 3000
        });
    }
};}]);

I'm using OwlCarousel for the slider and it's not being triggered using the one I did above.

By the way, this is how my controller look like:

app.controller('HomeController', function($scope) {
$scope.featuredImages = []; }

The featuredImages array above has the image URLs for the slider.

And then, this is the part where the slider is.

Anyone who can help me out? I've tried out several methods but still not showing up and working.

Body:
Create the dependency in this way:
f.e:

//Import moment.js into your page as always
<script type="text/javascript"
        src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.js"/>

//Before your main app module is declared, declare a momentjs module
angular.module('momentjs',[])
  //And on the momentjs module, declare the moment service that we want
  // available as an injectable
  .factory('moment', function ($window) {
    if($window.moment){
      //Delete moment from window so it's not globally accessible.
      //  We can still get at it through _thirdParty however, more on why later
      $window._thirdParty = $window._thirdParty || {};
      $window._thirdParty.moment = $window.moment;
      try { delete $window.moment; } catch (e) {$window.moment = undefined;
      /*<IE8 doesn't do delete of window vars, make undefined if delete error*/}
    }
    var moment = $window._thirdParty.moment;
    return moment;
  });

and then put the directive in this way to assign their own controller:

 angular.module("example").directive('exampleDirective', [function () {
    return {
        templateUrl: 'path',
        restrict: 'AE',
        transclude:true,
        controller: 'myDirectiveController'
    };
 }]).controller('myDirectiveController',myDirectiveController);

 function myDirectiveController($scope , $element, $attrs, moment ) {
        //and now you can use this thir party library in the directive controller.
    }


问:
Create dynamic switchery
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

```<code>var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);
</code>```

my Html codes:

```<code><script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia"></div>
</code>```

答:
The button code you're replacing the string with should be a string, not a jquery object.

var count = 3;
$("#btn").click(function() {
  CreateInlineChildWithSwitchery(count);
});

function CreateInlineChildWithSwitchery(countOfChilds) {

  var Integer_LastSwitcheryId = count;

  var btn = '<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">';
  console.log(btn)
  console.log($('#tpl').html())
  $('#all-encyclopedia').append(
    $("#tpl").html()
    .replace(/{switchery}/g, btn)
  );

  eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch" + Integer_LastSwitcheryId.toString() + "')");

  eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

  eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change" + Integer_LastSwitcheryId.toString() + "')");

  eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field" + Integer_LastSwitcheryId.toString() + "')");

}

for (i = 1; i < 4; i++)
  CreateInlineChildWithSwitchery(count++);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://alireza-salehi.ir/switchery/switchery.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://alireza-salehi.ir/switchery/switchery.js"></script>
<script type="text/tpl" id="tpl">
  {switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia">

</div></code>```

Title: Create dynamic switchery

Body:
I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code
Visit jsfiddle.net/eu3a0k3m/2/

my js codes:

var count = 3;
$("#btn").click(function(){
    CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){

      var Integer_LastSwitcheryId = count;

      var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
        $("#tpl ").html()
                                  .replace(/{switchery}/g,btn)
      );

      eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");

      eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

      eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");

      eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");

  }

  for(i=1;i<4;i++)
      CreateInlineChildWithSwitchery(count++);

my Html codes:

<button id="btn">insert Switchery</button>

Body:
The button code you're replacing the string with should be a string, not a jquery object.

var count = 3;
$("#btn").click(function() {
  CreateInlineChildWithSwitchery(count);
});

function CreateInlineChildWithSwitchery(countOfChilds) {

  var Integer_LastSwitcheryId = count;

  var btn = '<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">';
  console.log(btn)
  console.log($('#tpl').html())
  $('#all-encyclopedia').append(
    $("#tpl").html()
    .replace(/{switchery}/g, btn)
  );

  eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch" + Integer_LastSwitcheryId.toString() + "')");

  eval("switchery" + Integer_LastSwitcheryId.toString() + "={elem" + Integer_LastSwitcheryId.toString() + ",  color: '#1AB394',secondaryColor: '#688ab0'}");

  eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change" + Integer_LastSwitcheryId.toString() + "')");

  eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field" + Integer_LastSwitcheryId.toString() + "')");

}

for (i = 1; i < 4; i++)
  CreateInlineChildWithSwitchery(count++);

<link href="https://alireza-salehi.ir/switchery/switchery.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://alireza-salehi.ir/switchery/switchery.js"></script>
<script type="text/tpl" id="tpl">
  {switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia">

</div>


问:
Which one is best: Apache Ambari cluster on Physical system with 5 Machine or install on virtual machine with diffrent 5 VM?
Hi I am working on One of my project which I have created VM of 5 Machine and it is working fine in development environment but I have some confusion regarding VM cluster is good or need to go with physical system cluster.</p>

答:
Hadoop was developed for physical systems but it will function with varying degrees of success in virtual environments, it depends on the specific environment.

This is actually quite a common question on the hadoop mailing lists and was specifically addressed by the Hadoop developers on the Hadoop Wiki article: Virtual Hadoop. The article covers the strengths/weaknesses of each and talks about cloud deployments as well. You should read this article and see which deployment scenario you fall in to and assess what issues you may potentially have in your VM setup.


问:
how to use a .net dll with static utility functions in unity 5?
I have a .NET 3.5 .dll build with VS2015 that contains some static utility functions and has no further dependencies. What I want to achieve is to use those utility functions in a C# Script in my Unity 5.5 (personal edition) project.

I dragged the .dll into the assets browser and created a new C# Script. Unfortunately there was no automatic reference to the .dll, and I wasn't able to find any possibility to add one.

This is what unity shows when doubleclicking on the dll:

How can I use my (not in any way to Unity related) dll in my Unity C# Script?

答:
Unity runs on Mono not on .NET - that's different things.

Use one of Unity target frameworks (set in VS project properties) when compiling dll outside Unity environment or use PInvoke.

Put dll file into "Plugins" folder.


问:
How can one pass a date to CloudKit via CK Web Services from a PHP script?
I am writing a PHP script to send data to a CloudKit database via CK Web Services. It works well with string data, but I am having trouble passing a date from PHP to a CK Date/Time field.

CK returns dates as a 13-digit TIMESTAMP. So, the following code

```<code>$timestamp = $record['created']['timestamp'];
$timestamp = $timestamp/1000;
echo '<td>'.date('m-d-Y H:i:s', $timestamp)."</td>";
</code>```

echoes out

04-28-2017 12:35:19

Fine and dandy.

So I make the assumption that if CK delivers a 13-digit TIMESTAMP it should accept the same when passed to a Date/Time field.

Alas, passing $dobTimestamp from the following

```<code>$dobTimestamp = strtotime($dob) * 1000;
</code>```

Results in this BAD_REQUEST error

Invalid value, expected type TIMESTAMP

When I go to the CK Dashboard and manually enter $dob, CK returns a value exactly equal to $dobTimestamp so I think passing $dobTimestamp should work . . . but it does not.

I cannot find out what I am supposed to do in Apple's docs. Does anyone know how to pass a date to a CK Date/Time field via Web Services? Hard to imagine there would not be a way to do it.

答:
After a lot of fiddles, here's what works using PHP DateTime:

```<code>$openingDate = $_POST['openingDate']; // is mm/dd/yyyy
$closingDate = $_POST['closingDate'];
</code>```

. . .

```<code>// Process Dates
$openingDateTime = new DateTime($openingDate, new DateTimeZone('America/New_York'));  // Create new DateTime object
$closingDateTime = new DateTime($closingDate, new DateTimeZone('America/New_York'));

date_time_set($openingDateTime, 10, 00); // Set time for date object
date_time_set($closingDateTime, 17, 00); // Set time for date object

$oDate = (date_timestamp_get($openingDateTime)*1000);  // Get the TIMESTAMP from DateTiem object and convert to milliseconds
$cDate  = (date_timestamp_get($closingDateTime)*1000);
</code>```

The JSON for the CK Query is simple:

. . .

```<code>"openingDate": {"value":'.$oDate.'},
"closingDate": {"value":'.$cDate.'},
</code>```

Body:
I am writing a PHP script to send data to a CloudKit database via CK Web Services. It works well with string data, but I am having trouble passing a date from PHP to a CK Date/Time field.

CK returns dates as a 13-digit TIMESTAMP. So, the following code

$timestamp = $record['created']['timestamp'];
$timestamp = $timestamp/1000;
echo ''.date('m-d-Y H:i:s', $timestamp)."	";

echoes out

04-28-2017 12:35:19

Fine and dandy.

So I make the assumption that if CK delivers a 13-digit TIMESTAMP it should accept the same when passed to a Date/Time field.

Alas, passing $dobTimestamp from the following

$dobTimestamp = strtotime($dob) * 1000;

Results in this BAD_REQUEST error

Invalid value, expected type TIMESTAMP

When I go to the CK Dashboard and manually enter $dob, CK returns a value exactly equal to $dobTimestamp so I think passing $dobTimestamp should work . . . but it does not.

I cannot find out what I am supposed to do in Apple's docs. Does anyone know how to pass a date to a CK Date/Time field via Web Services? Hard to imagine there would not be a way to do it.

Body:
After a lot of fiddles, here's what works using PHP DateTime:

$openingDate = $_POST['openingDate']; // is mm/dd/yyyy
$closingDate = $_POST['closingDate'];

. . .

// Process Dates
$openingDateTime = new DateTime($openingDate, new DateTimeZone('America/New_York'));  // Create new DateTime object
$closingDateTime = new DateTime($closingDate, new DateTimeZone('America/New_York'));

date_time_set($openingDateTime, 10, 00); // Set time for date object
date_time_set($closingDateTime, 17, 00); // Set time for date object

$oDate = (date_timestamp_get($openingDateTime)*1000);  // Get the TIMESTAMP from DateTiem object and convert to milliseconds
$cDate  = (date_timestamp_get($closingDateTime)*1000);

The JSON for the CK Query is simple:

. . .

"openingDate": {"value":'.$oDate.'},
"closingDate": {"value":'.$cDate.'},


问:
purescript anonymous function arguments on nested records?
Is it possible to apply anonymous function arguments to nested records somehow in the followign way?

```<code>type UName = {fname :: String, lname :: String}
type XName = { xname :: UName, addr :: String}

updateU = _ { xname : { fname : _ } } -- not ok
-- or
updateU = _ { xname.fname = _ } -- not ok
-- or
updateU = _ { xname : fname = _ } } -- not ok
</code>```

Above trials say that context is invalid. Aim is to implement:

```<code>updateU = \x ->  { xname : { fname : x } }
</code>```

答:
The shortest version uses nested record updates and looks like this:</p>

```<code>updateU :: XName -> String -> XName
updateU = _ { xname { fname = _ } }
</code>```

Body:
Is it possible to apply anonymous function arguments to nested records somehow in the followign way?

type UName = {fname :: String, lname :: String}
type XName = { xname :: UName, addr :: String}

updateU = _ { xname : { fname : _ } } -- not ok
-- or
updateU = _ { xname.fname = _ } -- not ok
-- or
updateU = _ { xname : fname = _ } } -- not ok

Above trials say that context is invalid. Aim is to implement:

updateU = \x ->  { xname : { fname : x } }

Body:
The shortest version uses nested record updates and looks like this:

updateU :: XName -> String -> XName
updateU = _ { xname { fname = _ } }


问:
TextView inside an ImageView
I have this picture which is the template for an italian license plate:

My app manages vehicles. I've thought to display all user's vehicles in a RecyclerView with CardView, where each CardView contains an ImageView (which displays the previous image) and a TextView, which contains the license plate. But how could I do to put the TextView in the correct position compared to the image displayed in the ImageView? And, the worst thing I think, how could I do to place the TextView correctly for all screens resolutions?

答:
I've tried a sample code ..

res/layout/numberplate.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:orientation="horizontal">

<LinearLayout
    android:layout_margin="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="46dp"
        android:layout_height="46dp"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_marginLeft="20dp"
        android:gravity="center"
        android:text="Number"
        android:textSize="25dp" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>
</code>```

res/drawable/background.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#d0d0d0" />
<corners android:radius="5dp" />
<stroke android:color="#202020" android:width="3dp"/>
</shape>
</code>```

And how it looks like.

You can change the values to match the way you want..
Hope this helps..

Title: TextView inside an ImageView

Body:
I've tried a sample code ..

res/layout/numberplate.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:orientation="horizontal">

<LinearLayout
    android:layout_margin="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="46dp"
        android:layout_height="46dp"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_marginLeft="20dp"
        android:gravity="center"
        android:text="Number"
        android:textSize="25dp" />
    </LinearLayout>
</LinearLayout>
</LinearLayout>

res/drawable/background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#d0d0d0" />
<corners android:radius="5dp" />
<stroke android:color="#202020" android:width="3dp"/>
</shape>

And how it looks like.

You can change the values to match the way you want..
Hope this helps..


答:
Simply join the two aggregates on ItemID and ItemDate. Below uses two derived tables but in MS Access you can save those two aggregate queries as separate stored queries (i.e., views) and join them in another query.

```<code>SELECT subSales.SaleItemID, subSales.SumSaleItemQty, subRec.SumRecItemQty,
       subSales.SumSaleItemPrice, subSales.SaleItemDate
FROM

   (SELECT
      S.SaleItemID,
      Format(SUM(S.SaleItemQty), "###,##0.00") AS SumSaleItemQty,
      Format(SUM(S.SaleItemPrice), "###,##0.00") AS SumSaleItemPrice,
      S.SaleItemDate
    FROM Items_Sales S
    GROUP BY S.SaleItemID, S.SaleItemDate) As subSales

INNER JOIN

   (SELECT
      R.RecItemID,
      Format(SUM(R.RecItemQty), "###,##0.00") AS SumRecItemQty,
      Format(SUM(R.RecItemPrice), "###,##0.00") AS SumRecItemPrice,
      R.RecItemDate
    FROM Items_Rec R
    GROUP BY R.RecItemID, R.RecItemDate) As subRec

ON subSales.SaleItemID = subRec.RecItemID
AND subSales.SaleItemDate = subRec.RecItemDate
</code>```

Also, look into LEFT JOIN or RIGHT JOIN even UNION of the two (for FULL OUTER) in case item records are in one table and not the other and you need to still capture all pertinent rows.

Body:
Simply join the two aggregates on ItemID and ItemDate. Below uses two derived tables but in MS Access you can save those two aggregate queries as separate stored queries (i.e., views) and join them in another query.

SELECT subSales.SaleItemID, subSales.SumSaleItemQty, subRec.SumRecItemQty,
       subSales.SumSaleItemPrice, subSales.SaleItemDate
FROM

   (SELECT
      S.SaleItemID,
      Format(SUM(S.SaleItemQty), "###,##0.00") AS SumSaleItemQty,
      Format(SUM(S.SaleItemPrice), "###,##0.00") AS SumSaleItemPrice,
      S.SaleItemDate
    FROM Items_Sales S
    GROUP BY S.SaleItemID, S.SaleItemDate) As subSales

INNER JOIN

   (SELECT
      R.RecItemID,
      Format(SUM(R.RecItemQty), "###,##0.00") AS SumRecItemQty,
      Format(SUM(R.RecItemPrice), "###,##0.00") AS SumRecItemPrice,
      R.RecItemDate
    FROM Items_Rec R
    GROUP BY R.RecItemID, R.RecItemDate) As subRec

ON subSales.SaleItemID = subRec.RecItemID
AND subSales.SaleItemDate = subRec.RecItemDate

Also, look into LEFT JOIN or RIGHT JOIN even UNION of the two (for FULL OUTER) in case item records are in one table and not the other and you need to still capture all pertinent rows.