问:
Unseting a list of dynamic variables in Bash
How can I achieve the following with Bash:

```<code>x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
# prints something
# etc.

# (I am trying to do something here)
# So the following wouldn't print **something** anymore

echo $search
</code>```

I basically want to unset the variables that were set using eval initially.

答:
Preamble: Care using eval as eval is evil...

Whatever...

bash could do this very quickly:

```<code>unset ${x//=*([^ ])}
</code>```

As pointed out by glenn jackman, this work only if there are no spaces in content of variables.

In this case, we could (very quickly too) prepare some intermediary variable (x without spaces):

```<code>xwos=${x//\"*([^\"])\"}        # This will drop `search="don't know"`
xwos=${xwos//\'*([^\'])\'}     # This will drop `search='blah blah'`
unset ${xwos//=*([^ ])}
</code>```

In fine, adding this to your script will do the job:

```<code>xwos=${x//\"*([^\"])\"}; xwos=${xwos//\'*([^\'])\'}; unset ${xwos//=*([^ ])}
</code>```

Explanation / showcase

Of course, you have to use extglob bash's option, if not already set:

```<code>shopt -s extglob
</code>```

Let's try:

```<code>x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
something something

declare -p search replace subject
declare -- search="something something"
declare -- replace="something"
declare -- subject="/path/path"

shopt -s extglob
xwos=${x//\"*([^\"])\"}
printf 'X w/o double quoted spaces 1st:\n    "%s"\n' "$xwos"
X w/o double quoted spaces 1st:
    "search='something something' replace='something' subject=/path/path"

xwos=${xwos//\'*([^\'])\'}
printf 'X w/o single quoted spaces 2nd:\n    "%s"\n' "$xwos"
X w/o single quoted spaces 2nd:
    "search= replace= subject=/path/path"

printf 'String containing variables w/o values:\n    "%s"\n' "${xwos//=*([^ ])}"
String containing variables w/o values:
    "search replace subject"

unset ${xwos//=*([^ ])}

declare -p search replace subject
bash: declare: search: not found
bash: declare: replace: not found
bash: declare: subject: not found
</code>```

Nota: If you don't need x anymore, you could redefine x instead of populating a new variable:

```<code>shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}
</code>```

Demo

```<code>x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
something something

shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}
echo $search

</code>```

Body:
How can I achieve the following with Bash:

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
# prints something
# etc.

# (I am trying to do something here)
# So the following wouldn't print **something** anymore

echo $search

I basically want to unset the variables that were set using eval initially.

Body:
Preamble: Care using eval as eval is evil...

Whatever...

bash could do this very quickly:

unset ${x//=*([^ ])}

As pointed out by glenn jackman, this work only if there are no spaces in content of variables.

In this case, we could (very quickly too) prepare some intermediary variable (x without spaces):

xwos=${x//\"*([^\"])\"}        # This will drop `search="don't know"`
xwos=${xwos//\'*([^\'])\'}     # This will drop `search='blah blah'`
unset ${xwos//=*([^ ])}

In fine, adding this to your script will do the job:

xwos=${x//\"*([^\"])\"}; xwos=${xwos//\'*([^\'])\'}; unset ${xwos//=*([^ ])}

Explanation / showcase

Of course, you have to use extglob bash's option, if not already set:

shopt -s extglob

Let's try:

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
something something

declare -p search replace subject
declare -- search="something something"
declare -- replace="something"
declare -- subject="/path/path"

shopt -s extglob
xwos=${x//\"*([^\"])\"}
printf 'X w/o double quoted spaces 1st:\n    "%s"\n' "$xwos"
X w/o double quoted spaces 1st:
    "search='something something' replace='something' subject=/path/path"

xwos=${xwos//\'*([^\'])\'}
printf 'X w/o single quoted spaces 2nd:\n    "%s"\n' "$xwos"
X w/o single quoted spaces 2nd:
    "search= replace= subject=/path/path"

printf 'String containing variables w/o values:\n    "%s"\n' "${xwos//=*([^ ])}"
String containing variables w/o values:
    "search replace subject"

unset ${xwos//=*([^ ])}

declare -p search replace subject
bash: declare: search: not found
bash: declare: replace: not found
bash: declare: subject: not found

Nota: If you don't need x anymore, you could redefine x instead of populating a new variable:

shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}

Demo

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
something something

shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}
echo $search


来源: stackexchange

问:
how to get Session in javascript from ASP.NET MVC
I have some belows , please help me how i can get Session in Javascript code from Controller ?

```<code>public ActionResult Login(FormCollection f)
    {
        string sAcount = f["txtAccount"].ToString();
        string sPassword = f.Get("txtPassword").ToString();

        tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

        if (cs != null)
        {

            Session["Account"] = cs;

            return View();

        }

        return View();

    }
</code>```

and JS code is

```<code>        <script >

       $('#btnSendMsg').click(function () {

                  var msg = $("#txtMessage").val();

                  alert('Hello' + Session["Account"] );
                 });

    <script/>
</code>```

the result is alert stil is not working, help me.

答:
You should not update sessions many times, the type of data stored in Sessions are User Roles, Page Permissions and other global information. Once the login is done you should set login cookie. For login, you should use FormsAuthentication cookie.

Follow set Forms authentication to set forms authentication cookie.
Or check this link Create Forms Authentication cookie.

In the page use

```<code>alert("@HttpContext.Current.User.Identity.Name");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some belows , please help me how i can get Session in Javascript code from Controller ?

public ActionResult Login(FormCollection f)
    {
        string sAcount = f["txtAccount"].ToString();
        string sPassword = f.Get("txtPassword").ToString();

        tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

        if (cs != null)
        {

            Session["Account"] = cs;

            return View();

        }

        return View();

    }

and JS code is

Body:
You should not update sessions many times, the type of data stored in Sessions are User Roles, Page Permissions and other global information. Once the login is done you should set login cookie. For login, you should use FormsAuthentication cookie.

Follow set Forms authentication to set forms authentication cookie.
Or check this link Create Forms Authentication cookie.

In the page use

alert("@HttpContext.Current.User.Identity.Name");


问:
How To Add List-style-type: "disc" to
 tag
This seems like it ought to be ridiculously easy, but I'm having trouble figuring it out.

I want to replicate the
 function so the disc image appears to the left, but applied to a
 tag

I have this, but it does not show the disc image.

```<code>.list {
     margin-top: 15px;
     margin-bottom: 15px;
     list-style:disc outside none;
     display:inline;
     }

<p class="list"><em>And Much, Much More!</em></p>
</code>```

I want to avoid using any graphics to simulate the bullet if at all possible.

Thanks for the help

答:
Well, a p is not a list. Why not use

?

[edit]
Let me elaborate.
The problem is that you set this style on a list, while the disc is shown in the list items. A p has no items in that sense, so there's nothing to apply the disc to.

ContentLicense: CC BY-SA 2.5

Title: How To Add List-style-type: "disc" to <p> tag

Body:
This seems like it ought to be ridiculously easy, but I'm having trouble figuring it out.

I want to replicate the
 function so the disc image appears to the left, but applied to a
 tag

I have this, but it does not show the disc image.

.list {
     margin-top: 15px;
     margin-bottom: 15px;
     list-style:disc outside none;
     display:inline;
     }

And Much, Much More!

I want to avoid using any graphics to simulate the bullet if at all possible.

Thanks for the help

Body:
Well, a p is not a list. Why not use <ul><li>?

[edit]
Let me elaborate.
The problem is that you set this style on a list, while the disc is shown in the list items. A p has no items in that sense, so there's nothing to apply the disc to.


问:
c++ return type pointer declaration
```
function:
name: make_shape
return: Shape*
parameters: const string &shape_name; const vector &data
```

The class is ShapeFactory. This is what I have for this function definition:

```<code> ShapeFactory::Shape* make_shape(const string &shape_name, const vector<double>&data)
</code>```

I get an error that says:

"ShapeFactory.cpp:17:15: error: ‘Shape’ in ‘class ShapeFactory’ does not name a type"

I know Shape* isn't a return type, but I don't know how to declare the pointer. Any suggestions?

答:
You've written ShapeFactory::Shape* make_shape, which the compiler thinks is the implementation of a function in ShapeFactory called Shape*. You need to have the return type before this, and the bit after the :: is the function name. So, the correct code is:

```<code> Shape* ShapeFactory::make_shape(const string
 &shape_name, const vector<double>&data)
</code>```

Title: c++ return type pointer declaration

Body:
function:
name: make_shape
return: Shape*
parameters: const string &shape_name; const vector &data

The class is ShapeFactory. This is what I have for this function definition:

 ShapeFactory::Shape* make_shape(const string &shape_name, const vector<double>&data)

I get an error that says:

"ShapeFactory.cpp:17:15: error: ‘Shape’ in ‘class ShapeFactory’ does not name a type"

I know Shape* isn't a return type, but I don't know how to declare the pointer. Any suggestions?

Body:
You've written ShapeFactory::Shape* make_shape, which the compiler thinks is the implementation of a function in ShapeFactory called Shape*. You need to have the return type before this, and the bit after the :: is the function name. So, the correct code is:

 Shape* ShapeFactory::make_shape(const string
 &shape_name, const vector<double>&data)


问:
Difference between delegating events to different elements in the DOM
Is there any functional or performance difference between these two jQuery change events?

```<code>$(document).on('change', '#toggleList', function () {
    //code
}
</code>```

and

```<code>$('#toggleArea').on('change', '#toggleList', function () {
    //code
}
</code>```

...

```<code><div id="toggleArea">
    <select id="toggleList"></select>
</div>
</code>```

答:
There is no functional difference between the two. There is a (very) slight performance difference, though, as the first example requires the event to bubble up the DOM from the #toggleList element to the document. The second example needs only go as far up the DOM as the #toggleArea, so will be slightly faster.

The old live() method used to use the first method you outlined and was deprecated because of it.

In an ideal world, the delegated event should be assigned to the nearest parent element to those being dynamically created which is available in the DOM when document.ready fires. Avoid assigning it to document where possible.

Body:
Is there any functional or performance difference between these two jQuery change events?

$(document).on('change', '#toggleList', function () {
    //code
}

and

$('#toggleArea').on('change', '#toggleList', function () {
    //code
}

...

    <select id="toggleList"></select>


问:
View() method abruptly started returning Blank HTML
I am facing an issue where my views abruptly stopped rendering on the Server. Only a blank white page is displayed with no errors logged. Returning a String works fine on Server. I deployed the project on my local machine and everything works fine (Local Machine has Apache).

View Inspect :

```<code><html><head></head><body></body></html>
</code>```

Permissions :

```<code>drwxr-xr-x 10 nobody nobody 4.0K Nov 26 20:07 app
-rw-r--r--  1 nobody nobody 1.7K Nov 26 20:07 artisan
drwxr-xr-x  3 nobody nobody 4.0K Nov 26 20:07 bootstrap
-rw-r--r--  1 nobody nobody 1.5K Nov 26 20:07 composer.json
-rw-r--r--  1 nobody nobody 133K Nov 27 09:56 composer.lock
-rwxr-xr-x  1 nobody nobody 1.8M Nov 26 20:08 composer.phar
drwxr-xr-x  2 nobody nobody 4.0K Nov 26 20:07 config
drwxr-xr-x  5 nobody nobody 4.0K Nov 26 20:07 database
-rw-r--r--  1 nobody nobody  503 Nov 26 20:07 gulpfile.js
-rw-r--r--  1 nobody nobody  159 Nov 26 20:07 package.json
-rw-r--r--  1 nobody nobody  228 Nov 27 01:07 php_errors.log
-rw-r--r--  1 nobody nobody 1.1K Nov 26 20:07 phpunit.xml
drwxr-xr-x  6 nobody nobody 4.0K Nov 26 20:07 public
-rw-r--r--  1 nobody nobody 1.9K Nov 26 20:07 readme.md
drwxr-xr-x  5 nobody nobody 4.0K Nov 26 20:07 resources
-rw-r--r--  1 nobody nobody  567 Nov 26 20:07 server.php
drwxrwxrwx  6 nobody nobody 4.0K Nov 26 20:07 storage
drwxr-xr-x  2 nobody nobody 4.0K Nov 26 20:07 tests
drwxr-xr-x 34 nobody nobody 4.0K Nov 27 09:56 vendor
</code>```

Controller :

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Log;

class TestController extends Controller
{
    public function test(){
        Log::info("Reached Test Controller");
        return view("test");
    }

}
</code>```

View (test.blade.php) :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample View</title>
</head>
<body>

<h1>We Are heere</h1>

</body>
</html>
</code>```

Nginx Conf :

```<code>    location @optimusrewrite {
    rewrite ^/(.*)$ /optimus/public/index.php?_url=/$1;
}

location /optimus/public/
{
    try_files $uri $uri/ @optimusrewrite;
    index index.php;
}
</code>```

** Update **

Removing the .blade extension from test.blade.php renders the view.

答: Issue was resolved by chmod'ing the resource directory (chmod -R 775 resource/)

Body:
I am facing an issue where my views abruptly stopped rendering on the Server. Only a blank white page is displayed with no errors logged. Returning a String works fine on Server. I deployed the project on my local machine and everything works fine (Local Machine has Apache).

View Inspect :

Permissions :

drwxr-xr-x 10 nobody nobody 4.0K Nov 26 20:07 app
-rw-r--r--  1 nobody nobody 1.7K Nov 26 20:07 artisan
drwxr-xr-x  3 nobody nobody 4.0K Nov 26 20:07 bootstrap
-rw-r--r--  1 nobody nobody 1.5K Nov 26 20:07 composer.json
-rw-r--r--  1 nobody nobody 133K Nov 27 09:56 composer.lock
-rwxr-xr-x  1 nobody nobody 1.8M Nov 26 20:08 composer.phar
drwxr-xr-x  2 nobody nobody 4.0K Nov 26 20:07 config
drwxr-xr-x  5 nobody nobody 4.0K Nov 26 20:07 database
-rw-r--r--  1 nobody nobody  503 Nov 26 20:07 gulpfile.js
-rw-r--r--  1 nobody nobody  159 Nov 26 20:07 package.json
-rw-r--r--  1 nobody nobody  228 Nov 27 01:07 php_errors.log
-rw-r--r--  1 nobody nobody 1.1K Nov 26 20:07 phpunit.xml
drwxr-xr-x  6 nobody nobody 4.0K Nov 26 20:07 public
-rw-r--r--  1 nobody nobody 1.9K Nov 26 20:07 readme.md
drwxr-xr-x  5 nobody nobody 4.0K Nov 26 20:07 resources
-rw-r--r--  1 nobody nobody  567 Nov 26 20:07 server.php
drwxrwxrwx  6 nobody nobody 4.0K Nov 26 20:07 storage
drwxr-xr-x  2 nobody nobody 4.0K Nov 26 20:07 tests
drwxr-xr-x 34 nobody nobody 4.0K Nov 27 09:56 vendor

Controller :

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Log;

class TestController extends Controller
{
    public function test(){
        Log::info("Reached Test Controller");
        return view("test");
    }

}

View (test.blade.php) :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Sample View</title>

We Are heere

Nginx Conf :

    location @optimusrewrite {
    rewrite ^/(.*)$ /optimus/public/index.php?_url=/$1;
}

location /optimus/public/
{
    try_files $uri $uri/ @optimusrewrite;
    index index.php;
}

** Update **

Removing the .blade extension from test.blade.php renders the view.


问:
Gathering DNS whois information for large number of typo/squatting domain names
I am going to gather and analyze the DNS registration information of a large number of domain names. My domain names are such as bbc.com, bbc.com.co, bbc.com.a and bbc.com.aa. As you can see, I have typo/squatting domain names of the official web sites such as bbc.com. I am using python whois library and send DNS whois query to these domain names, but for so many of them, I got below message:
Here is my code for sending whois query :

```<code>try:
    typo_dns_info = whois.whois(typo)
    if typo_dns_info:
        typo_info[typo] = typo_dns_info
        registered_typo.append(typo)
except:
    pass
</code>```

and I got this error for many of the domain names:

```<code>Socket Error: [Errno 111] Connection refused
</code>```

I searched and I think maybe I need to sleep my program to send DNS query after 1 second. But it did not help me at all. I do not know what is the best way to get the whois information of a url?

答:
I use regular DNS queries to tell if a domain exists. Whois servers typically aren't set up for high volume queries and some limit the rate of queries on a per-IP basis. Regular DNS servers are designed for high lookup rates and will not throw the same errors.

Here's a bit of code to discover registered domains via dnspython:

```<code>try:
    dns.resolver.query(typo, 'A')
    print("%s exists" % typo)
except:
    try:
        x = whois.whois(typo)
        print("%s exists" % typo)
    except:
        print("%s doesn't exist" % typo)
</code>```

Body:
I am going to gather and analyze the DNS registration information of a large number of domain names. My domain names are such as bbc.com, bbc.com.co, bbc.com.a and bbc.com.aa. As you can see, I have typo/squatting domain names of the official web sites such as bbc.com. I am using python whois library and send DNS whois query to these domain names, but for so many of them, I got below message:
Here is my code for sending whois query :

try:
    typo_dns_info = whois.whois(typo)
    if typo_dns_info:
        typo_info[typo] = typo_dns_info
        registered_typo.append(typo)
except:
    pass

and I got this error for many of the domain names:

Socket Error: [Errno 111] Connection refused

I searched and I think maybe I need to sleep my program to send DNS query after 1 second. But it did not help me at all. I do not know what is the best way to get the whois information of a url?

Body:
I use regular DNS queries to tell if a domain exists. Whois servers typically aren't set up for high volume queries and some limit the rate of queries on a per-IP basis. Regular DNS servers are designed for high lookup rates and will not throw the same errors.

Here's a bit of code to discover registered domains via dnspython:

try:
    dns.resolver.query(typo, 'A')
    print("%s exists" % typo)
except:
    try:
        x = whois.whois(typo)
        print("%s exists" % typo)
    except:
        print("%s doesn't exist" % typo)


问:
ReactJS giving error Uncaught TypeError: Super expression must either be null or a function, not undefined
I am using ReactJS.

When I run the code below the browser says:

Uncaught TypeError: Super expression must either be null or a function, not undefined

Any hints at all as to what is wrong would be appreciated.

First the line used to compile the code:

```<code>browserify -t reactify -t babelify examples/temp.jsx  -o examples/public/app.js
</code>```

And the code:

```<code>var React = require('react');

class HelloMessage extends React.Component {
  render() {
    return <div>Hello </div>;
  }
}
</code>```

UPDATE:
After burning in hellfire for three days on this problem I found that I was not using the latest version of react.

Install globally:

```<code>sudo npm install -g react@0.13.2
</code>```

install locally:

```<code>npm install react@0.13.2
</code>```

make sure the browser is using the right version too:

```<code><script type="text/javascript" src="react-0.13.2.js"></script>
</code>```

Hope this saves someone else three days of precious life.

答:
In my case I was using:

```<code>class Root extends React.Component() {
// THIS IS WORNG
// After React.Component () <- WRONG!!
}
</code>```

which was wrong but correct is:

```<code>class Root extends React.Component {
// THIS IS CORRECT
// That -> '()' after React.Component was typo
}
</code>```

also make sure there is

√ React.Component

NOT

ˣ React.component or React.Components

ContentLicense: CC BY-SA 4.0

Body:
I am using ReactJS.

When I run the code below the browser says:

Uncaught TypeError: Super expression must either be null or a function, not undefined

Any hints at all as to what is wrong would be appreciated.

First the line used to compile the code:

browserify -t reactify -t babelify examples/temp.jsx  -o examples/public/app.js

And the code:

var React = require('react');

class HelloMessage extends React.Component {
  render() {
    return
Hello
;
  }
}

UPDATE:
After burning in hellfire for three days on this problem I found that I was not using the latest version of react.

Install globally:

sudo npm install -g react@0.13.2

install locally:

npm install react@0.13.2

make sure the browser is using the right version too:

Hope this saves someone else three days of precious life.

Body:
In my case I was using:

class Root extends React.Component() {
// THIS IS WORNG
// After React.Component () <- WRONG!!
}

which was wrong but correct is:

class Root extends React.Component {
// THIS IS CORRECT
// That -> '()' after React.Component was typo
}

also make sure there is

√ React.Component

NOT

ˣ React.component or React.Components


问:
Extract rows from dataframe inside list inside dataframe in R
I'm using package RISmed in R in order to obtain information from PubMed. The 'Mesh' package function allows me to obtain the MeSH terms of each citation. Nevertheless it is a List, containing a Data Frame.
I want to list each MeSH term besides its corresponding citation id (PMID).
For example, I can construct a table containing both values:

```<code>table = cbind(ArticleId(MedlineObject),Mesh(MedlineObject))
</code>```

The first column is a char object but the second one is a list, containing a dataframe. If the value inside 1st column were "29145282" and the content of 2dnd column were "Cardiomyopathy, Hypertrophic", "Combined Modality Therapy" and "Diagnosis, Differential", I would want to obtain:

```<code>"29145282","Cardiomyopathy, Hypertrophic"
"29145282","Combined Modality Therapy"
"29145282","Diagnosis, Differential"
</code>```

How could I accomplish this?

答:
Check out the tidyr and tibble packages. Make sure to take a look at the nest() and unnest() functions. I can't give you much more advice without a reproducible example.

```<code>x = 1:5
data <- lapply(x, function(i){
  data.frame(y = 1:5 * i)
})

temp = tibble::tibble(x, data)
temp
tidyr::unnest(temp)
</code>```

Body:
I'm using package RISmed in R in order to obtain information from PubMed. The 'Mesh' package function allows me to obtain the MeSH terms of each citation. Nevertheless it is a List, containing a Data Frame.
I want to list each MeSH term besides its corresponding citation id (PMID).
For example, I can construct a table containing both values:

table = cbind(ArticleId(MedlineObject),Mesh(MedlineObject))

The first column is a char object but the second one is a list, containing a dataframe. If the value inside 1st column were "29145282" and the content of 2dnd column were "Cardiomyopathy, Hypertrophic", "Combined Modality Therapy" and "Diagnosis, Differential", I would want to obtain:

"29145282","Cardiomyopathy, Hypertrophic"
"29145282","Combined Modality Therapy"
"29145282","Diagnosis, Differential"

How could I accomplish this?

Body:
Check out the tidyr and tibble packages. Make sure to take a look at the nest() and unnest() functions. I can't give you much more advice without a reproducible example.

x = 1:5
data <- lapply(x, function(i){
  data.frame(y = 1:5 * i)
})

temp = tibble::tibble(x, data)
temp
tidyr::unnest(temp)


问:
How to get a response of BatchWriteItem DocumentClient?
I'm going to put an item in two dynamodb tables. This is my request params of BatchWriteItem operation.

```<code>RequestItems: {
    first_table: [{
        PutRequest: {
            Item: {
                employee_id: '123',
                company_id: '123',
                job_position: 'manager'
            }
        }
    }],
    second_table: [{
        PutRequest: {
            Item: {
                facility_id: '123',
                company_id: '123',
                job_position: 'manager'
            }
        }
    }]
},
ReturnConsumedCapacity: "TOTAL"
</code>```

My item is updated succefully but I get this response -

UnprocessedItems: {}

How can I get response with updated data? Thanks

答:
Its not possible to get a response containing the items you have put using BatchWriteItem. PutItem can return overwritten values, but not new ones.

You might consider:

1) Using the data you already have. Afterall, you know the items have been written and you already have them.

2) If you want some statistics on your batchwrite you could use

```<code>"ReturnItemCollectionMetrics": "SIZE"
</code>```

3) Query for the items after you have written them.

Body:
I'm going to put an item in two dynamodb tables. This is my request params of BatchWriteItem operation.

RequestItems: {
    first_table: [{
        PutRequest: {
            Item: {
                employee_id: '123',
                company_id: '123',
                job_position: 'manager'
            }
        }
    }],
    second_table: [{
        PutRequest: {
            Item: {
                facility_id: '123',
                company_id: '123',
                job_position: 'manager'
            }
        }
    }]
},
ReturnConsumedCapacity: "TOTAL"

My item is updated succefully but I get this response -

UnprocessedItems: {}

How can I get response with updated data? Thanks

Body:
Its not possible to get a response containing the items you have put using BatchWriteItem. PutItem can return overwritten values, but not new ones.

You might consider:

1) Using the data you already have. Afterall, you know the items have been written and you already have them.

2) If you want some statistics on your batchwrite you could use

"ReturnItemCollectionMetrics": "SIZE"

3) Query for the items after you have written them.


问:
not able to create a dictionary from a one-element list
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

```<code>{Kabul: River Kabul, Tirana: River Tirane, etc}
</code>```

Any help will be really appreciated. Thanks in advance.

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])
</code>```

答:
Another way you can get required result (dictionary with city: river pairs) is to use requests and lxml as below:

```<code>import requests
from lxml import html

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = requests.get(url, headers=headers)
source = html.fromstring(req.content)

xpath = '//b[.="COUNTRY - CAPITAL CITY - RIVER"]/following::div[b and following-sibling::hr]'
rivers = [item.text_content().strip() for item in source.xpath(xpath) if item.text_content().strip()]
rivers_dict = {}

for river in rivers:
    rivers_dict[river.split("-")[1].strip()] = river.split("-")[2].strip()

print(rivers_dict)
</code>```

Output:

```<code>{'Asuncion': 'River Paraguay.', 'La Paz': 'River Choqueapu.', 'Kinshasa': 'River Congo.', ...}
</code>```

...147 items total

Body:
I am new in python programming and webscraping, I am able to get the relevant information from the website but it generates only one element with all the information needed in the list. The problem is that I cannot delete the unwanted things in this one element list. I am not sure if it is at all possible to do this from a single element list.Is there any way to create a python dictionary as in the example below:

{Kabul: River Kabul, Tirana: River Tirane, etc}

Any help will be really appreciated. Thanks in advance.

from bs4 import BeautifulSoup
import urllib.request

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class":"sites-layout-tile sites-tile-name-content-1"}
rivers = soup.find_all(["table", "tr", "td","div","div","div"], attrs=attr)

data = [div.text for div in rivers]

print(data[0])

Body:
Another way you can get required result (dictionary with city: river pairs) is to use requests and lxml as below:

import requests
from lxml import html

url = "https://sites.google.com/site/worldfactsinc/rivers-of-the-world-s-capital-cities"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
req = requests.get(url, headers=headers)
source = html.fromstring(req.content)

xpath = '//b[.="COUNTRY - CAPITAL CITY - RIVER"]/following::div[b and following-sibling::hr]'
rivers = [item.text_content().strip() for item in source.xpath(xpath) if item.text_content().strip()]
rivers_dict = {}

for river in rivers:
    rivers_dict[river.split("-")[1].strip()] = river.split("-")[2].strip()

print(rivers_dict)

Output:

{'Asuncion': 'River Paraguay.', 'La Paz': 'River Choqueapu.', 'Kinshasa': 'River Congo.', ...}

...147 items total


问:
ASPX page with a User Control not working with localization
I have a project that is using ASPX and C#.  All of the pages support localization through the overridden InitializeCulture method.  Everything works very well with the exception of one page.  This page has UserControl that is used for searching.  I have noticed something odd with this page.  If I execute a search, all of the French characters show up incorrectly.  However, if I change the language to English and then back to French they show up as they should.  The text is coming from a global resx file.
First display:

```Nous avons Ã©galement effectuÃ©```

After changing language and then back:

```Nous avons également effectué```

Any ideas why this is happening?  It affects the entire page too, even parts that work properly on all other pages.  The web.config file has the default encoding set to utf-8:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

答:
If you see two unrelated characters in place of a single character with a diacritic , you haven't told the client what it needs to know to treat the page as UTF-8, e.g.

```<code>Response.CodePage = 65001 ;
Response.CharSet = "utf-8" ;
</code>```

This is excerpt from related topic.

Body:
I have a project that is using ASPX and C#.  All of the pages support localization through the overridden InitializeCulture method.  Everything works very well with the exception of one page.  This page has UserControl that is used for searching.  I have noticed something odd with this page.  If I execute a search, all of the French characters show up incorrectly.  However, if I change the language to English and then back to French they show up as they should.  The text is coming from a global resx file.
First display:

Nous avons Ã©galement effectuÃ©

After changing language and then back:

Nous avons également effectué

Any ideas why this is happening?  It affects the entire page too, even parts that work properly on all other pages.  The web.config file has the default encoding set to utf-8:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" />

Body:
If you see two unrelated characters in place of a single character with a diacritic , you haven't told the client what it needs to know to treat the page as UTF-8, e.g.

Response.CodePage = 65001 ;
Response.CharSet = "utf-8" ;

This is excerpt from related topic.


问:
Labels on only root and terminal vertices in igraph (R)?
```<code>inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 2, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
df2 = cbind(df2, km)
g2 = graph_from_data_frame(df2)
tkplot(g2)
</code>```

how would I approach adding labels to exclusively my root and terminal vertices in a graph? I know it would involve this function, but how would you set it up? Assuming the graph object is just called 'g', or something obvious.

```<code>vertex.label =
</code>```

答:
Using your example graph, we'll identify the root and terminal vertices and remove the labels for other vertices. Here's what the initial graph looks like:

```<code>set.seed(2)
plot(g2)
</code>```

Now let's identify and remove the names of the intermediate vertices

```<code># Get all edges
e = get.edgelist(g2)

# Root vertices are in first column but not in second column
root = setdiff(e[,1],e[,2])

# Terminal vertices are in second column but not in first column
terminal = setdiff(e[,2], e[,1])

# Vertices to remove are not in root or terminal vertices
remove = setdiff(unique(c(e)), c(root, terminal))

# Remove names of intermediate vertices
V(g2)$name[V(g2)$name %in% remove] = ""

set.seed(2)
plot(g2)
</code>```

Original Answer

You can use set.vertex.attribute to change the label names. Here's an example:

```<code>library(igraph)

# Create a graph to work with
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

plot(g)
</code>```

Now we can remove the labels from the intermediate vertices:

```<code>g = set.vertex.attribute(g, "name", value=c(1,rep("", length(2:11)),12:21))

plot(g)
</code>```

Body:
inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 2, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
df2 = cbind(df2, km)
g2 = graph_from_data_frame(df2)
tkplot(g2)

how would I approach adding labels to exclusively my root and terminal vertices in a graph? I know it would involve this function, but how would you set it up? Assuming the graph object is just called 'g', or something obvious.

vertex.label =

Body:
Using your example graph, we'll identify the root and terminal vertices and remove the labels for other vertices. Here's what the initial graph looks like:

set.seed(2)
plot(g2)

Now let's identify and remove the names of the intermediate vertices

# Get all edges
e = get.edgelist(g2)

# Root vertices are in first column but not in second column
root = setdiff(e[,1],e[,2])

# Terminal vertices are in second column but not in first column
terminal = setdiff(e[,2], e[,1])

# Vertices to remove are not in root or terminal vertices
remove = setdiff(unique(c(e)), c(root, terminal))

# Remove names of intermediate vertices
V(g2)$name[V(g2)$name %in% remove] = ""

set.seed(2)
plot(g2)

Original Answer

You can use set.vertex.attribute to change the label names. Here's an example:

library(igraph)

# Create a graph to work with
g = graph_from_edgelist(cbind(c(rep(1,10),2:11), c(2:21)))

plot(g)

Now we can remove the labels from the intermediate vertices:

g = set.vertex.attribute(g, "name", value=c(1,rep("", length(2:11)),12:21))

plot(g)


问:
Python Code - SVD with numpy
I would like to get some help with my code on Python. I am a novice to Python.

At high level - I read a (.png) file from command line , put into original array , compute svd , find high rank of svd based on command line , multiple with original array and then finally  put the file and the array out.

My issue : The generated file is distorted and does not look like the real picture i intended to generate.

My question : I have put the snippet of code I am using , can you please point to what I am doing incorrectly ?

```<code>import sys
import os
import numpy
import numpy.linalg
import scipy.misc

def getOutputPngName(path, rank):
    filename, ext = os.path.splitext(path)
    return filename + '.' + str(rank) + '.png'

def getOutputNpyName(path, rank):
    filename, ext = os.path.splitext(path)
    return filename + '.' + str(rank) + '.npy'

if len(sys.argv) < 3:
    sys.exit('usage: task1.py <PNG inputFile> <rank>')

    inputfile = sys.argv[1]
    rank = int(sys.argv[2])
    outputpng = getOutputPngName(inputfile, rank)
    outputnpy = getOutputNpyName(inputfile, rank)

# Import pic.png into array im as command parameter
img = scipy.misc.imread(inputfile)

# Perform SVD on im and obtain individual matrices
P, D, Q = numpy.linalg.svd(img, full_matrices=False)

# Compute overall SVD matrix based on individual matrices
svd_decomp = numpy.dot(numpy.dot(P, numpy.diag(D)), Q)

# Keep Top entries in svd_decomp
initial = svd_decomp.argsort()
temp = numpy.array(initial)
svd_final = numpy.argpartition(temp,-rank)[-rank:]

# Multiply to obtain the best rank-k approximation of the original array
img = numpy.transpose(img)
final = (numpy.dot(svd_final,img))

#Saving the approximated array as a binary array file(1) and as a PNG file(2)
numpy.save(outputnpy, final)
scipy.misc.imsave(outputpng, final)
</code>```

答:
No Need to sort. Just compute your matrix over rank</p>

```<code>svd_decomp = np.zeros((len(P), len(Q)))
for i in range(rank):
    svd_decomp += D[i] * np.outer(P.T[i], Q[i])
</code>```

Title: Python Code - SVD with numpy

Body:
I would like to get some help with my code on Python. I am a novice to Python.

At high level - I read a (.png) file from command line , put into original array , compute svd , find high rank of svd based on command line , multiple with original array and then finally  put the file and the array out.

My issue : The generated file is distorted and does not look like the real picture i intended to generate.

My question : I have put the snippet of code I am using , can you please point to what I am doing incorrectly ?

import sys
import os
import numpy
import numpy.linalg
import scipy.misc

def getOutputPngName(path, rank):
    filename, ext = os.path.splitext(path)
    return filename + '.' + str(rank) + '.png'

def getOutputNpyName(path, rank):
    filename, ext = os.path.splitext(path)
    return filename + '.' + str(rank) + '.npy'

if len(sys.argv) < 3:
    sys.exit('usage: task1.py <PNG inputFile> <rank>')

    inputfile = sys.argv[1]
    rank = int(sys.argv[2])
    outputpng = getOutputPngName(inputfile, rank)
    outputnpy = getOutputNpyName(inputfile, rank)

# Import pic.png into array im as command parameter
img = scipy.misc.imread(inputfile)

# Perform SVD on im and obtain individual matrices
P, D, Q = numpy.linalg.svd(img, full_matrices=False)

# Compute overall SVD matrix based on individual matrices
svd_decomp = numpy.dot(numpy.dot(P, numpy.diag(D)), Q)

# Keep Top entries in svd_decomp
initial = svd_decomp.argsort()
temp = numpy.array(initial)
svd_final = numpy.argpartition(temp,-rank)[-rank:]

# Multiply to obtain the best rank-k approximation of the original array
img = numpy.transpose(img)
final = (numpy.dot(svd_final,img))

#Saving the approximated array as a binary array file(1) and as a PNG file(2)
numpy.save(outputnpy, final)
scipy.misc.imsave(outputpng, final)

Body:
No Need to sort. Just compute your matrix over rank

svd_decomp = np.zeros((len(P), len(Q)))
for i in range(rank):
    svd_decomp += D[i] * np.outer(P.T[i], Q[i])


问:
function not defined onclick with javascript
i am trying to play audio file on click of div, and then with the next click of the div pause it. However, I am very new to javascript and the first function isn't even executing, and i don't understand how it isn't defined.

here is my code:

```<code><!DOCTYPE html>
<html>

<head>
    <style>
        .floating-box {
            display: inline-block;
            width: 150px;
            height: 75px;
            margin: 10px;
            border: 3px solid #73AD21;
        }

        .after-box {
            clear: left;
            border: 3px solid red;
        }

        .player
    </style>
</head>
<script>
    var has_been_played = 0;

    function playSound() {
        var aud=new Audio(file);
        aud.play();
        var b1 = document.getElementbyId("box" + num);
        var b1.has_been_played == true;

    }

    var b1.has_been_played = pauseAud() {
        document.getElementById("box" + num).setAttribute("onClick",
            "javascript: pauseAud();");
    }

    function pauseAud() {
        var aud=new Audio(file);

        aud.pause();
    }
</script>

<body>
    <div id="box1" class="floating-box" onclick="playSound('donttalk.mp3');"></div>
    <div id="box2" class="floating-box" onclick="playSound('goodvibrations.mp3');"></div>
</body>

</html>
</code>```

I want it to play the sound, and then once it has been clicked the variable changes to "has_been_played" and the next time you click that div the audio file will pause. (hopefully then, the next you click it it will play again.

Why is it saying that the function playSound is not defined onclick?

答:
You need to add the function to the window like so:</p>

```<code>function playSound(){
    aud.play();
     var b1= document.getElementbyId("box"+num);
    var b1.has_been_played == true;

}

window.playSound = playSound;
</code>```

Body:
i am trying to play audio file on click of div, and then with the next click of the div pause it. However, I am very new to javascript and the first function isn't even executing, and i don't understand how it isn't defined.

here is my code:

<!DOCTYPE html>

I want it to play the sound, and then once it has been clicked the variable changes to "has_been_played" and the next time you click that div the audio file will pause. (hopefully then, the next you click it it will play again.

Why is it saying that the function playSound is not defined onclick?

Body:
You need to add the function to the window like so:

function playSound(){
    aud.play();
     var b1= document.getElementbyId("box"+num);
    var b1.has_been_played == true;

}

window.playSound = playSound;


问:
How to Assign values to a List of Lists in scala using loops?
I am new to scala so finding difficulty. can some one please guide me about how to initialize a list of lists using for loop?? I tried this:

for(i <- 1 to N)
  {
    for(D <- 1 to Dimensions)
    {
  Population=List(List(D,i))
    }```

but it is not working well

答:
Are you looking for something like this?

```<code>val population: List[List[(Int, Int)]] = List(1,2,3,4,5) map { i =>
   List(11, 12, 13, 14, 15) map { D =>
     (D, i)
  }
}
</code>```

Basically, if you start with a List you end up with a List.

Similarly, if you start with an IndexedSequence, you will end up with an IndexedSequence

```<code>val populationAsIndexedSeq: IndexedSeq[IndexedSeq[(Int, Int)]] = 1 to 5 map { i =>
  11 to 15 map { D =>
    (D, i)
  }
}
</code>```

Body:
I am new to scala so finding difficulty. can some one please guide me about how to initialize a list of lists using for loop?? I tried this:

for(i <- 1 to N)
  {
    for(D <- 1 to Dimensions)
    {
  Population=List(List(D,i))
    }

but it is not working well

Body:
Are you looking for something like this?

val population: List[List[(Int, Int)]] = List(1,2,3,4,5) map { i =>
   List(11, 12, 13, 14, 15) map { D =>
     (D, i)
  }
}

Basically, if you start with a List you end up with a List.

Similarly, if you start with an IndexedSequence, you will end up with an IndexedSequence

val populationAsIndexedSeq: IndexedSeq[IndexedSeq[(Int, Int)]] = 1 to 5 map { i =>
  11 to 15 map { D =>
    (D, i)
  }
}


问:
I'm trying to clear textarea after copying data from another textarea using jscript but unable to clear second textarea
```<code><!DOCTYPE html>
<html>
<body>

<b>Q1.</b>
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>

<script>
function clearText() {
    document.getElementById("A1").reset();
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   document.getElementById("A1").innerHTML = x;
}
</script>

</body>
</html>
</code>```

In the above code SameAnswer() function is working properly but ClearText() function isn't. Need help in resolving this issue

答:
reset is for an entire form. So you have two options.

1) set the value to empty string

```<code>document.getElementById("A1").value = "";
</code>```

2) set the value to equal the default value

```<code>var ta = document.getElementById("A1");
ta.value = ta.defaultValue;
</code>```

And when you are setting the value, you need to use value, not innerHTML.

function clearText1() {
  var ta = document.getElementById("A1");
  ta.value = "";
  ta.removeAttribute("readOnly")
}

function clearText2() {
  var ta = document.getElementById("A1")
  ta.value = ta.defaultValue;
  ta.removeAttribute("readOnly")
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   var ta = document.getElementById("A1");
   ta.value = x;
   ta.setAttribute("readOnly", true)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Q1.</b>
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText1()" value="New Answer 1">
<input type="button" onclick="clearText2()" value="New Answer 2">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea></code>```

Body:
<!DOCTYPE html>

Q1.
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<textarea readonly rows="4" columns="200" id="A1"></textarea>

In the above code SameAnswer() function is working properly but ClearText() function isn't. Need help in resolving this issue

Body:
reset is for an entire form. So you have two options.

1) set the value to empty string

document.getElementById("A1").value = "";

2) set the value to equal the default value

var ta = document.getElementById("A1");
ta.value = ta.defaultValue;

And when you are setting the value, you need to use value, not innerHTML.

function clearText1() {
  var ta = document.getElementById("A1");
  ta.value = "";
  ta.removeAttribute("readOnly")
}

function clearText2() {
  var ta = document.getElementById("A1")
  ta.value = ta.defaultValue;
  ta.removeAttribute("readOnly")
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   var ta = document.getElementById("A1");
   ta.value = x;
   ta.setAttribute("readOnly", true)
}

<b>Q1.</b>
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText1()" value="New Answer 1">
<input type="button" onclick="clearText2()" value="New Answer 2">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>


问:
How do I pull up the Expo QR code after React Native app has been started?
I've already started the app and did not see the QR code on the initial terminal after CRNA set up.
How can I pull it up now to scan the code?</p>

答: Simply type "q" in your terminal</p>

Body: Simply type "q" in your terminal


问:
WPF - use new images from .exe file
In my WPF application I added few images to my project in Visual Studio and changed their Build Action. And they work.
The problem is when I want to add new images to images folder. After that I launch my .exe file and application cannot see these new added images.
How to resolve this?</p>

```<code>private void ShowImage(Button button)
        {
            string buttonName = button.Name;
            string path = $@"Images/{buttonName}.png";

            Image image = new Image();
            image.Source = new BitmapImage(new Uri(path, UriKind.Relative));
            button.Content = image;
        }
</code>```

答:
If I understand your question, I think the answer you are looking for is a component reference that'd look like so:</p>

```<code>private void ShowImage(Button button)
    {
        string buttonName = button.Name;
        string path = "/MyProject;component/Images/{buttonName}.png";

        Image image = new Image();
        image.Source = new BitmapImage(new Uri(path, UriKind.Relative));
        button.Content = image;
    }
</code>```

Title: WPF - use new images from .exe file

Body:
In my WPF application I added few images to my project in Visual Studio and changed their Build Action. And they work.
The problem is when I want to add new images to images folder. After that I launch my .exe file and application cannot see these new added images.
How to resolve this?

private void ShowImage(Button button)
        {
            string buttonName = button.Name;
            string path = $@"Images/{buttonName}.png";

            Image image = new Image();
            image.Source = new BitmapImage(new Uri(path, UriKind.Relative));
            button.Content = image;
        }

Body:
If I understand your question, I think the answer you are looking for is a component reference that'd look like so:

private void ShowImage(Button button)
    {
        string buttonName = button.Name;
        string path = "/MyProject;component/Images/{buttonName}.png";

        Image image = new Image();
        image.Source = new BitmapImage(new Uri(path, UriKind.Relative));
        button.Content = image;
    }


问:
hello world in actionscript on linux
I would like to write a simple "hello world" program for ActionScript (flash media server) and execute it on the command line of my linux desktop.

Something simple like:

```<code>HelloWorld = function() {
    trace( "Hello world" );
}
</code>```

The purpose of this is so I can develop some simple functions and test them before adding them to larger existing Flash Media scripts.

Is this even possible? I just want to go to my command line and type something like:

```<code>actionscript helloworld.asc
</code>```

and then tail a log somewhere to view the output. I really don't want to have to set up a flash media server and all that entails and download flash for a browser and go to some web address just to trigger the script...

答:
If you just want the log, you can use the fdb command line tool [similar to gdb] (located in the bin folder of the Flex SDK you are working with).

You will still need some instance of an swf running to see the output. So you will either need the Standalone Flash debugger or the one in your browser.

Compile

```<code>mxmlc -debug=true hello.as
</code>```

Debug

```<code>fdb hello.swf
</code>```

From there you will see a trace ... in this case

```<code>[trace] Hello world
</code>```

Add breakpoints to step through if you want or bunch up commands in a bash script. The full list of commands are in the docs.

Title: hello world in actionscript on linux

Body:
I would like to write a simple "hello world" program for ActionScript (flash media server) and execute it on the command line of my linux desktop.

Something simple like:

HelloWorld = function() {
    trace( "Hello world" );
}

The purpose of this is so I can develop some simple functions and test them before adding them to larger existing Flash Media scripts.

Is this even possible? I just want to go to my command line and type something like:

actionscript helloworld.asc

and then tail a log somewhere to view the output. I really don't want to have to set up a flash media server and all that entails and download flash for a browser and go to some web address just to trigger the script...

Body:
If you just want the log, you can use the fdb command line tool [similar to gdb] (located in the bin folder of the Flex SDK you are working with).

You will still need some instance of an swf running to see the output. So you will either need the Standalone Flash debugger or the one in your browser.

Compile

mxmlc -debug=true hello.as

Debug

fdb hello.swf

From there you will see a trace ... in this case

[trace] Hello world

Add breakpoints to step through if you want or bunch up commands in a bash script. The full list of commands are in the docs.


问:
Regex filters on Bigtable queries - performance/recommendations
I'd like to ask about recommendations and performance considerations of using a Regex queries in Bigtable with or without a prefix.

We have information at the end of the row key that we need to filter with Regex.

Would Bigtable need to do a full table scan to perform a Regex query that does not include a prefix? What are the performance considerations? Is this recommended?

How would bringing in a prefix to the query impact the recommendation?

Would appreciate advice/thoughts on this as we optimize our schema.

答:
I'm on the eng team for Cloud Bigtable.

The Bigtable filter engine will attempt to parse out any prefix present in your Regex query and use it to reduce the scope of the scan.

Edit (2019-05-14): Turns out this isn't quite accurate. Bigtable will parse out the prefix and use it to seek past irrelevant data, but this happens separately for each tablet. And in particular, we still have to send a request to each tablet even if the tablet ends up getting entirely skipped. So this will be much faster than a true full table scan, but will still have performance issues. We are looking into improvements.

However, if you don't provide a prefix then Bigtable has nothing to go on, since any row could potentially match. As such, this type of query will result in a full table scan. Large scans are not recommended for queries which need to perform well, so it's best to arrange your row key to avoid them as much as possible. You can find more information about schema design in the docs.

Note that you can always set explicit row bounds on your scans in all of our supported clients. This is useful for limiting the size of an otherwise unbounded scan, but you can also use it to read multiple shards of the table in parallel if you truly need to accelerate a large query:

HBase

Python

Go


答:
Change .document.getElementById("A1").reset(); to document.getElementById("A1").value = "";

function clearText() {
    document.getElementById("A1").value = "";
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   document.getElementById("A1").innerHTML = x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Q1.</b>
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea></code>```

Title: I'm trying to clear textarea after copying data from another textarea using jscript but unable to clear second textarea

Body:
Change .document.getElementById("A1").reset(); to document.getElementById("A1").value = "";

function clearText() {
    document.getElementById("A1").value = "";
}

function SameAnswer() {
   var x = document.getElementById("Q1_Old").value;
   document.getElementById("A1").innerHTML = x;
}

<b>Q1.</b>
<textarea readonly rows="4" columns="200" id="Q1_Old">Answer to be copied to second textarea</textarea>

<p>If the above answer is unchanged click on "Same Answer" for copying over, else click on "New Answer" to draft new answer</p>

<button onclick="SameAnswer()">Same Answer</button>
<input type="button" onclick="clearText()" value="New Answer">

<p><textarea readonly rows="4" columns="200" id="A1"></textarea>


问:
Importing data into r from hive using RJDBC
My data resides in hive database on azure cloud and the link is "https://onetaxsitintegratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance
". I have the userid and password for the same. I tried to read data from R using the following but it throws an error

```<code>drv <- JDBC("org.apache.hive.jdbc.HiveDriver",
            "C:/Users/japrab/Documents/R/win-library/3.4/RJDBC/java/hive-jdbc-2.0.0.jar")

conn <- dbConnect(drv,"https://integratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance", "userid", "passwords")
</code>```

The error I get is:

```<code>options( java.parameters = "-Xmx8g" )
drv <- JDBC("org.apache.hive.jdbc.HiveDriver", "C:/Users/japrab/Documents/R/win-library/3.4/RJDBC/java/hive-jdbc-2.0.0.jar")
conn <- dbConnect(drv, "integratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance", "user", "password")
</code>```

Error in .verify.JDBC.result(jc, "Unable to connect JDBC to ", url) :
  Unable to connect JDBC to integratedcluster.azurehdinsight.net/#/main/view/HIVE/auto_hive20_instance

Please help. All the examples I see have localhost but unsure what do i do when data is on a cloud!

答: I think the problem may be that you quote the hive jar from your own system. If your data is loaded in a Hive database in the cloud, the cloud server must be running Hadoop and Hive itself. I believe it is those jars that you need to reference.</p>

Body:
My data resides in hive database on azure cloud and the link is "https://onetaxsitintegratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance
". I have the userid and password for the same. I tried to read data from R using the following but it throws an error

drv <- JDBC("org.apache.hive.jdbc.HiveDriver",
            "C:/Users/japrab/Documents/R/win-library/3.4/RJDBC/java/hive-jdbc-2.0.0.jar")

conn <- dbConnect(drv,"https://integratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance", "userid", "passwords")

The error I get is:

options( java.parameters = "-Xmx8g" )
drv <- JDBC("org.apache.hive.jdbc.HiveDriver", "C:/Users/japrab/Documents/R/win-library/3.4/RJDBC/java/hive-jdbc-2.0.0.jar")
conn <- dbConnect(drv, "integratedcluster.azurehdinsight.net/#/main/view/HIVE/random_instance", "user", "password")

Error in .verify.JDBC.result(jc, "Unable to connect JDBC to ", url) :
  Unable to connect JDBC to integratedcluster.azurehdinsight.net/#/main/view/HIVE/auto_hive20_instance

Please help. All the examples I see have localhost but unsure what do i do when data is on a cloud!


问:
How to read input from the text file until/after a specific location [C++]?
In my Project I need to get data about circuit from a text file then I need to parse it and produce to output data.
Here is a sample data for the text file

AND1 Adder1-3 Adder1-4  // Means AND1 gate gets its first input from
  Adder1's 3rd output and its second input from Adder1's 4th output

AND2 Adder1-4 Adder1-2

OR1 AND1-1 AND2-1    //OR1's two inputs are from AND1's 1st output and
  AND2's 1st output

now I need to read the component name first which is easy:

```<code>infile>>componentName;
</code>```

But for the second part I though I could to this in to ways

Read the whole data and seperate it into two parts : ComponentName -
thOutput.

Read until "-" and put it into string variable then read
    after "-" and put it into integer variable and repeat this for all
    lines.

I tried the first way but I really stuck at converting string into integer (I tried using stoi but its for C++ only :( and also encountered with couple of problems) but I though the second way would be much easier but I couldn't figure it how to do it.

So can you help me with this ?
Basicly I need to put component name(before "-") into string variable and put the integer (after "-") into integer variable.

NOTE: Sorry for my poor English not a Native Speaker. and since the Project is large I didn't put unnecessary codes above.

答:
You could use Boost.Spirit for this parsing task.  It allows you to parse the result directly into a struct.

```<code>#include <iostream>
#include <sstream>
#include <string>

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>

struct Entry
{
    std::string op;
    std::string dev1;
    int n1;
    std::string dev2;
    int n2;
};

BOOST_FUSION_ADAPT_STRUCT(
    Entry,
    op,
    dev1, n1,
    dev2, n2)

Entry parse(std::string const &input)
{
    auto iter = input.begin();

    using namespace boost::spirit::x3;

    auto op = rule<class op, std::string>{}
    = lexeme[upper >> *(upper | digit)];
    auto dev = rule<class dev, std::string>{}
        = lexeme[upper >> *alnum];

    Entry result;

    bool r = phrase_parse(iter, input.end(),
                          op > dev > lit('-') > int_ > dev > lit('-') > int_,
                          space, result);

    if (!r)
    {
        std::string rest(iter, input.end());
        throw std::invalid_argument("Parsing failed at " + rest);
    }

    return result;
}

int main()
{
    // This could be a file instead with std::ifstream
    std::istringstream input;
    input.str(
"AND1 Adder1-3 Adder1-4 // Means AND1 gate gets its first input from Adder1's 3rd output and its second input from Adder1's 4th output\n"
"AND2 Adder1-4 Adder1-2\n"
"OR1 AND1-1 AND2-1 //OR1's two inputs are from AND1's 1st output and AND2's 1st output\n");

    for (std::string line; std::getline(input, line); )
    {
        Entry e = parse(line);

        std::cout << "Found the following entries:\n"
                  << "  Operation: " << e.op << "\n"
                  << "  Device 1: " << e.dev1 << "-" << e.n1 << "\n"
                  << "  Device 2: " << e.dev2 << "-" << e.n2 << "\n";
    }
}
</code>```

Live example

Body:
In my Project I need to get data about circuit from a text file then I need to parse it and produce to output data.
Here is a sample data for the text file

AND1 Adder1-3 Adder1-4  // Means AND1 gate gets its first input from
  Adder1's 3rd output and its second input from Adder1's 4th output

AND2 Adder1-4 Adder1-2

OR1 AND1-1 AND2-1    //OR1's two inputs are from AND1's 1st output and
  AND2's 1st output

now I need to read the component name first which is easy:

infile>>componentName;

But for the second part I though I could to this in to ways

Read the whole data and seperate it into two parts : ComponentName -
thOutput.

Read until "-" and put it into string variable then read
    after "-" and put it into integer variable and repeat this for all
    lines.

I tried the first way but I really stuck at converting string into integer (I tried using stoi but its for C++ only :( and also encountered with couple of problems) but I though the second way would be much easier but I couldn't figure it how to do it.

So can you help me with this ?
Basicly I need to put component name(before "-") into string variable and put the integer (after "-") into integer variable.

NOTE: Sorry for my poor English not a Native Speaker. and since the Project is large I didn't put unnecessary codes above.

Body:
You could use Boost.Spirit for this parsing task.  It allows you to parse the result directly into a struct.

#include <iostream>
#include <sstream>
#include <string>

#include <boost/fusion/adapted.hpp>
#include <boost/spirit/home/x3.hpp>

struct Entry
{
    std::string op;
    std::string dev1;
    int n1;
    std::string dev2;
    int n2;
};

BOOST_FUSION_ADAPT_STRUCT(
    Entry,
    op,
    dev1, n1,
    dev2, n2)

Entry parse(std::string const &input)
{
    auto iter = input.begin();

    using namespace boost::spirit::x3;

    auto op = rule<class op, std::string>{}
    = lexeme[upper >> *(upper | digit)];
    auto dev = rule<class dev, std::string>{}
        = lexeme[upper >> *alnum];

    Entry result;

    bool r = phrase_parse(iter, input.end(),
                          op > dev > lit('-') > int_ > dev > lit('-') > int_,
                          space, result);

    if (!r)
    {
        std::string rest(iter, input.end());
        throw std::invalid_argument("Parsing failed at " + rest);
    }

    return result;
}

int main()
{
    // This could be a file instead with std::ifstream
    std::istringstream input;
    input.str(
"AND1 Adder1-3 Adder1-4 // Means AND1 gate gets its first input from Adder1's 3rd output and its second input from Adder1's 4th output\n"
"AND2 Adder1-4 Adder1-2\n"
"OR1 AND1-1 AND2-1 //OR1's two inputs are from AND1's 1st output and AND2's 1st output\n");

    for (std::string line; std::getline(input, line); )
    {
        Entry e = parse(line);

        std::cout << "Found the following entries:\n"
                  << "  Operation: " << e.op << "\n"
                  << "  Device 1: " << e.dev1 << "-" << e.n1 << "\n"
                  << "  Device 2: " << e.dev2 << "-" << e.n2 << "\n";
    }
}

Live example


问:
Setting WPF background Opacity programmatically
I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.

```<code>motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);
</code>```

You can adjust the background opacity in XAML like so

```<code><Border BorderThickness="1" Height="100" Width="100">
    <Border.BorderBrush>
        <SolidColorBrush Color="Black" Opacity="0.7"/>
    </Border.BorderBrush>
</Border>
</code>```

But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#

```<code>moboBorder.Background.Opacity = //Value
</code>```

However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()

I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.

答:
A double is certainly a "straight up number"; hover the mouse over the property to see the data type.

The problem (thanks, Clemens) is that you're trying to set the opacity of Brushes.Black, which is a system object and you've got no business doing that.

But you can set the Opacity of a SolidColorBrush that you create yourself.

To create a new semi-opaque white brush:

```<code>x.Background = new SolidColorBrush(Colors.White) { Opacity = 0.5 };
</code>```

See Geoff's answer for how to create a color from an RGB triplet (or ARGB quad) instead of named colors.

Or just keep the existing brush, if you're confident that you didn't get it from Brushes.

```<code>Background.Opacity = 0.5;
</code>```

If you did this, you got it from System.Brushes:

```<code><Window
    Background="DeepSkyBlue"
    ...
</code>```

If you did this, you didn't:

```<code><Window.Background><SolidColorBrush Color="DeepSkyBlue" /></Window.Background>
</code>```

That DeepSkyBlue is Colors.DeepSkyBlue; you're creating a new brush with that color.

You should be doing all of this in XAML with bindings instead of creating WPF controls in C#. You'll shoot your eye out, kid.

But it's your eye.

Body:
I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.

motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);

You can adjust the background opacity in XAML like so

<Border BorderThickness="1" Height="100" Width="100">
    <Border.BorderBrush>
        <SolidColorBrush Color="Black" Opacity="0.7"/>
    </Border.BorderBrush>
</Border>

But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#

moboBorder.Background.Opacity = //Value

However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()

I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.

Body:
A double is certainly a "straight up number"; hover the mouse over the property to see the data type.

The problem (thanks, Clemens) is that you're trying to set the opacity of Brushes.Black, which is a system object and you've got no business doing that.

But you can set the Opacity of a SolidColorBrush that you create yourself.

To create a new semi-opaque white brush:

x.Background = new SolidColorBrush(Colors.White) { Opacity = 0.5 };

See Geoff's answer for how to create a color from an RGB triplet (or ARGB quad) instead of named colors.

Or just keep the existing brush, if you're confident that you didn't get it from Brushes.

Background.Opacity = 0.5;

If you did this, you got it from System.Brushes:

<Window
    Background="DeepSkyBlue"
    ...

If you did this, you didn't:

<Window.Background><SolidColorBrush Color="DeepSkyBlue" /></Window.Background>

That DeepSkyBlue is Colors.DeepSkyBlue; you're creating a new brush with that color.

You should be doing all of this in XAML with bindings instead of creating WPF controls in C#. You'll shoot your eye out, kid.

But it's your eye.


问:
Extracting from a list in haskell
I'm pretty new to Haskell and don't fully understand the Maybe monads.

```<code>data Hmm = Hmm [Maybe Int]
 deriving (Show, Eq)

yd = Hmm [Just 8, Just 5,Nothing,Just 2, Nothing, Just 2, Nothing,Nothing]

getVal = case yd of
  [Just val] -> putStr val
  [Nothing] -> putStr "."
</code>```

I want to extract my list by replacing Nothing with a dot and Just n with n (all in one line). However, this code gives me an error.

```<code>Couldn't match expected type "Hmm" with actual type '[Maybe a0]'

In the pattern : [Nothing]
In a case alternative: [Nothing] -> putStr "."
In the expression:
  case yd of
  [Just val] -> putStr val
  [Nothing] -> putStr "."
</code>```

basically i want the list above to be in the format " 85.2.2.. "

答:
The error message tells you the error:

Couldn't match expected type "Hmm" with actual type '[Maybe a0]'

Let's simplify by using [Int] instead of [Maybe Int] so we can take monads completely out of the picture here. Let's re-write your test cases by using 0 instead of Nothing, and x instead of Just x

```<code>data Hmm = Hmm [Int]
 deriving (Show, Eq)

yd = Hmm [8, 5, 0, 2, 0, 2, 0, 0]

getVal = case yd of
  [0] -> putStr "."
  [x] -> putStr $ show x
-- N.B. I had to reverse the order here since `[x]` will match before `[0]`.
-- This isn't an issue when you're still using Maybes, since Just x doesn't match Nothing
</code>```

Now we've got no monadic elements at all (except getVal :: Hmm -> IO (), but...) and you'll still have the same issue as before. yd is constructed as a Hmm, but the only pattern matching you're doing on it is looking for an [a]. In addition, both patterns are only looking for single-element lists, so they wouldn't match even if yd :: [Int].

Let's re-write using the Hmm constructor in our pattern match and recursing correctly to capture the whole list. We'll also re-write getVal to return the String so we don't even have to mess with the IO monad that putStr :: String -> IO () returns.

```<code>import Data.Char (intToDigit)

data Hmm = Hmm [Int]
  deriving (Show, Eq)

yd = Hmm [8, 5, 0, 2, 0, 2, 0, 0]

getVal :: Hmm -> String
getVal (Hmm [])    = []
getVal (Hmm (0:xs) = '.'          : getVal (Hmm xs)
getVal (Hmm (x:xs) = intToDigit x : getVal (Hmm xs)

result :: String
result = getVal yd
</code>```

Notice how I include three alternations in my pattern matches. One for Hmm [] -- an empty list wrapped in a Hmm type, one for Hmm (0:xs) -- a non-empty list wrapped by a Hmm whose first value is zero, and one for Hmm (x:xs) -- a non-empty list wrapped by a Hmm, and each result but the first is recursive. This will return:

```<code>getVal yd =
getVal (Hmm (8:[5, 0, 2, 0, 2, 0, 0])) =
'8' : getVal (Hmm (5: [0, 2, 0, 2, 0, 0])) =
'8':'5' : getVal (Hmm (0: [2, 0, 2, 0, 0])) =
'8':'5':'.' : getVal (Hmm (2: [0, 2, 0, 0])) =
'8':'5':'.':'2' : getVal (Hmm (0: [2, 0, 0])) =
'8':'5':'.':'2':'.' : getVal (Hmm (2: [0, 0])) =
'8':'5':'.':'2':'.':'2' : getVal (Hmm (0: [0])) =
'8':'5':'.':'2':'.':'2':'.' : getVal (Hmm (0:[])) =
'8':'5':'.':'2':'.':'2':'.':'.': getVal (Hmm []) =   -- base case!
'8':'5':'.':'2':'.':'2':'.':'.':[] =      -- re-write as list
['8', '5', '.', '2', '.', '2', '.', '.']  -- re-write as String
"85.2.2.."
</code>```

Do note that this is just:

```<code>toString :: Hmm -> String
toString (Hmm xs) = map f xs where
  f 0 = '.'
  f x = intToDigit x
</code>```

To use a Maybe Int here and return this to the world of monads, just apply the same changes to your code

```<code>import Data.Char (intToDigit)

data Hmm = Hmm [Maybe Int]
  deriving (Show, Eq)

yd = Hmm [Just 8, Just 5, Nothing, Just 2, Nothing, Just 2, Nothing, Nothing]

getVal :: Hmm -> String
getVal (Hmm []) = []
getVal (Hmm (Nothing:xs)) = '.'          : getVal (Hmm xs)
getVal (Hmm (Just x :xs)) = intToDigit x : getVal (Hmm xs)

-- or equivalently

getVal' :: Hmm -> String
getVal' (Hmm xs) = map f xs where
  f Nothing = '.'
  f (Just x) = intToDigit x
</code>```

Title: Extracting from a list in haskell

Body:
I'm pretty new to Haskell and don't fully understand the Maybe monads.

data Hmm = Hmm [Maybe Int]
 deriving (Show, Eq)

yd = Hmm [Just 8, Just 5,Nothing,Just 2, Nothing, Just 2, Nothing,Nothing]

getVal = case yd of
  [Just val] -> putStr val
  [Nothing] -> putStr "."

I want to extract my list by replacing Nothing with a dot and Just n with n (all in one line). However, this code gives me an error.

Couldn't match expected type "Hmm" with actual type '[Maybe a0]'

In the pattern : [Nothing]
In a case alternative: [Nothing] -> putStr "."
In the expression:
  case yd of
  [Just val] -> putStr val
  [Nothing] -> putStr "."

basically i want the list above to be in the format " 85.2.2.. "

Body:
The error message tells you the error:

Couldn't match expected type "Hmm" with actual type '[Maybe a0]'

Let's simplify by using [Int] instead of [Maybe Int] so we can take monads completely out of the picture here. Let's re-write your test cases by using 0 instead of Nothing, and x instead of Just x

data Hmm = Hmm [Int]
 deriving (Show, Eq)

yd = Hmm [8, 5, 0, 2, 0, 2, 0, 0]

getVal = case yd of
  [0] -> putStr "."
  [x] -> putStr $ show x
-- N.B. I had to reverse the order here since `[x]` will match before `[0]`.
-- This isn't an issue when you're still using Maybes, since Just x doesn't match Nothing

Now we've got no monadic elements at all (except getVal :: Hmm -> IO (), but...) and you'll still have the same issue as before. yd is constructed as a Hmm, but the only pattern matching you're doing on it is looking for an [a]. In addition, both patterns are only looking for single-element lists, so they wouldn't match even if yd :: [Int].

Let's re-write using the Hmm constructor in our pattern match and recursing correctly to capture the whole list. We'll also re-write getVal to return the String so we don't even have to mess with the IO monad that putStr :: String -> IO () returns.

import Data.Char (intToDigit)

data Hmm = Hmm [Int]
  deriving (Show, Eq)

yd = Hmm [8, 5, 0, 2, 0, 2, 0, 0]

getVal :: Hmm -> String
getVal (Hmm [])    = []
getVal (Hmm (0:xs) = '.'          : getVal (Hmm xs)
getVal (Hmm (x:xs) = intToDigit x : getVal (Hmm xs)

result :: String
result = getVal yd

Notice how I include three alternations in my pattern matches. One for Hmm [] -- an empty list wrapped in a Hmm type, one for Hmm (0:xs) -- a non-empty list wrapped by a Hmm whose first value is zero, and one for Hmm (x:xs) -- a non-empty list wrapped by a Hmm, and each result but the first is recursive. This will return:

getVal yd =
getVal (Hmm (8:[5, 0, 2, 0, 2, 0, 0])) =
'8' : getVal (Hmm (5: [0, 2, 0, 2, 0, 0])) =
'8':'5' : getVal (Hmm (0: [2, 0, 2, 0, 0])) =
'8':'5':'.' : getVal (Hmm (2: [0, 2, 0, 0])) =
'8':'5':'.':'2' : getVal (Hmm (0: [2, 0, 0])) =
'8':'5':'.':'2':'.' : getVal (Hmm (2: [0, 0])) =
'8':'5':'.':'2':'.':'2' : getVal (Hmm (0: [0])) =
'8':'5':'.':'2':'.':'2':'.' : getVal (Hmm (0:[])) =
'8':'5':'.':'2':'.':'2':'.':'.': getVal (Hmm []) =   -- base case!
'8':'5':'.':'2':'.':'2':'.':'.':[] =      -- re-write as list
['8', '5', '.', '2', '.', '2', '.', '.']  -- re-write as String
"85.2.2.."

Do note that this is just:

toString :: Hmm -> String
toString (Hmm xs) = map f xs where
  f 0 = '.'
  f x = intToDigit x

To use a Maybe Int here and return this to the world of monads, just apply the same changes to your code

import Data.Char (intToDigit)

data Hmm = Hmm [Maybe Int]
  deriving (Show, Eq)

yd = Hmm [Just 8, Just 5, Nothing, Just 2, Nothing, Just 2, Nothing, Nothing]

getVal :: Hmm -> String
getVal (Hmm []) = []
getVal (Hmm (Nothing:xs)) = '.'          : getVal (Hmm xs)
getVal (Hmm (Just x :xs)) = intToDigit x : getVal (Hmm xs)

-- or equivalently

getVal' :: Hmm -> String
getVal' (Hmm xs) = map f xs where
  f Nothing = '.'
  f (Just x) = intToDigit x


答:
As @Clemens kindly pointed out in the comments:

You can't set the Opacity of the system's shared brushes directly.

You will need to use a non-shared SolidColorBrush, and then you will be able to set the Opacity of that.

You will be able to change the Opacity from any point in the code, from thereon-in.

E.g.:

```<code>moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0))
                        {
                            Opacity = 0.5 // or whatever opacity between
                                          //  0.0 (0%) and 1.0 (100%)
                        };
</code>```

Or

```<code>moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0));
moboBorder.Background.Opacity = 0.5;
</code>```

Similar the above example, you could also set the alpha (the opacity) if you're using RGB.

You can use the Color.FromArgb() static method, instead:

```<code>moboBorder.Background = new SolidColorBrush(Color.FromArgb(0.5, 255, 0, 0));
</code>```

Just use a double between 0.0 and 1.0 (as before), as your first argument to the method.

Hope this helps.

Title: Setting WPF background Opacity programmatically

Body:
As @Clemens kindly pointed out in the comments:

You can't set the Opacity of the system's shared brushes directly.

You will need to use a non-shared SolidColorBrush, and then you will be able to set the Opacity of that.

You will be able to change the Opacity from any point in the code, from thereon-in.

E.g.:

moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0))
                        {
                            Opacity = 0.5 // or whatever opacity between
                                          //  0.0 (0%) and 1.0 (100%)
                        };

Or

moboBorder.Background = new SolidColorBrush(Color.FromRgb(255, 0, 0));
moboBorder.Background.Opacity = 0.5;

Similar the above example, you could also set the alpha (the opacity) if you're using RGB.

You can use the Color.FromArgb() static method, instead:

moboBorder.Background = new SolidColorBrush(Color.FromArgb(0.5, 255, 0, 0));

Just use a double between 0.0 and 1.0 (as before), as your first argument to the method.

Hope this helps.


问:
python 3 round on one numpy float unexpectedly yielding float
I have an np.array startIdx originating from a list of tuples consisting of integer and float fields:

```<code>>>> startIdx, someInt, someFloat = np.array(resultList).T
>>> startIdx
array([0.0, 111.0, 333.0]) # 10 to a few 100 positive values of the order of 100 to 10000
>>> round(startIdx[2])
333.0 # oops
>>> help(round)
Round [...] returns an int when called with one argument, otherwise the same type as the number.
>>> round(np.pi)
3
>>> round(np.pi, 2) # the optional argument is the number of decimal digits
3.14
round([0.0, 111.0, 333.0][2]) # to test whether it's specific for numpy arrays.
333
</code>```

The float currently works (as index into numpy arrays) but yields a warning:

```<code> VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
</code>```

I could avoid the conversion from tuples to arrays (and int to float) by collecting my results in a grossly oversized record array (with an int field ''startIdx'').

I could use something like int(. + 0.1), which is also ugly. Would int(round(.)) or even int(.) safely yield correct results?

答:
```<code>In [70]: startIdx=np.array([0.0, 111.0, 333.0])
In [71]: startIdx
Out[71]: array([   0.,  111.,  333.])
</code>```

If you need an integer array, use astype:

```<code>In [72]: startIdx.astype(int)
Out[72]: array([  0, 111, 333])
</code>```

not round:

```<code>In [73]: np.round(startIdx)
Out[73]: array([   0.,  111.,  333.])
</code>```

np.array(resultList) produces a float dtype array because some values are float.  arr=np.array(resultList, dtype='i,i,f') should produce a structured array with integer and float fields, assuming resultList is indeed a list of tuples.

```<code> startIdx = arr['f0']
</code>```

should then be an integer dtype array.

I expect the memory use of the structured array to be the same as for the float one.

Body:
I have an np.array startIdx originating from a list of tuples consisting of integer and float fields:

>>> startIdx, someInt, someFloat = np.array(resultList).T
>>> startIdx
array([0.0, 111.0, 333.0]) # 10 to a few 100 positive values of the order of 100 to 10000
>>> round(startIdx[2])
333.0 # oops
>>> help(round)
Round [...] returns an int when called with one argument, otherwise the same type as the number.
>>> round(np.pi)
3
>>> round(np.pi, 2) # the optional argument is the number of decimal digits
3.14
round([0.0, 111.0, 333.0][2]) # to test whether it's specific for numpy arrays.
333

The float currently works (as index into numpy arrays) but yields a warning:

 VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future

I could avoid the conversion from tuples to arrays (and int to float) by collecting my results in a grossly oversized record array (with an int field ''startIdx'').

I could use something like int(. + 0.1), which is also ugly. Would int(round(.)) or even int(.) safely yield correct results?

Body:
In [70]: startIdx=np.array([0.0, 111.0, 333.0])
In [71]: startIdx
Out[71]: array([   0.,  111.,  333.])

If you need an integer array, use astype:

In [72]: startIdx.astype(int)
Out[72]: array([  0, 111, 333])

not round:

In [73]: np.round(startIdx)
Out[73]: array([   0.,  111.,  333.])

np.array(resultList) produces a float dtype array because some values are float.  arr=np.array(resultList, dtype='i,i,f') should produce a structured array with integer and float fields, assuming resultList is indeed a list of tuples.

 startIdx = arr['f0']

should then be an integer dtype array.

I expect the memory use of the structured array to be the same as for the float one.


问:
Select first empty cell in range
So my very basic VBA skills limit my programming codes. I want to search within a Range("A14:A23") the first empty cell in order to fill in a value. I have to do this within various ranges in A, so I can't just use the lastcell in column code. Can anyone help me?</p>

答:
If you're using various ranges, you could write it as a subroutine to take the first and last cells of the range as arguments:

```<code>Sub FindEmpty(a, b)

    ' loop through the range, find the first empty cell, then exit the loop

    For Each x In ActiveSheet.Range(a, b)
        If x.Value = "" Then
            ' do something here
            Exit For
        End If
    Next x

End Sub
</code>```

a would be the first cell in the range and b would be the last cell in the range. Once the first empty cell is found, you can execute your code, then quit the subroutine.

You could also set the subroutine to grab those values (first and last cell) from a cell on your spreadsheet instead of passing them in directly, or you could hardcode them into the subroutine if you wanted.

Title: Select first empty cell in range

Body:
If you're using various ranges, you could write it as a subroutine to take the first and last cells of the range as arguments:

Sub FindEmpty(a, b)

    ' loop through the range, find the first empty cell, then exit the loop

    For Each x In ActiveSheet.Range(a, b)
        If x.Value = "" Then
            ' do something here
            Exit For
        End If
    Next x

End Sub

a would be the first cell in the range and b would be the last cell in the range. Once the first empty cell is found, you can execute your code, then quit the subroutine.

You could also set the subroutine to grab those values (first and last cell) from a cell on your spreadsheet instead of passing them in directly, or you could hardcode them into the subroutine if you wanted.


问:
Laravel Eloquent with the max in second table?
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

```<code>$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}
</code>```

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )
```

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

答:
If i understand you correct, you want to grab all the listings between minimum_bid and maximum_bid, and sort them by listing_id?

You can do this:

```<code>//This gets you array of collections sorted by listing_id and sorted from
  highest bid_amount to lowest.
 $listings = Listing::join('bids', 'listings.id', '=', 'bids.listing_id');

if (!empty($request->minimum_bid)  && !empty($request->maximum_bid)) {

    $listings->whereBetween('bid_amount', [$request->minimum_bid,
        $request->maximum_bid]);

} else {

    if( !empty($minimum_bid) ) {

        $listings->where('bid_amount', '>', $request->minimum_bid);

    }

    if( !empty($request->maximum_bid) ) {

       $listings=$listings->where('bid_amount', '<', $request->maximum_bid);
    }

}

$listings = $listings->get()
    ->sortByDesc('bid_amount')
    ->groupBy('listing_id');
</code>```

Result looks like this(i tested with two listings):

```<code>    Collection {#196 ▼
  #items: array:2 [▼
    2 => Collection {#184 ▼
      #items: array:3 [▼
        0 => Listing {#204 ▶}
        1 => Listing {#208 ▶}
        2 => Listing {#207 ▶}
      ]
    }
    1 => Collection {#197 ▼
      #items: array:4 [▼
        0 => Listing {#203 ▶}
        1 => Listing {#205 ▶}
        2 => Listing {#206 ▶}
        3 => Listing {#202 ▶}
      ]
    }
  ]
}
</code>```

Body:
I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.

For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.

In bids we have two relevant fields: listing_id, and bid_amount.

For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.

The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.

$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');

if( !empty($request->keyword) ) {
    $listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
                ->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}

if( !empty($request->category) ) {
    $listings = $listings->where('listings.category_id','=',$request->category);
}

if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
    $listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
    if( !empty($request->minimum_bid) ) {
        $listings = $listings->where('bid_amount', '>', $request->minimum_bid);
    }

    if( !empty($request->maximum_bid) ) {
        $listings = $listings->where('bid_amount', '<', $request->maximum_bid);
    }
}

The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.

The equivalent MySQL query should be:

SELECT *
FROM   listings
       JOIN (SELECT listing_id,
                    Max(bid_amount) AS bid_amount
             FROM   bids
             GROUP  BY listing_id) bids
         ON bids.listing_id = listings.id
WHERE  ( listings.NAME LIKE '%keyword%'
          OR listings.tagline LIKE '%keyword%'
          OR listings.short_description LIKE' %keyword%'
          OR listings.seller_notes LIKE '%keyword%' )
       AND ( bids.bid_amount > minimum_bid )
       AND ( bids.bid_amount < maximum_bid )

I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.

Body:
If i understand you correct, you want to grab all the listings between minimum_bid and maximum_bid, and sort them by listing_id?

You can do this:

//This gets you array of collections sorted by listing_id and sorted from
  highest bid_amount to lowest.
 $listings = Listing::join('bids', 'listings.id', '=', 'bids.listing_id');

if (!empty($request->minimum_bid)  && !empty($request->maximum_bid)) {

    $listings->whereBetween('bid_amount', [$request->minimum_bid,
        $request->maximum_bid]);

} else {

    if( !empty($minimum_bid) ) {

        $listings->where('bid_amount', '>', $request->minimum_bid);

    }

    if( !empty($request->maximum_bid) ) {

       $listings=$listings->where('bid_amount', '<', $request->maximum_bid);
    }

}

$listings = $listings->get()
    ->sortByDesc('bid_amount')
    ->groupBy('listing_id');

Result looks like this(i tested with two listings):

    Collection {#196 ▼
  #items: array:2 [▼
    2 => Collection {#184 ▼
      #items: array:3 [▼
        0 => Listing {#204 ▶}
        1 => Listing {#208 ▶}
        2 => Listing {#207 ▶}
      ]
    }
    1 => Collection {#197 ▼
      #items: array:4 [▼
        0 => Listing {#203 ▶}
        1 => Listing {#205 ▶}
        2 => Listing {#206 ▶}
        3 => Listing {#202 ▶}
      ]
    }
  ]
}


问:
How to change separator color for UITableView only for first row?
```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        tableView.separatorColor = UIColor.clear
    } else {
        tableView.separatorColor = UIColor.blue
    }
}
</code>```

I have the above code to change the separator color for only first row. However, the whole section itself turns out with a clear color separator instead of blue. Could you please help me with this. Any help would be greatly appreciated. Thank you.

答:
Don't use tableview default seperator.

tableView.separatorColor = UIColor.clear
or
tableView.separatorStyle = .none

In UITableViewCell add a UIView of 1 px height, give that whatever color you want. If same UITableViewCell is used for all the table rows, then might be you can use something like -

seperatorView.hidden = indexPath.row != 0

Body:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row == 0 {
        tableView.separatorColor = UIColor.clear
    } else {
        tableView.separatorColor = UIColor.blue
    }
}

I have the above code to change the separator color for only first row. However, the whole section itself turns out with a clear color separator instead of blue. Could you please help me with this. Any help would be greatly appreciated. Thank you.