问:
I am having trouble in displaying date beside the entered todo element. What is wrong with changeDate() function?
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate();
  }
}

function changeDate() {
  var d = new Date();
  var dates = document.createElement("div");
  dates.className = "myClass";
  dates.innerHTML = document.createTextNode(d.toDateString());
  list2.innerHTML = dates;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    Your todos
  </h1>

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
  <div class="todos">
    <ul id="demo"></ul>
  </div>
</div></code>```

答:
First of all your JS has an issue. The list2 is a HTMLCollection and there's no .innerHTML for that. You need to use:

```<code>list2[0].innerHTML
</code>```

You don't even need that. The date issue is because of the Date Object incorrectly being set / inserted.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate(list);
  }
}

function changeDate(which) {
  var d = new Date();
  which.innerHTML += d.toDateString();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    Your todos
  </h1>

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
  <div class="todos">
    <ul id="demo"></ul>
  </div>
</div></code>```

Preview

Body:
Entered todo is shown but the date is not being shown. Am i using any wrong command?? On entering a data, date should be shown on the left of the todo, just below the input area.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate();
  }
}

function changeDate() {
  var d = new Date();
  var dates = document.createElement("div");
  dates.className = "myClass";
  dates.innerHTML = document.createTextNode(d.toDateString());
  list2.innerHTML = dates;
}

    Your todos

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">

Body:
First of all your JS has an issue. The list2 is a HTMLCollection and there's no .innerHTML for that. You need to use:

list2[0].innerHTML

You don't even need that. The date issue is because of the Date Object incorrectly being set / inserted.

var list = document.getElementById('demo');
var list2 = document.getElementsByTagName('todos');

function store(ele) {
  if (event.keyCode == 13) {
    changeText();
  }
}

function changeText() {
  var data = document.getElementById('todo').value;
  if (data != '') {
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(data));
    list.appendChild(entry);
    changeDate(list);
  }
}

function changeDate(which) {
  var d = new Date();
  which.innerHTML += d.toDateString();
}

<div class="container">
  <h1>
    Your todos
  </h1>

  <input type="text" id="todo" placeholder="Add a new todo and hit enter" onkeydown="store(this)">
  <div class="todos">
    <ul id="demo"></ul>
  </div>
</div>

Preview


来源: stackexchange

问:
How do I execute a command with quotation marks in an argument?
I'm trying to run the command

rsync -rtv -e 'ssh -i /Users/yuanlinfeng/.ssh/id_rsa -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2"' /tmp/a username@ip:/home/ubuntu/a
```

<p>The code is:</p>

```let login_settings = format!(r#"'ssh -i {} -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2"'"#, identity);
let mut cmd = Command::new("rsync");
cmd.env("SETTING", login_settings);
cmd.arg("-rtv").arg("-e").arg(login_settings);
if delete {
    cmd.arg("--delete");
}
match exclude_files {
    None => {}
    Some(exclude_files) => {
        for file in exclude_files.iter() {
            cmd.arg("--exclude").arg(file);
        }
    }
}
let target = format!("{}@{}:{}", username, remote_ip, dest);
cmd.arg(source).arg(target);
let output = cmd.output()?;
if output.stdout.len() > 0 {
    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
}
if output.stderr.len() > 0 {
    println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
}
```

<p>The error:</p>

<pre class="lang-none prettyprint-override"><code>stderr: rsync: Failed to exec ssh -i /Users/yuanlinfeng/.ssh/id_rsa -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2": No such file or directory (2)
rsync error: error in IPC code (code 14) at /BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-52/rsync/pipe.c(86) [sender=2.6.9]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-52/rsync/io.c(453) [sender=2.6.9]
</code>```

It looks like the quotation marks in the arguments are removed. How do I fix it?

I'm using macOS High Sierra and Rust 1.22.1.

答:
The ' quotes around the ssh ... argument are not actually passed to rsync; they are used by the shell to separate the arguments to rsync.

Your Rust code tries to call something like this: rsync -e "'ssh ...'" .... rsync then tries to split the 'ssh ...' argument similar to the shell (it seems it doesn't actually use the shell to expand it). This means it will see ssh ... as one argument (the filename to execute) but such a file doesn't exist.

Remove the ' quotes in your format! call, and it might work.

On Linux you could run your example through strace -ff -e trace=execve -- ./target/... to see how this works.  macOS has dtruss, but I can't help you with that :)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run the command

rsync -rtv -e 'ssh -i /Users/yuanlinfeng/.ssh/id_rsa -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2"' /tmp/a username@ip:/home/ubuntu/a

The code is:

let login_settings = format!(r#"'ssh -i {} -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2"'"#, identity);
let mut cmd = Command::new("rsync");
cmd.env("SETTING", login_settings);
cmd.arg("-rtv").arg("-e").arg(login_settings);
if delete {
    cmd.arg("--delete");
}
match exclude_files {
    None => {}
    Some(exclude_files) => {
        for file in exclude_files.iter() {
            cmd.arg("--exclude").arg(file);
        }
    }
}
let target = format!("{}@{}:{}", username, remote_ip, dest);
cmd.arg(source).arg(target);
let output = cmd.output()?;
if output.stdout.len() > 0 {
    println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
}
if output.stderr.len() > 0 {
    println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
}

The error:

stderr: rsync: Failed to exec ssh -i /Users/yuanlinfeng/.ssh/id_rsa -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking no" -o "ConnectTimeout=2": No such file or directory (2)
rsync error: error in IPC code (code 14) at /BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-52/rsync/pipe.c(86) [sender=2.6.9]
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at /BuildRoot/Library/Caches/com.apple.xbs/Sources/rsync/rsync-52/rsync/io.c(453) [sender=2.6.9]

It looks like the quotation marks in the arguments are removed. How do I fix it?

I'm using macOS High Sierra and Rust 1.22.1.


问:
How to avoid calling javadoc more than once if creating a site?
I would like to deploy an artifact together with javadoc and a Maven site. I use

```<code>clean javadoc:jar site deploy site:deploy
</code>```

(the split between site and site:deploy is just to avoid the deployment of a site if deploy fails).

Now the javadoc is created twice - once in javadoc:jar and once in site. Is it possible to create it just once and use it both for the javadoc-jar in Nexus and the Maven site?

答: I'm pretty sure the plugin is missing a check if the output is already generated as part of the Maven session. Would be a nice improvement to verify if the output is generated after Maven had started. (and let's add a force-parameter to enforce the creation anyway).

Body:
I would like to deploy an artifact together with javadoc and a Maven site. I use

clean javadoc:jar site deploy site:deploy

(the split between site and site:deploy is just to avoid the deployment of a site if deploy fails).

Now the javadoc is created twice - once in javadoc:jar and once in site. Is it possible to create it just once and use it both for the javadoc-jar in Nexus and the Maven site?


问:
htaccess - The page isn't redirecting properly
I have taken over a website and am trying to force https. I have added the following to my .htaccess file:

```<code>RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L]
</code>```

The rest of the file looks like this:

```<code>RewriteCond %{REQUEST_FILENAME} !^(.*)/audio_recording/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.*)/bwcheck/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.+)/page\.php$
... lots of Conditions
RewriteRule ^(.*)\.* page.php?$1 [L]
IndexIgnore *
</code>```

When I add the https redirect I am getting the following error:

The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

and chrome:

This webpage has a redirect loop...

The url is updated to https however.

EDIT:

Here is the begining of the .htaccess file:

```<code>php_value memory_limit 64M

<Files .htaccess>
order allow,deny
deny from all
</Files>

DirectoryIndex index
Options +FollowSymlinks
RewriteEngine on
RewriteBase /

ErrorDocument 404 /web/content/content/404.php
</code>```

答:
its as simple as:</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</code>```

Body:
I have taken over a website and am trying to force https. I have added the following to my .htaccess file:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L]

The rest of the file looks like this:

RewriteCond %{REQUEST_FILENAME} !^(.*)/audio_recording/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.*)/bwcheck/(.*)$
RewriteCond %{REQUEST_FILENAME} !^(.+)/page\.php$
... lots of Conditions
RewriteRule ^(.*)\.* page.php?$1 [L]
IndexIgnore *

When I add the https redirect I am getting the following error:

The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.

and chrome:

This webpage has a redirect loop...

The url is updated to https however.

EDIT:

Here is the begining of the .htaccess file:

php_value memory_limit 64M

<Files .htaccess>
order allow,deny
deny from all
</Files>

DirectoryIndex index
Options +FollowSymlinks
RewriteEngine on
RewriteBase /

ErrorDocument 404 /web/content/content/404.php

Body:
its as simple as:

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


问:
window.open() does not work in knockout.js
I'm working on an application where I need a window to be open in the browser when user clicks the button. But I get some errors after done() complete.
I am not sure that this is knockout.js issue but I suppose that it is:

I have this knockout action in js file:

```<code>function SaveBankCard(vm) {
if (viewModel._isBankCardChange()) {
    var modelJs = viewModel.BankCard.ToJS();

    return $.ajax({
        method: "POST",
        url: "../Profile/Save",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            currentCards: modelJs.Items,
            workerId: viewModel.Main.WorkerId()
        })

    })
        .done(function (changes) {
            viewModel._hashBankCardOld(viewModel.BankCard.GetHash());
            ShowSuccessContainer('Saved');

            if (changes.MemoAdded) {
                var url = '../Profile/Download?workerId='+ viewModel.Main.WorkerId();
                window.open(url, '_blank');
            }
        });
}

}
</code>```

By some reason the url Profile/Download?workerId= is not opened on production environment (even when changes.MemoAdded is true). However, on test site it is working...

In Chrome Developer Tool I get the following errors:

(WEB_PAGE context) Lazy require of app.binding did not set the binding field

(WEB_PAGE context) Lazy require of webstore.binding did not set the binding field

(WEB_PAGE context) Lazy require of runtime.binding did not set the binding field

Uncaught Natives disabled

Uncaught Natives disabled

(WEB_PAGE context) extensions::event_bindings:8: Uncaught Natives disabled{}

(WEB_PAGE context) extensions::binding:5: Uncaught TypeError: Cannot read property 'Event' of undefined{TypeError: Cannot read property 'Event' of undefined
    at extensions::binding:5:38
    at extensions::runtime:7:28}

Uncaught TypeError: Cannot read property 'Binding' of undefined
    at extensions::runtime:7

I don't understand what these messages mean.

Any thought would be very appreciated ... I use knockout-3.3.0

UPDATE: these messages appears in Google Chrome (62.0.3202.94), Firefox is OK.

答: Omg, I just need to refresh the web page with Ctrl + F5.</p>

Body:
I'm working on an application where I need a window to be open in the browser when user clicks the button. But I get some errors after done() complete.
I am not sure that this is knockout.js issue but I suppose that it is:

I have this knockout action in js file:

function SaveBankCard(vm) {
if (viewModel._isBankCardChange()) {
    var modelJs = viewModel.BankCard.ToJS();

    return $.ajax({
        method: "POST",
        url: "../Profile/Save",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            currentCards: modelJs.Items,
            workerId: viewModel.Main.WorkerId()
        })

    })
        .done(function (changes) {
            viewModel._hashBankCardOld(viewModel.BankCard.GetHash());
            ShowSuccessContainer('Saved');

            if (changes.MemoAdded) {
                var url = '../Profile/Download?workerId='+ viewModel.Main.WorkerId();
                window.open(url, '_blank');
            }
        });
}

}

By some reason the url Profile/Download?workerId= is not opened on production environment (even when changes.MemoAdded is true). However, on test site it is working...

In Chrome Developer Tool I get the following errors:

(WEB_PAGE context) Lazy require of app.binding did not set the binding field

(WEB_PAGE context) Lazy require of webstore.binding did not set the binding field

(WEB_PAGE context) Lazy require of runtime.binding did not set the binding field

Uncaught Natives disabled

Uncaught Natives disabled

(WEB_PAGE context) extensions::event_bindings:8: Uncaught Natives disabled{}

(WEB_PAGE context) extensions::binding:5: Uncaught TypeError: Cannot read property 'Event' of undefined{TypeError: Cannot read property 'Event' of undefined
    at extensions::binding:5:38
    at extensions::runtime:7:28}

Uncaught TypeError: Cannot read property 'Binding' of undefined
    at extensions::runtime:7

I don't understand what these messages mean.

Any thought would be very appreciated ... I use knockout-3.3.0

UPDATE: these messages appears in Google Chrome (62.0.3202.94), Firefox is OK.


问:
Need synchronous behavior in angular js 1.x
Background: I have one Web API with GET method and returning the boolean value.
Once I receive this value then I need to perform some action.

Issue: My code is reaching to the condition where I am checking this boolean value before the API return the value. I am unable to wait until the API returns the value. In below code Javascript execution is reaching to "setTimeout" statement.

My R&D: I have applied this setTimeout to delay the execution but still the value is coming late from api and javascript is processing.

Code: using AngularJS 1.6 version
I have tried both way using $http.get() and $http({//setting the confiuration here});

actual code:
1. code where I am calling the service

```<code>paymentFormRoleValidationBeforeSubmit: function (contractId, payFormId) {
        return $http({
            url: 'some api url',
            method: "GET",
            headers: serviceheader,
            config: serviceconfig
        }).success(function (data, status, headers, serviceheader) {
            return data.value;
        }).error(function (data, status, header, serviceheader) {
                console.log("** Fail -- before submitting role checked is failed.")
                return false;
        });
    }
</code>```

javascript code where I am calling this one

```<code>if (workflowStatus == "Start") {
        var returnHttp = $paymentFormsService.paymentFormRoleValidationBeforeSubmit(parseInt($rootScope.contractId), parseInt($rootScope.payFormId));
                    flagValue = returnHttp;
                }
</code>```

Inside this fire method I am checking whether flagValue is true or false and then executing some other task, but this value is coming undefine and the else part is executing

setTimeout(fire(workflowStatus, flagValue), 5000);

function fire(workflowStatus, flagValue){
 if (flagValue === true) {
     // if value is true then save in database.
 }
 else{
    // Here I am displaying an error popup on UI screen
 }
}

But in my case I am getting error popup everytime, because the API has not yet return the value and flagValue is undefined. and this popup get dispalyed. After that in then API return the value it is working in async way.

Or is there any other way to do it please update me.. This is my production issue.

答:
I think you should do your http request in your service and get your promise where you call the service. This way you can set your flag when your http call returns a promise.

service

```<code>paymentFormRoleValidationBeforeSubmit = function (contractId, payFormId) {
    var request = $http({
        url: 'some api url',
        method: "GET",
        headers: serviceheader,
        config: serviceconfig
    });
    return request;
}
</code>```

code where you call the service

```<code>var promiseGet = $paymentFormsService.paymentFormRoleValidationBeforeSubmit(parseInt($rootScope.contractId), parseInt($rootScope.payFormId));;
promiseGet.then(function (returnHttp) {
    flagValue = returnHttp;
},
function (errorPl) {

});
</code>```

Body:
Background: I have one Web API with GET method and returning the boolean value.
Once I receive this value then I need to perform some action.

Issue: My code is reaching to the condition where I am checking this boolean value before the API return the value. I am unable to wait until the API returns the value. In below code Javascript execution is reaching to "setTimeout" statement.

My R&D: I have applied this setTimeout to delay the execution but still the value is coming late from api and javascript is processing.

Code: using AngularJS 1.6 version
I have tried both way using $http.get() and $http({//setting the confiuration here});

actual code:
1. code where I am calling the service

paymentFormRoleValidationBeforeSubmit: function (contractId, payFormId) {
        return $http({
            url: 'some api url',
            method: "GET",
            headers: serviceheader,
            config: serviceconfig
        }).success(function (data, status, headers, serviceheader) {
            return data.value;
        }).error(function (data, status, header, serviceheader) {
                console.log("** Fail -- before submitting role checked is failed.")
                return false;
        });
    }

javascript code where I am calling this one

if (workflowStatus == "Start") {
        var returnHttp = $paymentFormsService.paymentFormRoleValidationBeforeSubmit(parseInt($rootScope.contractId), parseInt($rootScope.payFormId));
                    flagValue = returnHttp;
                }

Inside this fire method I am checking whether flagValue is true or false and then executing some other task, but this value is coming undefine and the else part is executing

setTimeout(fire(workflowStatus, flagValue), 5000);

function fire(workflowStatus, flagValue){
 if (flagValue === true) {
     // if value is true then save in database.
 }
 else{
    // Here I am displaying an error popup on UI screen
 }
}

But in my case I am getting error popup everytime, because the API has not yet return the value and flagValue is undefined. and this popup get dispalyed. After that in then API return the value it is working in async way.

Or is there any other way to do it please update me.. This is my production issue.

Body:
I think you should do your http request in your service and get your promise where you call the service. This way you can set your flag when your http call returns a promise.

service

paymentFormRoleValidationBeforeSubmit = function (contractId, payFormId) {
    var request = $http({
        url: 'some api url',
        method: "GET",
        headers: serviceheader,
        config: serviceconfig
    });
    return request;
}

code where you call the service

var promiseGet = $paymentFormsService.paymentFormRoleValidationBeforeSubmit(parseInt($rootScope.contractId), parseInt($rootScope.payFormId));;
promiseGet.then(function (returnHttp) {
    flagValue = returnHttp;
},
function (errorPl) {

});


问:
Angular 5 / Node Express each request uses new session
I am developing an application in Angular 5 which connects to my server in NodeJS.

I add the user in the req.session object after the user is logged in.

When I make a second request from Angular 5 app to retrieve something from the API, the req.session doesn't contain the user and the req.sessionId is always different.

How can I make the session persistent?

Here are the session and cookieParser middlewares:

```<code>app.use(cookieParser(config.secret))

app.use(session({
    secret: config.secret,
    saveUninitialized: false,
    resave: false,
    cookie: {
        httpOnly: true,
        secure: false
    }
}))
</code>```

答: It was a CORS related issue. I needed to include { withCredentials: true } in the http request options in Angular.

Body:
I am developing an application in Angular 5 which connects to my server in NodeJS.

I add the user in the req.session object after the user is logged in.

When I make a second request from Angular 5 app to retrieve something from the API, the req.session doesn't contain the user and the req.sessionId is always different.

How can I make the session persistent?

Here are the session and cookieParser middlewares:

app.use(cookieParser(config.secret))

app.use(session({
    secret: config.secret,
    saveUninitialized: false,
    resave: false,
    cookie: {
        httpOnly: true,
        secure: false
    }
}))


问:
Lists in python 3
So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc  and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function. </p>

```<code> l1 = []
 def fun2(x,y):
    for x in range(x+1):
        for y in range(y+1):
            l1.append((x,y))
    return l1
</code>```

答:
Method 1: Using list comprehnsion:

```<code>lst = [c for c in l1 if c[0] != c[1]]
</code>```

Method 2: Building the list manually:

```<code>lst = []
for elem in l1:
    if elem[0] != elem[1]:
        lst.append(elem)
</code>```

Title: Lists in python 3

Body:
So the problem is that I have a list which is made of pairs of numbers [ (0,0),(0,1)(0,2) ...etc  and I would like to know how to delete from this list all pairs with the same numbers . List was created by this function.

 l1 = []
 def fun2(x,y):
    for x in range(x+1):
        for y in range(y+1):
            l1.append((x,y))
    return l1

Body:
Method 1: Using list comprehnsion:

lst = [c for c in l1 if c[0] != c[1]]

Method 2: Building the list manually:

lst = []
for elem in l1:
    if elem[0] != elem[1]:
        lst.append(elem)


问:
Returning the passed slot with an extra class from vuejs render function
I am trying to create a component who task is to simply add a class on whatever element is passed to it as slot when its just one node

Usage:

```<code><my-component>
 <button>hello</button>
</my-component>
</code>```

Output:

```<code><button class="added-by-component">hello</button>
</code>```

I tried with <template> tag, but <slot> isn't allowed to be on the root.

Even with render() function, I tried returning the passed slot's vnode after modifying the class property:

```<code>render (createElement) {
 var vnode = this.$slots.default[0]
 vnode.data = vnode.data || {}
 vnode.data.class = { 'added-by-component': this.someCondition }
 return vnode
}
</code>```

Even this doesn't work as expected. I don't get the class added even when the condition is true.

答:
```<code>const Wrapper = {
  functional: true,
  render (h, ctx) {
    const slots = ctx.slots()
    const node = slots.default[0]

    node.data.staticClass = [
      'my-class',
      node.data.staticClass || ''
    ].join(' ')

    return node
  }
}
</code>```

You can use data.class too but it would need extra type handling.

Body:
I am trying to create a component who task is to simply add a class on whatever element is passed to it as slot when its just one node

Usage:

<my-component>
 <button>hello</button>
</my-component>

Output:

<button class="added-by-component">hello</button>

I tried with <template> tag, but <slot> isn't allowed to be on the root.

Even with render() function, I tried returning the passed slot's vnode after modifying the class property:

render (createElement) {
 var vnode = this.$slots.default[0]
 vnode.data = vnode.data || {}
 vnode.data.class = { 'added-by-component': this.someCondition }
 return vnode
}

Even this doesn't work as expected. I don't get the class added even when the condition is true.

Body:
const Wrapper = {
  functional: true,
  render (h, ctx) {
    const slots = ctx.slots()
    const node = slots.default[0]

    node.data.staticClass = [
      'my-class',
      node.data.staticClass || ''
    ].join(' ')

    return node
  }
}

You can use data.class too but it would need extra type handling.


问:
Form: Onload a script, wait 2 sec, then load next
I have a page that automatically gets the position, and fills it into a form.

```<code></script>
<body onload="getLocation();">
</code>```

Then i have to wait 2 sec, and push a button to convert position to real address.

```<code><input id="submit" type="button" value="Reverse Geocode">
</code>```

How can i trigg the button automatically or remove the button and have the trigging automatically-

With a time delay of 2 sec?

Code:

```<code> function getLocation(){

    if(navigator.geolocation){
       // timeout at 60000 milliseconds (60 seconds)
       var options = {timeout:60000};
       navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
    }
    else{
       alert("Sorry, browser does not support geolocation!");
    }
 }
</code>```

答:
You can use the setTimeout() function to run a function after a defined number of milliseconds. In your case,

```<code>function getLocation(){
  if(navigator.geolocation){
    var options = {timeout:60000};
    navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

    setTimeout(
      function(){
        document.getElementById("submit").click(); //Click the Button
      },
      2000 // 2000 milliseconds = 2 seconds
    );
  }

  else{
    alert("Sorry, browser does not support geolocation!");
  }
}
</code>```

The DOM click() method is used to virtually click the button with JavaScript.

Body:
I have a page that automatically gets the position, and fills it into a form.

</script>

Then i have to wait 2 sec, and push a button to convert position to real address.

<input id="submit" type="button" value="Reverse Geocode">

How can i trigg the button automatically or remove the button and have the trigging automatically-

With a time delay of 2 sec?

Code:

 function getLocation(){

    if(navigator.geolocation){
       // timeout at 60000 milliseconds (60 seconds)
       var options = {timeout:60000};
       navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
    }
    else{
       alert("Sorry, browser does not support geolocation!");
    }
 }

Body:
You can use the setTimeout() function to run a function after a defined number of milliseconds. In your case,

function getLocation(){
  if(navigator.geolocation){
    var options = {timeout:60000};
    navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

    setTimeout(
      function(){
        document.getElementById("submit").click(); //Click the Button
      },
      2000 // 2000 milliseconds = 2 seconds
    );
  }

  else{
    alert("Sorry, browser does not support geolocation!");
  }
}

The DOM click() method is used to virtually click the button with JavaScript.


答:
You are looking for 'setTimeout' function:</p>

```<code>setTimeout(function () {
  // your code
}, 3000);
</code>```

Title: Form: Onload a script, wait 2 sec, then load next

Body:
You are looking for 'setTimeout' function:

setTimeout(function () {
  // your code
}, 3000);


问:
How can I create a JTextField that shows drop down menu, that drop menu would show the list of items from my Database?
How can I create a JTextField that shows drop down menu, that drop menu would show the list of items from my Database? ,Please see JTextField having Add and Clear Button in front of it</p>

答: Probably what you need is JComboBox. You can read more about it here.


问:
Why my app is not shown in iCloud Drive Folder
iCloud Drive Folder doesn't show my app's folder.

This is how I send a file to iCloud Drive:

```<code>- (IBAction)btnStoreTapped:(id)sender {
    // Let's get the root directory for storing the file on iCloud Drive
    [self rootDirectoryForICloud:^(NSURL *ubiquityURL) {
        NSLog(@"1. ubiquityURL = %@", ubiquityURL);
        if (ubiquityURL) {

            // We also need the 'local' URL to the file we want to store
            //NSURL *localURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Photo" ofType:@"pdf"]];

            NSURL *localURL = [self localPathForResource:@"document" ofType:@"doc"];
            NSLog(@"2. localURL = %@", localURL);

            // Now, append the local filename to the ubiquityURL
            ubiquityURL = [ubiquityURL URLByAppendingPathComponent:localURL.lastPathComponent];
            NSLog(@"3. ubiquityURL = %@", ubiquityURL);

            // And finish up the 'store' action
            NSError *error;
            if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:localURL destinationURL:ubiquityURL error:&error]) {
                NSLog(@"Error occurred: %@", error);
            }else{
                NSLog(@"Succeed");
            }
        }
        else {
            NSLog(@"Could not retrieve a ubiquityURL");
        }
    }];
}

- (void)rootDirectoryForICloud:(void (^)(NSURL *))completionHandler {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:@"Documents"];

        if (rootDirectory) {
            if (![[NSFileManager defaultManager] fileExistsAtPath:rootDirectory.path isDirectory:nil]) {
                NSLog(@"Create directory");
                [[NSFileManager defaultManager] createDirectoryAtURL:rootDirectory withIntermediateDirectories:YES attributes:nil error:nil];
            }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(rootDirectory);
        });
    });
}

- (NSURL *)localPathForResource:(NSString *)resource ofType:(NSString *)type {
    NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *resourcePath = [[documentsDirectory stringByAppendingPathComponent:resource] stringByAppendingPathExtension:type];
    return [NSURL fileURLWithPath:resourcePath];
}
</code>```

Actually I did everyting explained in this post

Everything looks like fine. I can upload files successfully and I can show them in my computer via terminal.

And I can see the files I just uploaded from my iphone.

But nothing shown in my iCloud Drive folder in my mac or icloud.com. Why they are not showing my app's folder even everything looks like fine and there is no error?

答:
Bump CFBundleVersion in Info.plist.

Create a new iCound container on https://developer.apple.com/account/ios/identifier/cloudContainer

Specify custom containers in Xcode. Untick the old containers and tick the new created container.

Body:
iCloud Drive Folder doesn't show my app's folder.

This is how I send a file to iCloud Drive:

- (IBAction)btnStoreTapped:(id)sender {
    // Let's get the root directory for storing the file on iCloud Drive
    [self rootDirectoryForICloud:^(NSURL *ubiquityURL) {
        NSLog(@"1. ubiquityURL = %@", ubiquityURL);
        if (ubiquityURL) {

            // We also need the 'local' URL to the file we want to store
            //NSURL *localURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Photo" ofType:@"pdf"]];

            NSURL *localURL = [self localPathForResource:@"document" ofType:@"doc"];
            NSLog(@"2. localURL = %@", localURL);

            // Now, append the local filename to the ubiquityURL
            ubiquityURL = [ubiquityURL URLByAppendingPathComponent:localURL.lastPathComponent];
            NSLog(@"3. ubiquityURL = %@", ubiquityURL);

            // And finish up the 'store' action
            NSError *error;
            if (![[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:localURL destinationURL:ubiquityURL error:&error]) {
                NSLog(@"Error occurred: %@", error);
            }else{
                NSLog(@"Succeed");
            }
        }
        else {
            NSLog(@"Could not retrieve a ubiquityURL");
        }
    }];
}

- (void)rootDirectoryForICloud:(void (^)(NSURL *))completionHandler {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil]URLByAppendingPathComponent:@"Documents"];

        if (rootDirectory) {
            if (![[NSFileManager defaultManager] fileExistsAtPath:rootDirectory.path isDirectory:nil]) {
                NSLog(@"Create directory");
                [[NSFileManager defaultManager] createDirectoryAtURL:rootDirectory withIntermediateDirectories:YES attributes:nil error:nil];
            }
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(rootDirectory);
        });
    });
}

- (NSURL *)localPathForResource:(NSString *)resource ofType:(NSString *)type {
    NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *resourcePath = [[documentsDirectory stringByAppendingPathComponent:resource] stringByAppendingPathExtension:type];
    return [NSURL fileURLWithPath:resourcePath];
}

Actually I did everyting explained in this post

Everything looks like fine. I can upload files successfully and I can show them in my computer via terminal.

And I can see the files I just uploaded from my iphone.

But nothing shown in my iCloud Drive folder in my mac or icloud.com. Why they are not showing my app's folder even everything looks like fine and there is no error?


问:
How to fix 405 Method not allowed with okhttp
I'm getting

405 Method not allowed

when I try to patch the application using below code. How to fix it?

```<code>RequestBody body = new MultipartBuilder()
    .type(MultipartBuilder.FORM)
    .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/zip"), uploadZipFile))
    .addFormDataPart("artifactName", "gpswalker")
    .addFormDataPart("targetId", new Integer(SERV_ID).toString())
    .build();

Request request = new Request
    .Builder()
    .url(url)
    .patch(body)
    .addHeader("authorization", bearer_token)
    .addHeader("x-anypnt-org-id", ORG_ID)
    .addHeader("x-anypnt-env-id", ENV_ID)
    .addHeader("cache-control", "no-cache")
    .build();

Response response = client.newCall(request).execute();
</code>```

答: there is no wrong in code, issue was with URL. and it is fixed.</p>

Body:
I'm getting

405 Method not allowed

when I try to patch the application using below code. How to fix it?

RequestBody body = new MultipartBuilder()
    .type(MultipartBuilder.FORM)
    .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/zip"), uploadZipFile))
    .addFormDataPart("artifactName", "gpswalker")
    .addFormDataPart("targetId", new Integer(SERV_ID).toString())
    .build();

Request request = new Request
    .Builder()
    .url(url)
    .patch(body)
    .addHeader("authorization", bearer_token)
    .addHeader("x-anypnt-org-id", ORG_ID)
    .addHeader("x-anypnt-env-id", ENV_ID)
    .addHeader("cache-control", "no-cache")
    .build();

Response response = client.newCall(request).execute();


问:
Interlocked.Increment() not working the way I'd expect in the Task Parallel Library
I have a Parallel.ForEach() loop that takes a list of URL's and downloads each of them for some additional processing.  Outside my loop I have declared a loop counter variable and inside the loop body I use Interlocked.Increment() thinking this would be the best way to keep a "thread safe" way of increasing the count as each loop interation is performed.

```<code>int counter = 0;

Parallel.ForEach(urlList, (url, state) =>
{
    // various code statments

    Interlocked.Increment( ref counter );

    Debug.WriteLine(" ......... counter: " + counter);
});
</code>```

I would have thought that I would see something similar to:

```<code> ......... 1
 ......... 2
 ......... 3
 ......... 4
 ......... 5
 .........
 .........
 ......... n
</code>```

But what I get instead is 16 " ......... 0" (this is because I have a dual quad core computer with 8 native cores, but hyper threading is enabled giving me a total of 16 cores).  Then I will start to see the counter get incremented normally for the most part but sometimes I will see duplicate or even triplicate counter values in the Debug output.

Using a Parallel.ForEach() what is the best way to count loop iterations?  Thanks for any advice.

答:
This is because the Increment + WriteLine together are not atomic.

It might be that thread1 increments counter, then thread2 increments it again, and then the two threads get to the WriteLine part with the same value of counter.

ContentLicense: CC BY-SA 2.5

Body:
I have a Parallel.ForEach() loop that takes a list of URL's and downloads each of them for some additional processing.  Outside my loop I have declared a loop counter variable and inside the loop body I use Interlocked.Increment() thinking this would be the best way to keep a "thread safe" way of increasing the count as each loop interation is performed.

int counter = 0;

Parallel.ForEach(urlList, (url, state) =>
{
    // various code statments

    Interlocked.Increment( ref counter );

    Debug.WriteLine(" ......... counter: " + counter);
});

I would have thought that I would see something similar to:

 ......... 1
 ......... 2
 ......... 3
 ......... 4
 ......... 5
 .........
 .........
 ......... n

But what I get instead is 16 " ......... 0" (this is because I have a dual quad core computer with 8 native cores, but hyper threading is enabled giving me a total of 16 cores).  Then I will start to see the counter get incremented normally for the most part but sometimes I will see duplicate or even triplicate counter values in the Debug output.

Using a Parallel.ForEach() what is the best way to count loop iterations?  Thanks for any advice.


问:
How to unit test a service call in xUnit and nSubstitute
I been trying to figure out how i can unit test service and so far have got nowhere.

I am using xUnit and NSubstitute (as advised by friends), below is the simple test that i want to run (which fails currently).

```<code>public class UnitTest1
{
    private readonly RallyService _rallyService;

    public UnitTest1(RallyService rallyService)
    {
        _rallyService= rallyService;
    }

    [Fact]
    public void Test1()
    {
        var result = _rallyService.GetAllRallies();

        Assert.Equal(2, result.Count());
    }
}
</code>```

My rally service class makes a simple call to the db to get all Rally entites and returns those:

```<code>public class RallyService : IRallyService
{
    private readonly RallyDbContext _context;

    public RallyService(RallyDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Rally> GetAllRallies()
    {
        return _context.Rallies;
    }
}
</code>```

Any guidance would be appreciated.

答:
I don't think it is standard to have a unit test constructor with a parameter. The unit test runner will new up this class, and unless you are using something that will auto-inject that parameter I think the test will fail to run.

Here is a standard fixture layout:

```<code>public class SampleFixture {

    [Fact]
    public void SampleShouldWork() {
        // Arrange stuff we need for the test. This may involved configuring
        // some dependencies, and also creating the subject we are testing.
        var realOrSubstitutedDependency = new FakeDependency();
        realOrSubstitutedDependency.WorkingItemCount = 42;
        var subject = new Subject(realOrSubstitutedDependency);

        // Act: perform the operation we are testing
        var result = subject.DoWork();

        // Assert: check the subject's operation worked as expected
        Assert.Equal(42, result);
    }

    [Fact]
    public void AnotherTest() { /* ... */ }
}
</code>```

If you need a common setup between tests, you can use a parameterless constructor and do common initialisation there.

In terms of the specific class you are trying to test, you need to make sure your RallyDbContext is in a known state to repeatably and reliably test. You may want to look up answers specific to testing Entity Framework for more information.

Body:
I been trying to figure out how i can unit test service and so far have got nowhere.

I am using xUnit and NSubstitute (as advised by friends), below is the simple test that i want to run (which fails currently).

public class UnitTest1
{
    private readonly RallyService _rallyService;

    public UnitTest1(RallyService rallyService)
    {
        _rallyService= rallyService;
    }

    [Fact]
    public void Test1()
    {
        var result = _rallyService.GetAllRallies();

        Assert.Equal(2, result.Count());
    }
}

My rally service class makes a simple call to the db to get all Rally entites and returns those:

public class RallyService : IRallyService
{
    private readonly RallyDbContext _context;

    public RallyService(RallyDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Rally> GetAllRallies()
    {
        return _context.Rallies;
    }
}

Any guidance would be appreciated.

Body:
I don't think it is standard to have a unit test constructor with a parameter. The unit test runner will new up this class, and unless you are using something that will auto-inject that parameter I think the test will fail to run.

Here is a standard fixture layout:

public class SampleFixture {

    [Fact]
    public void SampleShouldWork() {
        // Arrange stuff we need for the test. This may involved configuring
        // some dependencies, and also creating the subject we are testing.
        var realOrSubstitutedDependency = new FakeDependency();
        realOrSubstitutedDependency.WorkingItemCount = 42;
        var subject = new Subject(realOrSubstitutedDependency);

        // Act: perform the operation we are testing
        var result = subject.DoWork();

        // Assert: check the subject's operation worked as expected
        Assert.Equal(42, result);
    }

    [Fact]
    public void AnotherTest() { /* ... */ }
}

If you need a common setup between tests, you can use a parameterless constructor and do common initialisation there.

In terms of the specific class you are trying to test, you need to make sure your RallyDbContext is in a known state to repeatably and reliably test. You may want to look up answers specific to testing Entity Framework for more information.


问:
Using time() inside a while loop
For a school assignment we need to write a PHP script that counts for 1 second.

The following code I wrote should do exactly that was my thought:

```<code>$startTijd = time();
$teller = 0;
while($startTijd == time()){
    echo 'Iteratie: ' . $teller . '<br>';
    $teller++;
}
</code>```

However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.

答:
Your code as it is would not work (would not count one second exactly), because time() has a granularity of one second, and you have no guarantees that you landed on your page exactly at the tick of a second. So you need to synchronize.

To be clear, imagine calling time() several times, and let's suppose time() outputs in HH:MM:SS instead of Unix timestamps for legibility's sake:

```<code>Code
print time()
print time()
print time()
...

Output:
01:15:17
01:15:17
01:15:17
...
01:15:18
01:15:18
01:15:18
...
</code>```

Your program probably currently does not work correctly because even in the little time that the loop runs, it generates a fantastic quantity of output (as can be seen above, time() remains "valid" for up to a whole second, and in that time a loop can execute lots of times). If there's some sort of resource limit on the PHP process, it's possible that this drives the process over its quota, resulting in the 502 error. You can check that by removing the echo from the loop, and just adding echo "Done." at the end.

You want to count between the instant in time in which time() transitions from 01:15:17 to 01:15:18, up to the instant when it again transitions to 01:15:19. Those instants will be separated by exactly one second.

What you would need to do is:

```<code>$startTijd = time()+1; // It is now maybe 01:15:17.93. We want to start
                       // counting at 01:15:18, so we need to wait for it.
while($startTijd !== time()) {
    // Do nothing except maybe a very brief sleep to save CPU
    usleep(5); // this is optional anyway.
}
// It is now 01:15:18.000003 and $startTijd is 01:15:18
$teller = 0;
// time() will remain equal to 01:15:18 for one second,
// while wall clock time increases from 01:15:18.000003 to 01:15:18.999999
while ($startTijd == time()) {
    // Don't output anything here
    $teller++;
}
// New transition detected.
// It is now e.g. 01:15:19.000137 and time() says 01:15:19.
echo 'Iteratie: ' . $teller . '<br>';
</code>```

Alternately you can use microtime(true):

```<code>$teller = 0;
$endTijd = microtime(true) + 1.0;
while ($endTijd >= microtime(true)) {
    // Don't output anything here
    $teller++;
}
echo 'Iteratie: ' . $teller . '<br>';
</code>```

Title: Using time() inside a while loop

Body:
For a school assignment we need to write a PHP script that counts for 1 second.

The following code I wrote should do exactly that was my thought:

$startTijd = time();
$teller = 0;
while($startTijd == time()){
    echo 'Iteratie: ' . $teller . '
';
    $teller++;
}

However, every time I run this or any PHP script similar to it that uses the time() function inside a while loop I get a 502 bad request from the server when I try to visit the page.

Body:
Your code as it is would not work (would not count one second exactly), because time() has a granularity of one second, and you have no guarantees that you landed on your page exactly at the tick of a second. So you need to synchronize.

To be clear, imagine calling time() several times, and let's suppose time() outputs in HH:MM:SS instead of Unix timestamps for legibility's sake:

Code
print time()
print time()
print time()
...

Output:
01:15:17
01:15:17
01:15:17
...
01:15:18
01:15:18
01:15:18
...

Your program probably currently does not work correctly because even in the little time that the loop runs, it generates a fantastic quantity of output (as can be seen above, time() remains "valid" for up to a whole second, and in that time a loop can execute lots of times). If there's some sort of resource limit on the PHP process, it's possible that this drives the process over its quota, resulting in the 502 error. You can check that by removing the echo from the loop, and just adding echo "Done." at the end.

You want to count between the instant in time in which time() transitions from 01:15:17 to 01:15:18, up to the instant when it again transitions to 01:15:19. Those instants will be separated by exactly one second.

What you would need to do is:

$startTijd = time()+1; // It is now maybe 01:15:17.93. We want to start
                       // counting at 01:15:18, so we need to wait for it.
while($startTijd !== time()) {
    // Do nothing except maybe a very brief sleep to save CPU
    usleep(5); // this is optional anyway.
}
// It is now 01:15:18.000003 and $startTijd is 01:15:18
$teller = 0;
// time() will remain equal to 01:15:18 for one second,
// while wall clock time increases from 01:15:18.000003 to 01:15:18.999999
while ($startTijd == time()) {
    // Don't output anything here
    $teller++;
}
// New transition detected.
// It is now e.g. 01:15:19.000137 and time() says 01:15:19.
echo 'Iteratie: ' . $teller . '<br>';

Alternately you can use microtime(true):

$teller = 0;
$endTijd = microtime(true) + 1.0;
while ($endTijd >= microtime(true)) {
    // Don't output anything here
    $teller++;
}
echo 'Iteratie: ' . $teller . '<br>';


问:
Your site 'www.xxxxx.com' has not been linked through the Digital Assets Link protocol to your app
I have try many times for upload an instant app, but always get this error at google play console.

Your site 'www.builtbee.com' has not been linked through the Digital Assets Link protocol to your app. Please link your site through the Digital Assets Link protocol to your app.

Here is my manifest....

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

```<code><uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="asset_statements"
        android:resource="@string/asset_statements" />

    <activity
        android:name=".Home"
        android:screenOrientation="portrait">

        <meta-data
            android:name="default-url"
            android:value="https://www.builtbee.com" />

        <intent-filter
            android:autoVerify="true"
            android:order="1">

            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:host="www.builtbee.com" />
            <data android:pathPattern="/instantApp" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>
</code>```

and i have pass the digital asset link with my release keystore file.

https://i.stack.imgur.com/UvcTR.png

Am I miss something?

Thanks

答: Agree with Kaze, I was having the same issue and finally figured out it was because you need to put in the digital asset link file, the app release key and not the upload key you pull from the google play console.</p>

Body:
I have try many times for upload an instant app, but always get this error at google play console.

Your site 'www.builtbee.com' has not been linked through the Digital Assets Link protocol to your app. Please link your site through the Digital Assets Link protocol to your app.

Here is my manifest....

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

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="asset_statements"
        android:resource="@string/asset_statements" />

    <activity
        android:name=".Home"
        android:screenOrientation="portrait">

        <meta-data
            android:name="default-url"
            android:value="https://www.builtbee.com" />

        <intent-filter
            android:autoVerify="true"
            android:order="1">

            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:host="www.builtbee.com" />
            <data android:pathPattern="/instantApp" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

and i have pass the digital asset link with my release keystore file.

https://i.stack.imgur.com/UvcTR.png

Am I miss something?

Thanks


问:
Record Map Changes with JaVers
Is it possible to record changes to values in a Map with JaVers?

I would like to record all changes (Add, Update and Remove) to my RecordStore object so that I have an audit trail of what has happened. At the moment, I'm using the following code, and committing after every change.

```<code>private Map<String, Record> records = new HashMap<>();
private Javers history = JaversBuilder.javers().build();

public RecordStore(){
    history.commit("user", records);
}

public void addRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", records);
}
public void removeRecord(Record a){
    records.remove(a.getId());
    history.commit("user", records);
}
public void updateRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", records);
}

public String printHistory(){
    List<Change> changes = history.findChanges(QueryBuilder.anyDomainObject().build());
    return history.processChangeList(changes, new SimpleTextChangeLog());
}
</code>```

However, the change list produced by JaVers (printHistory()) only has EntryAdded and EntryRemoved records in it. Worse than that, it is using the changed value throughout the log rather than only after the change. I've not used JaVers before, so any help getting it to work as desired would be appreciated. A test class using the RecordStore is below:

```<code>public static void main(String[] args){
    RecordStore store = new RecordStore();

    Record a1 = new Record();
    a1.setStart(0);
    a1.setEnd(5);
    a1.setValue("James");
    store.addRecord(a1);

    Record a2 = new Record();
    a2.setStart(10);
    a2.setEnd(15);
    a2.setValue("Jimmy");
    store.addRecord(a2);

    Record a3 = new Record();
    a3.setStart(20);
    a3.setEnd(25);
    a3.setValue("Jimbo");
    store.addRecord(a3);

    a2.setValue("JIMMY");
    store.updateRecord(a2);

    store.removeRecord(a1);

    System.out.println(store.printHistory());
}
</code>```

答:
Usually, you commit domain objects one by one, for example:

```<code>public void addRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", a);
}
public void removeRecord(Record a){
    records.remove(a.getId());
    history.commitShallowDelete("user", a);
}
public void updateRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", a);
}
</code>```

but then, Record should be mapped as Entity type (with @Id).

Title: Record Map Changes with JaVers

Body:
Is it possible to record changes to values in a Map with JaVers?

I would like to record all changes (Add, Update and Remove) to my RecordStore object so that I have an audit trail of what has happened. At the moment, I'm using the following code, and committing after every change.

private Map<String, Record> records = new HashMap<>();
private Javers history = JaversBuilder.javers().build();

public RecordStore(){
    history.commit("user", records);
}

public void addRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", records);
}
public void removeRecord(Record a){
    records.remove(a.getId());
    history.commit("user", records);
}
public void updateRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", records);
}

public String printHistory(){
    List<Change> changes = history.findChanges(QueryBuilder.anyDomainObject().build());
    return history.processChangeList(changes, new SimpleTextChangeLog());
}

However, the change list produced by JaVers (printHistory()) only has EntryAdded and EntryRemoved records in it. Worse than that, it is using the changed value throughout the log rather than only after the change. I've not used JaVers before, so any help getting it to work as desired would be appreciated. A test class using the RecordStore is below:

public static void main(String[] args){
    RecordStore store = new RecordStore();

    Record a1 = new Record();
    a1.setStart(0);
    a1.setEnd(5);
    a1.setValue("James");
    store.addRecord(a1);

    Record a2 = new Record();
    a2.setStart(10);
    a2.setEnd(15);
    a2.setValue("Jimmy");
    store.addRecord(a2);

    Record a3 = new Record();
    a3.setStart(20);
    a3.setEnd(25);
    a3.setValue("Jimbo");
    store.addRecord(a3);

    a2.setValue("JIMMY");
    store.updateRecord(a2);

    store.removeRecord(a1);

    System.out.println(store.printHistory());
}

Body:
Usually, you commit domain objects one by one, for example:

public void addRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", a);
}
public void removeRecord(Record a){
    records.remove(a.getId());
    history.commitShallowDelete("user", a);
}
public void updateRecord(Record a){
    records.put(a.getId(), a);
    history.commit("user", a);
}

but then, Record should be mapped as Entity type (with @Id).


问:
How to move a file from a model's folder to another?
I have two models [1] TempFile(models.Model) and Company(models.Model) , when the view [2] save_records(request) is called I'd like to save & move the image from TempFile(models.Model) which is in folder /temporary_files/ to Company(models.Model) which is in folder /company_logo/.

[1] models.py

```<code>class Company(models.Model):
    logo = models.FileField(upload_to="company_logo")
    ...

class TempFile(models.Model):
    unique_id = models.CharField(max_length=8)
    image = models.FileField(upload_to="temporary_files")
    ...
</code>```

[2] views.py

```<code>def save_records(request):
    if request.method == 'POST':
        temp_file = TempFile.objects.get(unique_id=request.session['uuid'])

        Company.objects.create(
            logo = temp_file.image
            ...
        )
</code>```

Here's the problem with this method, while the logo is saved the path of the folder stays /temporary_files/. I'd like to know how to save or move the image without quality loss and performance issue to Company(models.Model)'s company_logo folder ?

答:
If you are using file system storage, then the most efficient option is to move the file on disk (see this part of the documentation):

```<code>import os
from django.conf import settings

temp_file = TempFile.objects.get(unique_id=request.session['uuid'])

# Move the file
old_path = temp_file.image.path
filename = os.path.basename(old_path)
new_path = os.path.join(settings.MEDIA_ROOT, 'company_logo', filename)
os.rename(old_path, new_path)
temp_file.save()

Company.objects.create(
    logo = temp_file.image
)
</code>```

Note that the path of temp_file.image has also changed - presumably you will be deleting that object once you've saved the Company object.

Body:
I have two models [1] TempFile(models.Model) and Company(models.Model) , when the view [2] save_records(request) is called I'd like to save & move the image from TempFile(models.Model) which is in folder /temporary_files/ to Company(models.Model) which is in folder /company_logo/.

[1] models.py

class Company(models.Model):
    logo = models.FileField(upload_to="company_logo")
    ...

class TempFile(models.Model):
    unique_id = models.CharField(max_length=8)
    image = models.FileField(upload_to="temporary_files")
    ...

[2] views.py

def save_records(request):
    if request.method == 'POST':
        temp_file = TempFile.objects.get(unique_id=request.session['uuid'])

        Company.objects.create(
            logo = temp_file.image
            ...
        )

Here's the problem with this method, while the logo is saved the path of the folder stays /temporary_files/. I'd like to know how to save or move the image without quality loss and performance issue to Company(models.Model)'s company_logo folder ?

Body:
If you are using file system storage, then the most efficient option is to move the file on disk (see this part of the documentation):

import os
from django.conf import settings

temp_file = TempFile.objects.get(unique_id=request.session['uuid'])

# Move the file
old_path = temp_file.image.path
filename = os.path.basename(old_path)
new_path = os.path.join(settings.MEDIA_ROOT, 'company_logo', filename)
os.rename(old_path, new_path)
temp_file.save()

Company.objects.create(
    logo = temp_file.image
)

Note that the path of temp_file.image has also changed - presumably you will be deleting that object once you've saved the Company object.


问:
Jenkinsfile junit report file path as variable
Good day all,

I have below code in my Jenkinsfile:

finally {
    try {
        sh "cat \"${report_file}\""
        junit "${report_file}"
    }
    catch (e) {
        echo "ERROR: Can't operate junit xml results'"
        echo e.toString()
    }
}
```

<p>The result is when run is below:</p>

```> [] Running shell script cat
> '/var/lib/jenkins/workspace//Sanity/authenticate/keystone.json/report.junit.xml'
> <testsuites>      <testsuite errors="0" failures="0"
> id="" skipped="0" tests="1"
> time="15.00" timestamp="2017-12-08T18:26:17">
>     <testcase classname="Authenticate" id="" name="keystone" time="2.78"
> timestamp="2017-12-08T18:26:27" />   </testsuite> </testsuites>
>
> [Pipeline] junit Recording test results [Pipeline] echo ERROR: Can't
> operate junit xml results' [Pipeline] echo hudson.AbortException: No
> test report files were found. Configuration error?
```

The report is there but junit step cannot read the variable. Is this possible?

Many thanks

答:
Don't specify an absolute path to the test result file. This somehow does not work with the junit step.

The following code works for me:

node {
    // def path =  env.WORKSPACE + '/junit.xml'
    def path = 'junit.xml'
    writeFile file: path, text: '<testsuites>   <testsuite errors="0" failures="0" id="" skipped="0" tests="1" time="15.00" timestamp="2017-12-08T18:26:17"><testcase classname="Authenticate" id="" name="keystone" time="2.78" timestamp="2017-12-08T18:26:27" /></testsuite></testsuites>'
    echo path
    junit path
}
```

<p>with output</p>

<pre class="lang-none prettyprint-override"><code>Running on Jenkins in /var/jenkins_home/workspace/Pipeline
[Pipeline] {
[Pipeline] writeFile
[Pipeline] echo
junit.xml
[Pipeline] junit
Recording test results
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

Using an absolute path:

node {
    def path =  env.WORKSPACE + '/junit.xml'
    // def path = 'junit.xml'
    writeFile file: path, text: '<testsuites>   <testsuite errors="0" failures="0" id="" skipped="0" tests="1" time="15.00" timestamp="2017-12-08T18:26:17"><testcase classname="Authenticate" id="" name="keystone" time="2.78" timestamp="2017-12-08T18:26:27" /></testsuite></testsuites>'
    echo path
    junit path
}
```

<p>the <code>junit</code> step <strong>fails</strong> to find test results:</p>

<pre class="lang-none prettyprint-override"><code>Running on Jenkins in /var/jenkins_home/workspace/Pipeline
[Pipeline] {
[Pipeline] writeFile
[Pipeline] echo
/var/jenkins_home/workspace/Pipeline/junit.xml
[Pipeline] junit
Recording test results
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: No test report files were found. Configuration error?
Finished: FAILURE
</code>```

Body:
Good day all,

I have below code in my Jenkinsfile:

finally {
    try {
        sh "cat \"${report_file}\""
        junit "${report_file}"
    }
    catch (e) {
        echo "ERROR: Can't operate junit xml results'"
        echo e.toString()
    }
}

The result is when run is below:

> [] Running shell script cat
> '/var/lib/jenkins/workspace//Sanity/authenticate/keystone.json/report.junit.xml'
> <testsuites>      <testsuite errors="0" failures="0"
> id="" skipped="0" tests="1"
> time="15.00" timestamp="2017-12-08T18:26:17">
>     <testcase classname="Authenticate" id="" name="keystone" time="2.78"
> timestamp="2017-12-08T18:26:27" />   </testsuite> </testsuites>
>
> [Pipeline] junit Recording test results [Pipeline] echo ERROR: Can't
> operate junit xml results' [Pipeline] echo hudson.AbortException: No
> test report files were found. Configuration error?

The report is there but junit step cannot read the variable. Is this possible?

Many thanks

Body:
Don't specify an absolute path to the test result file. This somehow does not work with the junit step.

The following code works for me:

node {
    // def path =  env.WORKSPACE + '/junit.xml'
    def path = 'junit.xml'
    writeFile file: path, text: '<testsuites><!--Report is generated by Rally 0.10.1~dev35 at 2017-12-08T18:26:40-->   <testsuite errors="0" failures="0" id="" skipped="0" tests="1" time="15.00" timestamp="2017-12-08T18:26:17"><testcase classname="Authenticate" id="" name="keystone" time="2.78" timestamp="2017-12-08T18:26:27" /></testsuite></testsuites>'
    echo path
    junit path
}

with output

Running on Jenkins in /var/jenkins_home/workspace/Pipeline
[Pipeline] {
[Pipeline] writeFile
[Pipeline] echo
junit.xml
[Pipeline] junit
Recording test results
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Using an absolute path:

node {
    def path =  env.WORKSPACE + '/junit.xml'
    // def path = 'junit.xml'
    writeFile file: path, text: '<testsuites><!--Report is generated by Rally 0.10.1~dev35 at 2017-12-08T18:26:40-->   <testsuite errors="0" failures="0" id="" skipped="0" tests="1" time="15.00" timestamp="2017-12-08T18:26:17"><testcase classname="Authenticate" id="" name="keystone" time="2.78" timestamp="2017-12-08T18:26:27" /></testsuite></testsuites>'
    echo path
    junit path
}

the junit step fails to find test results:

Running on Jenkins in /var/jenkins_home/workspace/Pipeline
[Pipeline] {
[Pipeline] writeFile
[Pipeline] echo
/var/jenkins_home/workspace/Pipeline/junit.xml
[Pipeline] junit
Recording test results
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: No test report files were found. Configuration error?
Finished: FAILURE


问:
How to Insert Session Array into MySQL DB using PHP
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

```<code>if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];
</code>```

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

```<code> $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";
</code>```

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

```<code> foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";
</code>```

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

```<code> <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>
<tr class="odd">
    <td width="33%">Street/Number</td>
    <td><input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/></td>
</tr>
<tr>
    <td>Address 2</td>
    <td><input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/></td>
</tr>
 <?php endfor; ?>
</code>```

Submit.php doesn't have anything besides connecting to the db and the above insert.

答:
As well:

```<code>$insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo) VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";
</code>```

You're using double-quoted strings, so the ' single quotes within the query won't "break out" of string mode, so if $id,$addressLineOneand$addressLineTwo` are blank for whatever reason, your query ends up looking like:

```<code>INSERT INTO ... VALUES ('..', '..', '..')
</code>```

which explains why you're getting dots in your fields.

Either rewrite the query to be

```<code>$insertAddress = "INSERT .... VALUES ('$id', '$addressLineOne', '$addressLineTwo')
</code>```

or

```<code>$insertAddress = 'INSERT ... VALUES (\'' . $id . '\', \'' ....)
</code>```

Personally, directly writing variables into double-quoted strings leads to far more readable code, especially in a syntax highlighting editor which is PHP-aware.

Body:
I have a multi page form and am trying to capture an array as a session to insert into mysql. Page two of the form is the  "Address" section. Here I ask for Address information. The user can hit a "enter another address" button which expands another box.

The user hits next to go to the next page (phone.php) where I ask for phone info. On this page I think I am  registering the session data correctly like so:

if(!isset($_SESSION))
{
@session_start();
}
header("Cache-control: private");
ob_start();

include('header.php');

//now, let's register our session variables from address.php
session_register('addressLineOne');
session_register('addressLineTwo');

//finally, let's store our posted values in the session variables
$_SESSION['addressLineOne'] = $_POST['addressLineOne'];
$_SESSION['addressLineTwo'] = $_POST['addressLineTwo'];

Eventually we hit the submit.php . If I disable the code to add an additional address, this is the insert I am using which works fine.

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ( '$id','$_SESSION[addressLineOne]','$_SESSION[addressLineTwo]')";
 if (!mysql_query($insertAddress,$con))
   {die('Error: ' . mysql_error());}
 echo "";

When I enable the "add additional address" code, the insert above will insert "ARRAY" into every DB field. I have been trying out the following:

 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=$id;
    $addressLineOne=$_SESSION['addressLineOne'][$row];
    $addressLineTwo=$_SESSION['addressLineTwo'][$row];
}
 //enter rows into database
 foreach($_SESSION['idperson'] as $row=>$id)
{
    $idperson=mysql_real_escape_string($id);
    $addressLineOne=mysql_real_escape_string($_SESSION['addressLineOne'][$row]);
    $addressLineTwo=mysql_real_escape_string($_SESSION['addressLineTwo'][$row]);
}

 $insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo)
 VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

 if (!mysql_query($insertAddress,$con))
 {
 die('Error: ' . mysql_error());
 }
 echo "$row record added";

Instead of working, however, the above just inserts a couple of dots like "..." into the database. I don't know what else to do. Am I not grabbing the session data correctly? Is my foreach code way off? Thanks for any help.

Here is the code i'm using to add another table on address.php:

 <?php for($i=1; $i<6; $i++):?>
 <div id='hidden<?php echo $i; ?>' style='display: none'>

    Street/Number
    <input type="text" name="addressLineOne[]" id="addressLineOne<?php echo $i; ?>"/>

    Address 2
    <input type="text" name="addressLineTwo[]" id="addressLineTwo<?php echo $i; ?>"/>

 <?php endfor; ?>

Submit.php doesn't have anything besides connecting to the db and the above insert.

Body:
As well:

$insertAddress="INSERT INTO address (idperson, addressLineOne, addressLineTwo) VALUES ('.$id.','.$addressLineOne.','.$addressLineTwo.')";

You're using double-quoted strings, so the ' single quotes within the query won't "break out" of string mode, so if $id,$addressLineOneand$addressLineTwo` are blank for whatever reason, your query ends up looking like:

INSERT INTO ... VALUES ('..', '..', '..')

which explains why you're getting dots in your fields.

Either rewrite the query to be

$insertAddress = "INSERT .... VALUES ('$id', '$addressLineOne', '$addressLineTwo')

or

$insertAddress = 'INSERT ... VALUES (\'' . $id . '\', \'' ....)

Personally, directly writing variables into double-quoted strings leads to far more readable code, especially in a syntax highlighting editor which is PHP-aware.


问:
How to return readonly fields?
Error is

"A readonly field cannot be assigned to(...)"

I must return vector, which equal sum of two another vectors (vector and vector1)
ReadOnlyVector has readonly fields X and Y. How can I initialize them and return new ReadOnlyVector?

```<code>public class ReadOnlyVector
    {
        public readonly double X;
        public readonly double Y;
        public ReadOnlyVector(int x, int y)
        {
            X = x;
            Y = y;
        }
        public ReadOnlyVector Add (ReadOnlyVector vector, ReadOnlyVector vector1)
        {
            return new ReadOnlyVector {X = vector.X + vector1.X, Y = vector.Y + vector1.Y}
        }
    }
</code>```

答:
Use the constructor. You're currently using object initializer syntax.</p>

```<code>public ReadOnlyVector Add (ReadOnlyVector vector, ReadOnlyVector vector1)
{
    return new ReadOnlyVector(vector.X + vector1.X, vector.Y + vector1.Y);
}
</code>```

Title: How to return readonly fields?

Body:
Error is

"A readonly field cannot be assigned to(...)"

I must return vector, which equal sum of two another vectors (vector and vector1)
ReadOnlyVector has readonly fields X and Y. How can I initialize them and return new ReadOnlyVector?

public class ReadOnlyVector
    {
        public readonly double X;
        public readonly double Y;
        public ReadOnlyVector(int x, int y)
        {
            X = x;
            Y = y;
        }
        public ReadOnlyVector Add (ReadOnlyVector vector, ReadOnlyVector vector1)
        {
            return new ReadOnlyVector {X = vector.X + vector1.X, Y = vector.Y + vector1.Y}
        }
    }

Body:
Use the constructor. You're currently using object initializer syntax.

public ReadOnlyVector Add (ReadOnlyVector vector, ReadOnlyVector vector1)
{
    return new ReadOnlyVector(vector.X + vector1.X, vector.Y + vector1.Y);
}


问:
Adding radio button to the DT Data Table in R Shiny
I need to add radio button to one of the column of DT Data Table and on selection of radio button need to have the popup with a button. I am able accomplish the same using action button , looking for the ways to achieve the same using radio button. Code with action button:

```<code>library(shiny)
library(DT)
library(shinyBS)

shinyApp(
ui <- fluidPage(
actionButton("Refresh","Refresh"),
br(),
br(),
DT::dataTableOutput("table"),uiOutput("popup")
),

server <- function(input, output,session) {

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

df <- reactiveValues(data = data.frame(
  cbind(Delete = shinyInput(actionButton,nrow(mtcars),'button_', label = " ",onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'),
        mtcars)
))

output$table <- DT::renderDataTable(
  df$data, server = FALSE, escape = FALSE, selection = 'none'
)

observeEvent(input$select_button, {
  toggleModal(session, "modalExample", "open")
})

SelectedRow <- eventReactive(input$select_button,{
  as.numeric(strsplit(input$select_button, "_")[[1]][2])
})

output$popup <- renderUI({
  bsModal("modalExample", "Do you want to delete the row?", "", size = "large",
          actionButton("Delete","Delete")
  )
})

observeEvent(input$Refresh,{
  mtcars <<- retrieveValues()
  df$data <-  data.frame(
    cbind(Delete = shinyInput(actionButton,nrow(mtcars),'button_', label = HTML('<input type="radio" name="radio" value="1"/>'),onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'),
          mtcars)
  )
})

}
)
</code>```

答:
Code

```<code>shinyApp(
ui = fluidPage(
title = 'Radio buttons in a table',
tags$div(id="C",class='shiny-input-radiogroup',DT::dataTableOutput('foo')),
verbatimTextOutput("test")
),

server = function(input, output, session) {
m = matrix(
  c(round(rnorm(24),1), rep(3,12)), nrow = 12, ncol = 3, byrow = F,
  dimnames = list(month.abb, LETTERS[1:3])
)
for (i in seq_len(nrow(m))) {
  m[i, 3] = sprintf(

    '<input type="radio" name="%s" value="%s"/>',

    "C", month.abb[i]
  )
}
m
output$foo = DT::renderDataTable(
  m, escape = FALSE, selection = 'single', server = FALSE,
  options = list(dom = 't', paging = FALSE, ordering = FALSE)
)
output$test <- renderPrint(str(input$C))

output$popup <- renderUI({
  bsModal("modalExample", "Do you want to delete the row?", "", size = "large",
          actionButton("Delete","Delete")
  )
})

observeEvent(input$C, {

  #print("TESTING")

  showModal(modalDialog(
    title = "Do you want to delete the row?",
    actionButton("delete","Delete"),
    size = "l",
    easyClose = TRUE,
    fade = TRUE,
    footer = tagList(
      modalButton("Close")
    )

  ))

})

})
</code>```

Body:
I need to add radio button to one of the column of DT Data Table and on selection of radio button need to have the popup with a button. I am able accomplish the same using action button , looking for the ways to achieve the same using radio button. Code with action button:

library(shiny)
library(DT)
library(shinyBS)

shinyApp(
ui <- fluidPage(
actionButton("Refresh","Refresh"),
br(),
br(),
DT::dataTableOutput("table"),uiOutput("popup")
),

server <- function(input, output,session) {

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), ...))
  }
  inputs
}

df <- reactiveValues(data = data.frame(
  cbind(Delete = shinyInput(actionButton,nrow(mtcars),'button_', label = " ",onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'),
        mtcars)
))

output$table <- DT::renderDataTable(
  df$data, server = FALSE, escape = FALSE, selection = 'none'
)

observeEvent(input$select_button, {
  toggleModal(session, "modalExample", "open")
})

SelectedRow <- eventReactive(input$select_button,{
  as.numeric(strsplit(input$select_button, "_")[[1]][2])
})

output$popup <- renderUI({
  bsModal("modalExample", "Do you want to delete the row?", "", size = "large",
          actionButton("Delete","Delete")
  )
})

observeEvent(input$Refresh,{
  mtcars <<- retrieveValues()
  df$data <-  data.frame(
    cbind(Delete = shinyInput(actionButton,nrow(mtcars),'button_', label = HTML('<input type="radio" name="radio" value="1"/>'),onclick = 'Shiny.onInputChange(\"select_button\",  this.id)'),
          mtcars)
  )
})

}
)

Body:
Code

shinyApp(
ui = fluidPage(
title = 'Radio buttons in a table',
tags$div(id="C",class='shiny-input-radiogroup',DT::dataTableOutput('foo')),
verbatimTextOutput("test")
),

server = function(input, output, session) {
m = matrix(
  c(round(rnorm(24),1), rep(3,12)), nrow = 12, ncol = 3, byrow = F,
  dimnames = list(month.abb, LETTERS[1:3])
)
for (i in seq_len(nrow(m))) {
  m[i, 3] = sprintf(

    '<input type="radio" name="%s" value="%s"/>',

    "C", month.abb[i]
  )
}
m
output$foo = DT::renderDataTable(
  m, escape = FALSE, selection = 'single', server = FALSE,
  options = list(dom = 't', paging = FALSE, ordering = FALSE)
)
output$test <- renderPrint(str(input$C))

output$popup <- renderUI({
  bsModal("modalExample", "Do you want to delete the row?", "", size = "large",
          actionButton("Delete","Delete")
  )
})

observeEvent(input$C, {

  #print("TESTING")

  showModal(modalDialog(
    title = "Do you want to delete the row?",
    actionButton("delete","Delete"),
    size = "l",
    easyClose = TRUE,
    fade = TRUE,
    footer = tagList(
      modalButton("Close")
    )

  ))

})

})


问:
jQuery Close div if clicked outside div
```<code><li class="dropdown-grid open">
  <a class="dropdown-toggle" id="ddaccount" aria-expanded="false">
    <i class="fa fa-lock"></i> <span class="hidden-sm hidden-md hidden-lg">User Account</span><span class="caret"></span>
  </a>
  <div role="menu" class="dropdown-grid-wrapper">
    <ul class="dropdown-menu col-xs-12 col-sm-10 col-md-8 col-lg-7">
      <li>
        <div data-ride-class="carousel slide" id="carousel-example-account">
          <div class="row">
            <div class="col-lg-8 col-md-8 col-sm-8">
              <div class="carousel-inner">
                <div class="item active">
                  <h3 class="text-right"><i class="fa fa-lock"></i> Login</h3><br>

                </div>
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>
  </div>
</li>
</code>```

In above code i have one ul element that when i click on button it needs to add open class to li element and that is working fine...but problem is that i want one more function in jQuery that when user click inside that open div that it does not close....but only to close that div if user click outside that div...

working that when i click on button that add class open:

```<code>$("li").on("click","a.dropdown-toggle",function(e){
    $('li.dropdown-grid').toggleClass("open");
    e.stopPropagation();
  });
</code>```

NOT WORKING...when user click inside that open div it needs NOT to close...and when user click outside that open div it needs to close that div (remove class open)

```<code>$(document).on("click", function(e) {
    if ($(e.currentTarget).is("a.dropdown-toggle") === false) {
      $('li.dropdown-grid').removeClass("open");
      console.log("close menu clicked outside ul...");
    }
  });
</code>```

i don't know why it closes inside open div (outside div click close and that is fine) but it close also if i click inside that div and i need to not to close when i click inside that div...where i do wrong in above code?

答:
I added this and now is working..it is not elegant and clean way (length === 0) but if works if someone knows more elegant way please post...this works for me...</p>

```<code>$(document).on("click", function(e) {
    if ($(e.target).closest('li.dropdown-grid').length === 0) {
      $('li.dropdown-grid').removeClass("open");
    }
  });
</code>```

Title: jQuery Close div if clicked outside div

Body:
     User Account

 Login

In above code i have one ul element that when i click on button it needs to add open class to li element and that is working fine...but problem is that i want one more function in jQuery that when user click inside that open div that it does not close....but only to close that div if user click outside that div...

working that when i click on button that add class open:

$("li").on("click","a.dropdown-toggle",function(e){
    $('li.dropdown-grid').toggleClass("open");
    e.stopPropagation();
  });

NOT WORKING...when user click inside that open div it needs NOT to close...and when user click outside that open div it needs to close that div (remove class open)

$(document).on("click", function(e) {
    if ($(e.currentTarget).is("a.dropdown-toggle") === false) {
      $('li.dropdown-grid').removeClass("open");
      console.log("close menu clicked outside ul...");
    }
  });

i don't know why it closes inside open div (outside div click close and that is fine) but it close also if i click inside that div and i need to not to close when i click inside that div...where i do wrong in above code?

Body:
I added this and now is working..it is not elegant and clean way (length === 0) but if works if someone knows more elegant way please post...this works for me...

$(document).on("click", function(e) {
    if ($(e.target).closest('li.dropdown-grid').length === 0) {
      $('li.dropdown-grid').removeClass("open");
    }
  });


问:
Printing only the duplicates from an int array and how many times they occur
I am trying to print only the duplicate elements from an array and how many times each of them appear.

Example:

```<code>Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times
</code>```

My code prints all the elements of the array rather than printing only duplicate elements.

I must mention that i cannot use HashMap, only conditional statments.

 Thanks
Below is the code :

```<code>    int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
    int counter = 0, temp = 0;// variable that holds the temporary value of each element
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        temp = array[i];
        counter = 0;
        for (int j = 0; j < array.length; j++) {
            if (temp == array[j]) {
                counter++;
            }
        }
        System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
    }
</code>```

答:
One simple solution here would be to use a map to count the number of occurrences of each digit.  Then, iterate the map and report any number having a count of two or more.

```<code>int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
Map<Integer, Integer> map = new HashMap<>();
for (int num : array) {
    Integer count = map.get(num);
    map.put(num, count == null ? 1 : count.intValue() + 1);
}

// now iterate the map
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    Integer num = entry.getKey();
    Integer count = entry.getValue();
    if (count > 1) {
        System.out.println("Number: " + num + ", occurs: " + count + " times");
    }
}
</code>```

Demo

Body:
I am trying to print only the duplicate elements from an array and how many times each of them appear.

Example:

Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times

My code prints all the elements of the array rather than printing only duplicate elements.

I must mention that i cannot use HashMap, only conditional statments.

 Thanks
Below is the code :

    int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
    int counter = 0, temp = 0;// variable that holds the temporary value of each element
    Arrays.sort(array);
    for (int i = 0; i < array.length; i++) {
        temp = array[i];
        counter = 0;
        for (int j = 0; j < array.length; j++) {
            if (temp == array[j]) {
                counter++;
            }
        }
        System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
    }

Body:
One simple solution here would be to use a map to count the number of occurrences of each digit.  Then, iterate the map and report any number having a count of two or more.

int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
Map<Integer, Integer> map = new HashMap<>();
for (int num : array) {
    Integer count = map.get(num);
    map.put(num, count == null ? 1 : count.intValue() + 1);
}

// now iterate the map
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    Integer num = entry.getKey();
    Integer count = entry.getValue();
    if (count > 1) {
        System.out.println("Number: " + num + ", occurs: " + count + " times");
    }
}

Demo


问:
Java Generics: Error when using innerclass
Based on the answer: https://stackoverflow.com/a/47693998/8760211

Following Compile Error occurs, when I try to sort a list with elements of Type Student from within the class Invoker.
Student is an innerclass of class University:

```<code>Type mismatch: cannot convert from ToIntFunction<University.Student> to ToIntFunction<? super T>
</code>```

Code:

```<code>public class University implements Serializable {
    private List<Student> values = new ArrayList<Student>();

    public static final class Student implements Serializable {
        private int id;
        private String name;
        private String location;
        private Date date;

        Student(int id, String name, String location, Date date) {
            this.id = id;
            this.name = name;
            this.location = location;
            this.date = date;
        }

        // Problem occurs even with getters!!
}

public class Invoker implements Serializable {
    public static void main(String[] args) {
        List<University.Student> students = new ArrayList<>();

        Map<String, Integer> locationOrder = students.stream().collect(HashMap::new,
                (m, s) -> m.putIfAbsent(s.getName(), m.size()),
                (m1, m2) -> m2.keySet().forEach(l -> m1.putIfAbsent(l, m1.size())));

        students.sort(Comparator.comparingInt((University.Student s) -> locationOrder.get(s.name)).thenComparing(s -> s.id));
    }
}
</code>```

The following code snippet is marked in IDE as cause of the Compiler error:
comparingInt((University.Student s) -> locationOrder.get(s.name)

If I move the innerclass into the class Invoker everything works fine!!

Any help would be much appreciated.
Thanks in advance.

答:
Try changing it to this</p>

```<code>students.sort(Comparator.<University.Student>comparingInt(s -> locationOrder.get(s.name)).thenComparing(s -> s.id));
</code>```

Body:
Based on the answer: https://stackoverflow.com/a/47693998/8760211

Following Compile Error occurs, when I try to sort a list with elements of Type Student from within the class Invoker.
Student is an innerclass of class University:

Type mismatch: cannot convert from ToIntFunction<University.Student> to ToIntFunction<? super T>

Code:

public class University implements Serializable {
    private List<Student> values = new ArrayList<Student>();

    public static final class Student implements Serializable {
        private int id;
        private String name;
        private String location;
        private Date date;

        Student(int id, String name, String location, Date date) {
            this.id = id;
            this.name = name;
            this.location = location;
            this.date = date;
        }

        // Problem occurs even with getters!!
}

public class Invoker implements Serializable {
    public static void main(String[] args) {
        List<University.Student> students = new ArrayList<>();

        Map<String, Integer> locationOrder = students.stream().collect(HashMap::new,
                (m, s) -> m.putIfAbsent(s.getName(), m.size()),
                (m1, m2) -> m2.keySet().forEach(l -> m1.putIfAbsent(l, m1.size())));

        students.sort(Comparator.comparingInt((University.Student s) -> locationOrder.get(s.name)).thenComparing(s -> s.id));
    }
}

The following code snippet is marked in IDE as cause of the Compiler error:
comparingInt((University.Student s) -> locationOrder.get(s.name)

If I move the innerclass into the class Invoker everything works fine!!

Any help would be much appreciated.
Thanks in advance.

Body:
Try changing it to this

students.sort(Comparator.<University.Student>comparingInt(s -> locationOrder.get(s.name)).thenComparing(s -> s.id));


问:
MBProgressHUD can not show
I am using MBProgressHUD to show user a tip, but it is not showing. There are many viewcontrollers that use the same method. Only one page can not show it, this view controller is created with xib.
the method is following:

```<code>-(void)creatHUD:(NSString *)hud {

    if (!HUD) {
        HUD = [[MBProgressHUD alloc] initWithView:self.view] ;
        [self.view addSubview:HUD];
        HUD.delegate = self;
    }
    HUD.labelText = hud;
}
</code>```

答:
If you are developing in swift try this one</p>

```<code>DispatchQueue.main.async {

        MBProgressHUD.showAdded(to: UIApplication.shared.keyWindow!, animated: true)
    }
</code>```

Title: MBProgressHUD can not show

Body:
I am using MBProgressHUD to show user a tip, but it is not showing. There are many viewcontrollers that use the same method. Only one page can not show it, this view controller is created with xib.
the method is following:

-(void)creatHUD:(NSString *)hud {

    if (!HUD) {
        HUD = [[MBProgressHUD alloc] initWithView:self.view] ;
        [self.view addSubview:HUD];
        HUD.delegate = self;
    }
    HUD.labelText = hud;
}

Body:
If you are developing in swift try this one

DispatchQueue.main.async {

        MBProgressHUD.showAdded(to: UIApplication.shared.keyWindow!, animated: true)
    }


问:
iOS 4.x: UIWebView iframe Scrolling
I'm using a UIWebView to show an html page with an iframe in it.

The UIWebView has myWebView.scalesPageToFit = YES;

and the page itself has

<meta name="viewport" content="width=320,user-scalable=yes"/>

Under 3.2 , the iframe had very nice scrollbars and I could scale and double tap the contents of the iframe, which is a javascript-dynamically loaded PDF. Under 4.x , it's not interactive at all and has no scrollbars. Yes, this is the same code.

I'm not aware of any new flags for this behavior under 4.x. Are you? Or will I have to end up making a UITextView and loading the PDF there?

答:
From the discussion on a duplicate question someone asked later, and in light of Apple's own documentation stating this should be possible, it sounds like this is a (annoying) bug in recent versions of iOS:
IFRAMEs and the Safari on the iPad, how can the user scroll the content?

I've filed rdar://problem/8904584 with Apple, if this is affecting you please (everyone) file a duplicate at http://bugreport.apple.com referencing that bug number.

Title: iOS 4.x: UIWebView iframe Scrolling