问:
How to get a string from a function which has a void pointer?
When I try to get a string from a function which has type void*, I only get the first character.

I tried to copy string manually without using strcpy() it gives me same problem

```<code>struct arr {
   int first
   int last.
   void **val;
};

//I have a function which is called
void *inspect_arr(const arr *ar, int position)
{
   ....
   return ar->val[offset];
}
//I want to inspect the array so that I can compare the strings
int main()
{
   char *str = calloc(10,sizeof(char));
   char *k = *(char*)inspect_arr(...) //I have a string in the array
  // strcpy(str,k);       Doesn't work
   strcmp(str,k);         Invalid read from valgrind
   //If array has an integer type then I would write my code like this:
   //int a = *(int*)inspect_arr(...) but I can not do the same thing for char
}
</code>```

I get Segmentation fault when I run the program.

答:
One problem is that first * in *(char*)inspect_arr(...).

There you dereference the pointer, getting only the first character. It's equivalent to ((char*)inspect_arr(...))[0].

To make it more troublesome, you then assign this single character to the pointer k. This doesn't make k point to the character, it make k point to whatever address corresponds to that characters encoded value. With e.g. ASCII and the character 'd' the initialization is equivalent to

```<code>char *k = 100;
</code>```

Body:
When I try to get a string from a function which has type void*, I only get the first character.

I tried to copy string manually without using strcpy() it gives me same problem

struct arr {
   int first
   int last.
   void **val;
};

//I have a function which is called
void *inspect_arr(const arr *ar, int position)
{
   ....
   return ar->val[offset];
}
//I want to inspect the array so that I can compare the strings
int main()
{
   char *str = calloc(10,sizeof(char));
   char *k = *(char*)inspect_arr(...) //I have a string in the array
  // strcpy(str,k);       Doesn't work
   strcmp(str,k);         Invalid read from valgrind
   //If array has an integer type then I would write my code like this:
   //int a = *(int*)inspect_arr(...) but I can not do the same thing for char
}

I get Segmentation fault when I run the program.

Body:
One problem is that first * in *(char*)inspect_arr(...).

There you dereference the pointer, getting only the first character. It's equivalent to ((char*)inspect_arr(...))[0].

To make it more troublesome, you then assign this single character to the pointer k. This doesn't make k point to the character, it make k point to whatever address corresponds to that characters encoded value. With e.g. ASCII and the character 'd' the initialization is equivalent to

char *k = 100;


来源: stackexchange

问:
How to send the element object as parameter to javascript function without ID
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

```<code><td ...... >
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXX">

<td ......
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXXX">
</code>```

Based on clicked ....> I would like to hide/show it (or to show/hide next class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

```<code>function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}
</code>```

答:
I tried both recommendations(thx for it) - no success.

It looks that the "this" argument is not passed like clicked element(object) reference.

The parameter "row" seems to be like parent of all object, so like new Object and not the clicked object.

I am not sure if href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)"  is correct syntax though.

ContentLicense: CC BY-SA 4.0

Body:
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

<td ......

Based on clicked  I would like to hide/show it (or to show/hide next <a class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}


问:
Get value based on input in two dimensional array
I have a 2 dimensional array

```<code>var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];
</code>```

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.

答:
You could take a Map with Map#get and the key for getting the value.

var years = [[-1, "0 years"], [1, "< 1 year"], [2, "1-3 years"], [3, "> 3 years"]],
    yearsMap = new Map(years);

console.log(yearsMap.get(1));```

Body:
I have a 2 dimensional array

var years = [[-1,"0 years"], [1,"< 1 year"], [2,"1-3 years"], [3,"> 3 years"]];

And I want to get the number of years based on user Input, which is -1,1,2,3 how can I do it in Javascript?

I'm trying using years[years_input] but I don't get the correct value.


问:
RxJava2 flatMap operator
I'm try to use the flatMap operator to make two request using retrofit on Android. The idea is make the first request to get the users and after that make the second request which I need to know the total of users that I get to make the second request. This is the way I'm trying to do it.

```<code>remoteDataSource.requestAuthors()
            .flatMap {remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .subscribe {
                //here I need the authors and avatars to create the new object
            }
</code>```

Is the flatMap the correct operator to do that? Thanks!

Answer - Yes!

Updating

In that case, should I do something like that?

```<code>override fun requestAuthors(): Observable<List<AuthorResponse>> {
        val authors = mutableListOf<Author>()
        val authorResponse = remoteDataSource.requestAuthors()
            .doOnNext { authors.addAll(it) }
            .flatMap { remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .doOnNext {avatars->
                avatars.results.forEach { avatar ->
                    authors.forEach { author ->
                        author.avatarUrl = avatar
                    }
                }
            }

        return authorResponse

    }
</code>```

答:
I think, flatMap is a great operator to do stuff like this. You will handle errors from each request and they will execute one after another.

If you need to do something between these two requests, use doOnSuccess() operator.

```<code>remoteDataSource.requestAuthors()
                .doOnSuccess { /*interact with authors*/ }
                .flatMap {remoteDataSource.requestAvatars(it.size) }
                .subscribeOn(Schedulers.io())
                .subscribe {
            /*interact with avatart*/
        }
</code>```

Title: RxJava2 flatMap operator

Body:
I'm try to use the flatMap operator to make two request using retrofit on Android. The idea is make the first request to get the users and after that make the second request which I need to know the total of users that I get to make the second request. This is the way I'm trying to do it.

remoteDataSource.requestAuthors()
            .flatMap {remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .subscribe {
                //here I need the authors and avatars to create the new object
            }

Is the flatMap the correct operator to do that? Thanks!

Answer - Yes!

Updating

In that case, should I do something like that?

override fun requestAuthors(): Observable<List<AuthorResponse>> {
        val authors = mutableListOf<Author>()
        val authorResponse = remoteDataSource.requestAuthors()
            .doOnNext { authors.addAll(it) }
            .flatMap { remoteDataSource.requestAvatars(it.size) }
            .subscribeOn(Schedulers.io())
            .doOnNext {avatars->
                avatars.results.forEach { avatar ->
                    authors.forEach { author ->
                        author.avatarUrl = avatar
                    }
                }
            }

        return authorResponse

    }

Body:
I think, flatMap is a great operator to do stuff like this. You will handle errors from each request and they will execute one after another.

If you need to do something between these two requests, use doOnSuccess() operator.

remoteDataSource.requestAuthors()
                .doOnSuccess { /*interact with authors*/ }
                .flatMap {remoteDataSource.requestAvatars(it.size) }
                .subscribeOn(Schedulers.io())
                .subscribe {
            /*interact with avatart*/
        }


问:
How to version & publish snapshot/not-finished work on a go module?
I'm new in Golang, and I'm trying to develop a go-module and share it with my colleagues while I'm developing it; In JVM/sbt I used to publish my work with a 'SNAPSHOT' postfixed to version value. but How I can achieve the same in with go-modules? </p>

答:
Versions for modules are tagged by using repo tags (e.g. git tag), following semantic versioning (https://semver.org/).

So, any version starting with v0 is treated as unstable and may make breaking changes at any time. Once you release a v1, you cannot make any breaking changes without bumping your major version, which also means you change your module name.

You also have the option of appending +foo to the end of your version to indicate additional information about the version.

I wrote https://blog.golang.org/using-go-modules as an overview of how to get started using modules.


问:
Internal Server Error for Deshboard only mode user
I have created dashboard and shared it to other computer which is demo user with  the role-> kibana_dashboard_only_user.
now when i open shared with demo user login credentials it shows error like

```<code>Internal Server Error

Error: Internal Server Error
      SearchError@http://10.42.35.14:5601/bundles/commons.bundle.js:3:298201
_callee2$/<.searching</<@http://10.42.35.14:5601/bundles/commons.bundle.js:4:324908
processQueue@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:199687
scheduleProcessQueue/<@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:200650
$digest@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:210412
$apply@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:213219
done@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:132717
completeRequest@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:136329
requestLoaded@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:135225
</code>```

答:
Does the user have read permissions on the index? Just dashboard permissions alone are not enough; this is unfortunately not super obvious.

The user (or role) needs to have at least the read permission on the desired index in addition to the dashboard-only role.

Check the documentation here:

https://www.elastic.co/guide/en/kibana/current/xpack-dashboard-only-mode.html#grant-read-access-to-indices

BTW the feature has generally been reworked and is deprecated in the old form

Body:
I have created dashboard and shared it to other computer which is demo user with  the role-> kibana_dashboard_only_user.
now when i open shared with demo user login credentials it shows error like

Internal Server Error

Error: Internal Server Error
      SearchError@http://10.42.35.14:5601/bundles/commons.bundle.js:3:298201
_callee2$/<.searching</<@http://10.42.35.14:5601/bundles/commons.bundle.js:4:324908
processQueue@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:199687
scheduleProcessQueue/<@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:200650
$digest@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:210412
$apply@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:213219
done@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:132717
completeRequest@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:136329
requestLoaded@http://10.42.35.14:5601/built_assets/dlls/vendors.bundle.dll.js:427:135225


问:
calling a function within a function
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

```<code>function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '<p>The date field is empty.</p>';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '<div class="news-preview-container">';
        echo '<div class="news-preview-container-date">';
        echo "<P>" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "</p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-title">';
        echo "<p><a href='article.php?id=" .$row['nid']."'>" .$row['title']."</a></p><BR>";
        echo '</div>';
        echo '<div class="news-preview-container-inner">';
        echo '<div class="news-preview-container-text">';
        echo '<p>'.ShortenText($row['body']).'</p>';
        echo '</div>';
        echo '<div class="news-preview-container-image"><img src="'.$imgurl.'"'.$scale.'"></div><BR></div>';
        echo '<div class="news-preview-container-bottombar">Posted in '.$row[tag].' / '.$comcount.' Comments</div>';
        echo '</div>';

    }
}
</code>```

and the check_orientation function

```<code>function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}
</code>```

Thanks in advance to whoever points out the silly mistake i'm missing!

答: You aren't doing anything with the return value of check_orientation4</p>

ContentLicense: CC BY-SA 3.0

Title: calling a function within a function

Body:
I've had a look through several of the related questions and just can't seem to see the issue!

the following two functions are within my function include file and for some reason I cannot seem to get the check_orientation function to return scale to the display_months_news function.

I'm fairly sure I'm just missing something really obviously.

the display_news function

function display_months_news()
{
    //header('Content-type: image/jpeg');
    $year = date("y");
    $year = "20" .$year;
    $month = date("m");
    if ($month) {
        switch ($month){
            case "01": $month = "January"; break;
            case "02": $month = "February"; break;
            case "03": $month = "March"; break;
            case "04": $month = "April"; break;
            case "05": $month = "May"; break;
            case "06": $month = "June"; break;
            case "07": $month = "July"; break;
            case "08": $month = "August"; break;
            case "09": $month = "September"; break;
            case "10": $month = "October"; break;
            case "11": $month = "November"; break;
            case "12": $month = "December"; break;
        }
    } else {
        echo '
The date field is empty.
';
    }
    $nowdate = $month." ".$year;

    $result = mysql_query("SELECT * FROM news ORDER BY sqldate DESC LIMIT 6") or die(mysql_error());

    while ($row = mysql_fetch_array($result)) {
        global $imgurl;
        $imgurl = $row['img1'];

        check_orientation4($imgurl);

        $comcount = comment_count($row['nid']);
        if ($comcount == NULL) {$comcount = 0;}

        echo '
';
        echo '
';
        echo "
" .$row['mmonth']. " ".$row['dday']. ", " .$row['yyear']. "

";
        echo '
';
        echo '
';
        echo "
" .$row['title']."

";
        echo '
';
        echo '
';
        echo '
';
        echo '
'.ShortenText($row['body']).'
';
        echo '
';
        echo '

';
        echo '
Posted in '.$row[tag].' / '.$comcount.' Comments
';
        echo '
';

    }
}

and the check_orientation function

function check_orientation4($imgurls){

if ($imgurls == NULL){ echo "";  }
else {
        $imgurlshrunk = NULL;
        $maxsize = 120;
        $filename = NULL;
        $height = NULL;
        $width = NULL;
        $scale = NULL;
        $imgurlshrunk = $imgurls;
        $filename = basename($imgurlshrunk);
        $filename = "admin/uploads/" . $filename;
        list($width,$height,$type,$attr) = getimagesize("$filename");
        $wRatio = $maxsize / $width;
        $hRatio= $maxsize / $height;

    global $scale;

    if ( ($width <= $maxsize) && ($height <= $maxsize))
      {

        $scale = "";
        return $scale;
      }
    elseif ( ($wRatio * $height) < $maxsize)
    {
        $scale = "width = '100%'";
        return $scale;
    }
    elseif  ($height == NULL)
    {

        echo "empty height";
    }
    else
    {
    global $height;
        $scale = "height = '100%'";
        return $scale;
    }       }}

Thanks in advance to whoever points out the silly mistake i'm missing!


问:
More than one top level domain?
In a normal URL, you have a protocol, subdomains (optional), domain name, top level domain and subdirectories.

For example: http://www.google.com/path. Here www is subdomain, google is domain name and com is TLD; path is subdirectory here. Parsing this is simple programming task.

But the problem comes when there are more than one TLD's. For example: www.google.co.in/path. Here co.in is TLD. But I see that there is a website with name www.co.in also present.

My doubts are:

How many Top level domains can a URL have? In a URL how to find the top level domains, if there could be multiple TLDs?

In the above example google.co.in is not a subdomain of co.in, so how come www.co.in is resolving to a different website than google.co.in?

Title: More than one top level domain?


问:
Python3 imports
I am looking for a way to import modules so that I can run a script both from the sub-folder project/v0 and from the root folder project

My file structure in python 3.6 (which is why there are no init files)

```<code>project
├── api.py
├── v0
│   ├── SearchEngine.py     => contains SearchEngine class
│   └── SearchEngineBE.py
</code>```

My SearchEngineBE.py module contains

```<code>from SearchEngine import SearchEngine
</code>```

My api.py module contains

```<code>from v0.SearchEngineBE import SearchEngineBE
</code>```

step1: When from project/v0 I run python3 SearcheEngineBE.py my module is correctly imported and everything goes well.

step2: However, when from project I run python3 run api.py I get the error:

```<code>Traceback (most recent call last):
  File "api.py", line 3, in <module>
    from v0.SearchEngineBE import SearchEngineBE
  File "/xxx/project/v0/SearchEngineBE.py", line 3, in <module>
    from SearchEngine import SearchEngine
ModuleNotFoundError: No module named 'SearchEngine'
</code>```

How can I fix this so that both step 1 and step 2 would work ?

答:
Non-relative imports are searched by the interpreter in the current directory (and any additional search paths).

You could use relative imports in your SearchEngineBE.py file to let the interpreter know you want the relative module, and not a module off the import path:

```<code># SearchEngineBE.py
from .SearchEngine import SearchEngine
</code>```

The . lets the interpreter know that you are referencing a module relative to the current module.  You'll need at least a blank __init__.py file in the same directory as SearchEngine.py for relative imports to work though:

The __init__.py files are required to make Python treat directories
  containing the file as packages.

https://docs.python.org/3/tutorial/modules.html

See this guide for some more discussion: https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html#absolute-vs-relative-import

Edit:
Without a root package, this won't work.  See this post for an alternative approach: Importing modules from a neighbouring folder in Python

Title: Python3 imports

Body:
I am looking for a way to import modules so that I can run a script both from the sub-folder project/v0 and from the root folder project

My file structure in python 3.6 (which is why there are no init files)

project
├── api.py
├── v0
│   ├── SearchEngine.py     => contains SearchEngine class
│   └── SearchEngineBE.py

My SearchEngineBE.py module contains

from SearchEngine import SearchEngine

My api.py module contains

from v0.SearchEngineBE import SearchEngineBE

step1: When from project/v0 I run python3 SearcheEngineBE.py my module is correctly imported and everything goes well.

step2: However, when from project I run python3 run api.py I get the error:

Traceback (most recent call last):
  File "api.py", line 3, in <module>
    from v0.SearchEngineBE import SearchEngineBE
  File "/xxx/project/v0/SearchEngineBE.py", line 3, in <module>
    from SearchEngine import SearchEngine
ModuleNotFoundError: No module named 'SearchEngine'

How can I fix this so that both step 1 and step 2 would work ?

Body:
Non-relative imports are searched by the interpreter in the current directory (and any additional search paths).

You could use relative imports in your SearchEngineBE.py file to let the interpreter know you want the relative module, and not a module off the import path:

# SearchEngineBE.py
from .SearchEngine import SearchEngine

The . lets the interpreter know that you are referencing a module relative to the current module.  You'll need at least a blank __init__.py file in the same directory as SearchEngine.py for relative imports to work though:

The __init__.py files are required to make Python treat directories
  containing the file as packages.

https://docs.python.org/3/tutorial/modules.html

See this guide for some more discussion: https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html#absolute-vs-relative-import

Edit:
Without a root package, this won't work.  See this post for an alternative approach: Importing modules from a neighbouring folder in Python


问:
Shell user prompt (Y/n)
I just wanted to write a small sript for copying some files for my NAS,
so I'm not very experienced in Shell-Scripting.
I know that many command line tools on Linux use the following sheme for Yes/No inputs

```<code>Are you yure [Y/n]
</code>```

where the capitalized letter indicates the standard action which would also be started
by hitting Enter.
Which is nice for a quick usage.

I also want to implement something like this, but I have some trouble with caching the Enter key.
Here is what I got so far:

```<code>read -p "Are you sure? [Y/n] " response

    case $response in [yY][eE][sS]|[yY]|[jJ]|[#insert ENTER codition here#])

        echo
        echo files will be moved
        echo
        ;;
    *)
        echo
        echo canceld
        echo
        ;;
esac
</code>```

I can add what ever I want but it just won't work with Enter.

答:
A few years passed since the question was asked, but since it's still relevant in searches I thought I'd provide the different method I ended up using.

I wanted to lock the question in place until a y/n/enter is pressed and without spamming the prompt request, so I (ab)used the -s echo suppression and came up with the following:

```<code>#!/bin/bash
echo -n "Confirm action [y/N]? "
while true; do
    read -sn1 response
    case "$response" in
        [yY]) echo 'y'; break;;
        [nN]|"") echo 'n'; exit 0;;
    esac
done
</code>```

Upon N or Enter the script is ended, otherwise it just goes on as intended. The additional echos to output user choice is not necessary, but I left it in as a visual feedback.

Also, by moving the |"" around, you can default the enter key to either yes or no responses.

Title: Shell user prompt (Y/n)

Body:
I just wanted to write a small sript for copying some files for my NAS,
so I'm not very experienced in Shell-Scripting.
I know that many command line tools on Linux use the following sheme for Yes/No inputs

Are you yure [Y/n]

where the capitalized letter indicates the standard action which would also be started
by hitting Enter.
Which is nice for a quick usage.

I also want to implement something like this, but I have some trouble with caching the Enter key.
Here is what I got so far:

read -p "Are you sure? [Y/n] " response

    case $response in [yY][eE][sS]|[yY]|[jJ]|[#insert ENTER codition here#])

        echo
        echo files will be moved
        echo
        ;;
    *)
        echo
        echo canceld
        echo
        ;;
esac

I can add what ever I want but it just won't work with Enter.

Body:
A few years passed since the question was asked, but since it's still relevant in searches I thought I'd provide the different method I ended up using.

I wanted to lock the question in place until a y/n/enter is pressed and without spamming the prompt request, so I (ab)used the -s echo suppression and came up with the following:

#!/bin/bash
echo -n "Confirm action [y/N]? "
while true; do
    read -sn1 response
    case "$response" in
        [yY]) echo 'y'; break;;
        [nN]|"") echo 'n'; exit 0;;
    esac
done

Upon N or Enter the script is ended, otherwise it just goes on as intended. The additional echos to output user choice is not necessary, but I left it in as a visual feedback.

Also, by moving the |"" around, you can default the enter key to either yes or no responses.


问:
How to move file from one folder to another folder on remote sftp server providing the filename dynamically using Java Config?
I am stuck with the problem. I have a folder om my sftp server with a file in it: folder/file.txt . What i'm trying to do is simply to move this file to another directory : folder/subfolder/file.txt. In documentation it was written that you simply need to use OutboundGateway with the MV command. That's ok but the main problem is that i don`t know exactly what would be the name of the file, so i need to provide this name dynamically. How can i do that?

@Bean
@InboundChannelAdapter(value = "toSftpChannel",
        poller = @Poller(fixedDelay = "60000", maxMessagesPerPoll = "-1"))
public MessageSource<File> sftpMessageSource() {
    SftpInboundFileSynchronizingMessageSource source =
            new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
    source.setLocalDirectory(new File(localDirectory));
    source.setAutoCreateLocalDirectory(true);
    source.setLocalFilter(new AcceptOnceFileListFilter<File>());
    return source;
}

@Bean
public SftpInboundFileSynchronizer sftpInboundFileSynchronizer() {
    SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(getSftpSessionFactory());
    fileSynchronizer.setDeleteRemoteFiles(false);
    fileSynchronizer.setRemoteDirectory("/folder");
    fileSynchronizer.setFilter(new FtpSimplePatternFileListFilter("*.txt"));
    return fileSynchronizer;
}

@Bean
@ServiceActivator(inputChannel = "toSftpChannel")
public SftpOutboundGateway moveFileHandler() {
     SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(getSftpSessionFactory(), "mv", "'folder/" + "file.txt" + "'");
        sftpOutboundGateway.setRenameExpression(new LiteralExpression("/folder/subfolder/" + "file.txt"));
        return sftpOutboundGateway;
    }
```

答:
Instead of using literal expressions, use a dynamic expression.

e.g. instead of

```<code>"'folder/" + "file.txt" + "'"
</code>```

use

```<code>"'folder/' + headers['file_relativePath']"
</code>```

and

```<code>sftpOutboundGateway.setRenameExpression(parser.parseExpression("'/folder/subfolder/' + headers['file_relativePath']";
</code>```

(The relative path header is set up by the inbound adapter).

Body:
Instead of using literal expressions, use a dynamic expression.

e.g. instead of

"'folder/" + "file.txt" + "'"

use

"'folder/' + headers['file_relativePath']"

and

sftpOutboundGateway.setRenameExpression(parser.parseExpression("'/folder/subfolder/' + headers['file_relativePath']";

(The relative path header is set up by the inbound adapter).


问:
What's the best server / network architecture for powerful web development?
What I have:

Cloud Hosting + CDN

What I want:

Multiple development servers, ideally assigned to a sub-domain (e.g dev.domain.com) - Some of these will be used for in-house work, other for clients

I want to push changes from these dev servers (through subversion) to independent staging servers, and finally, to production server

I want to have multiple servers for databases, client-side content

I want to use a LAMP stack (with Zend Framework)

I will eventually upgrade to RedHat for the Linux distribution, but I want to know the best way to 1) map everything out 2) what distribution would be good for now (I'm thinking centOS)

答: That's old-school. Take a look at hadoop. Build on homogeneous distributed computing.</p>


问:
Webhook| Gitlab | jenkins pipeline |Declarative syntax
I'm trying to integrate Webhook with gitlab and jenkins. I have done it via upstream downstream jobs using the URL.
While trying to rece=reate the same via declarative pipeline, I'm in a stanstill

```<code> pipeline {
  agent any
  stages {
    stage('fetchcodeFromGit') {
      steps {
        timeout(time: 30) {
          git(url: 'http:<<>>/JenkinsPipeline.git', branch: 'master', credentialsId: 'QualityAssurance', poll: true)
        }

      }
    }
</code>```

Can anyone help with documents or any sample snippets?

答:
You can use this snippet:

```<code>pipeline {

options {
    gitLabConnection('your-gitlab-conn')
}

triggers {
    gitlab(
      triggerOnPush: false,
      triggerOnMergeRequest: true, triggerOpenMergeRequestOnPush: "both",
      triggerOnNoteRequest: true,
      noteRegex: "Jenkins please retry a build",
      skipWorkInProgressMergeRequest: false,
      ciSkip: false,
      setBuildDescription: true,
      addNoteOnMergeRequest: true,
      addCiMessage: true,
      addVoteOnMergeRequest: true,
      acceptMergeRequestOnSuccess: false,
      branchFilterType: "All",
      secretToken: "NOTVERYSECRET")
}

stages {
    ...
</code>```

more details here: https://github.com/jenkinsci/gitlab-plugin

Body:
I'm trying to integrate Webhook with gitlab and jenkins. I have done it via upstream downstream jobs using the URL.
While trying to rece=reate the same via declarative pipeline, I'm in a stanstill

 pipeline {
  agent any
  stages {
    stage('fetchcodeFromGit') {
      steps {
        timeout(time: 30) {
          git(url: 'http:<<>>/JenkinsPipeline.git', branch: 'master', credentialsId: 'QualityAssurance', poll: true)
        }

      }
    }

Can anyone help with documents or any sample snippets?

Body:
You can use this snippet:

pipeline {

options {
    gitLabConnection('your-gitlab-conn')
}

triggers {
    gitlab(
      triggerOnPush: false,
      triggerOnMergeRequest: true, triggerOpenMergeRequestOnPush: "both",
      triggerOnNoteRequest: true,
      noteRegex: "Jenkins please retry a build",
      skipWorkInProgressMergeRequest: false,
      ciSkip: false,
      setBuildDescription: true,
      addNoteOnMergeRequest: true,
      addCiMessage: true,
      addVoteOnMergeRequest: true,
      acceptMergeRequestOnSuccess: false,
      branchFilterType: "All",
      secretToken: "NOTVERYSECRET")
}

stages {
    ...

more details here: https://github.com/jenkinsci/gitlab-plugin


问:
Building a Protein Data Bank (PDB) file
I have to model a complex polymer of lysine. It resembles a protein, except the lysines don't always bound with their alpha amine. My goal is to produce a PDB (Protein Data Bank) for further calculations.

Do you know any module allowing me to build a molecule? I have special needs, like:

I have chain of amino acid

I need to add one more to the chain

but I have to be able to specify where and how this n+1 amino acid bounds to the previous one

At the end, I have to be able to generate a PDB file

My first approach was to use the SMILES format, and I can do everything perfectly, except I can not build a pdb at the end, because there is no software capable of handling my number of atoms (> 15000).

答:
You could overlay selected atoms from the amino acid and the protein to make an artificial bond in pymol -
https://pymolwiki.org/index.php/Pair_fit

then export as a .pdb

you can have a play with the molecule/s positions before pairing.

Title: Building a Protein Data Bank (PDB) file


问:
Cannot step into .NET framework source with VS2008 SP1
Somehow my VS2008 SP1 has lost the ability to step into .NET framework sources. I've played around with checkboxes to no end; I've re-deleted the Symbol cache folder a dozen times; and I've tried all kinds of debug symbol servers.

All it does is download some .PDB files, but when I try to select a stack frame in .NET, I always get the message about no source available and "do you want to view disassembly".

What gives?

Added: Web application; Windows Vista Business x32; .NET 3.5 SP1.

答: Try this instruction, I got everything works fine!</p>

OwnerDisplayName: Vilx-

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha

OwnerDisplayName: abatishchev


问:
unpleasant separator between embedded activities
I have an ActivityGroup embeds some other activities. But at the top of each embedded activity layout there is a separator (with shadow, like below a window custom title).

I don't know how to remove it.

```<code>Intent intent = new Intent(this, HomeLocalProductsActivity.class);
Window w = getLocalActivityManager().startActivity("LocalProducts", intent);
View dv = null == w ? null : w.getDecorView();
if (null != dv) {
    ((ViewGroup) findViewById(R.id.home_content_wrapper)).addView(dv);
}
</code>```

This the code inside the ActivityGroup to get the sub-activity content and add it.

答:
It looks like all embeded activities inherit their style from their parent activity group. So, if you apply a style to the activity group that has no windowContentOverlay, like this:

```<code><style name="Theme.MasterActivity" parent="@android:style/Theme">
    <item name="android:windowContentOverlay">@null</item>
</style>
</code>```

It will effectively apply to all embeded activities and they'll get rid of the annoying shadow. Unfortunately, this removes the effect from the parent activity, which may not good look for your app.

Another approach is to hack into the view hierarchy to modify the relevent property of the embeded activities at runtime. A quick inspection with the HierarchyViewer shows that this annoying shadow is drawn as a foreground of a FrameLayout inside the DecorView. The FrameLayout itself contains our actual user-defined layout:

```<code>+-----------+     +-------------+     +--------------------+
| DecorView |-----| FrameLayout |-----| Your actual layout |----- ...
+-----------+     +-------------+     +--------------------+
</code>```

So the task is to call setForeground(null) on this FrameLayout in the middle.  If we rework the last example by luc, it will look like this:

```<code>final Window w = getLocalActivityManager().startActivity("LocalProducts", intent);
final View dv = null == w ? null : w.getDecorView();
if (dv != null && instanceof ViewGroup) {
    ViewGroup group = (ViewGroup) currentView;
    if (group.getChildCount() > 0) {
        View child = group.getChildAt(0);
        if (child instanceof FrameLayout) {
            ((FrameLayout) child).setForeground(null); // die, annoying shadow!
        }
    }
}
</code>```

Body:
I have an ActivityGroup embeds some other activities. But at the top of each embedded activity layout there is a separator (with shadow, like below a window custom title).

I don't know how to remove it.

Intent intent = new Intent(this, HomeLocalProductsActivity.class);
Window w = getLocalActivityManager().startActivity("LocalProducts", intent);
View dv = null == w ? null : w.getDecorView();
if (null != dv) {
    ((ViewGroup) findViewById(R.id.home_content_wrapper)).addView(dv);
}

This the code inside the ActivityGroup to get the sub-activity content and add it.

Body:
It looks like all embeded activities inherit their style from their parent activity group. So, if you apply a style to the activity group that has no windowContentOverlay, like this:

<style name="Theme.MasterActivity" parent="@android:style/Theme">
    <item name="android:windowContentOverlay">@null</item>
</style>

It will effectively apply to all embeded activities and they'll get rid of the annoying shadow. Unfortunately, this removes the effect from the parent activity, which may not good look for your app.

Another approach is to hack into the view hierarchy to modify the relevent property of the embeded activities at runtime. A quick inspection with the HierarchyViewer shows that this annoying shadow is drawn as a foreground of a FrameLayout inside the DecorView. The FrameLayout itself contains our actual user-defined layout:

+-----------+     +-------------+     +--------------------+
| DecorView |-----| FrameLayout |-----| Your actual layout |----- ...
+-----------+     +-------------+     +--------------------+

So the task is to call setForeground(null) on this FrameLayout in the middle.  If we rework the last example by luc, it will look like this:

final Window w = getLocalActivityManager().startActivity("LocalProducts", intent);
final View dv = null == w ? null : w.getDecorView();
if (dv != null && instanceof ViewGroup) {
    ViewGroup group = (ViewGroup) currentView;
    if (group.getChildCount() > 0) {
        View child = group.getChildAt(0);
        if (child instanceof FrameLayout) {
            ((FrameLayout) child).setForeground(null); // die, annoying shadow!
        }
    }
}


问:
reset validations after form reset(ReactiveForms)
HTML:

```<code><form [formGroup]="locationForm" #myForm="ngForm" class="formContainer">

<div class="buttonContainer">
      <section class="btn1">
          <button
          (click)="addAnotherMethod()"
          mat-raised-button
          color="primary"> Add another method </button>
      </section>

      <section>
          <button
          (click)="addAnotherLocation()"
          mat-raised-button
          color="primary"> Add another location </button>
      </section>
    </div>
</code>```

.TS File

```<code>@ViewChild('myForm') currentLocationForm;

addAnotherLocation(): void{
    if(this.locationForm.valid){
      //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }

addAnotherMethod: void {
    if(this.locationForm.valid){
     //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }
</code>```

With the above code I'm able to reset the form after the data is sent to redux,but after reset, the validation error messages in the new form comes up saying to fill the required fields. I need help in using the correct method in resetting this form and clearing validations when new form is shown. I may be also using wrong method to call two button functions.
Thank you.

答:
If you're looking to reset the form back to it's original state. Meaning before anything has been touched then
Mark as Pristine would be your best bet.

Actually markAsPristine would do what you are expecting but also recalculate the validity based on the form values.

Reset is what would do both clear the form and mark it as it was never touched aka Pristine

So in code you would do something like.

```<code>this.locationForm.reset();
</code>```

Which would mark the fromGroup and all it's children as pristine.
This would effectively reset your form and should not have any validation errors.

Let me know if this helps!

Ex. https://angular-qv2mfx.stackblitz.io

Body:
HTML:

<form [formGroup]="locationForm" #myForm="ngForm" class="formContainer">

          <button
          (click)="addAnotherMethod()"
          mat-raised-button
          color="primary"> Add another method </button>

          <button
          (click)="addAnotherLocation()"
          mat-raised-button
          color="primary"> Add another location </button>

.TS File

@ViewChild('myForm') currentLocationForm;

addAnotherLocation(): void{
    if(this.locationForm.valid){
      //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }

addAnotherMethod: void {
    if(this.locationForm.valid){
     //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }

With the above code I'm able to reset the form after the data is sent to redux,but after reset, the validation error messages in the new form comes up saying to fill the required fields. I need help in using the correct method in resetting this form and clearing validations when new form is shown. I may be also using wrong method to call two button functions.
Thank you.

Body:
If you're looking to reset the form back to it's original state. Meaning before anything has been touched then
Mark as Pristine would be your best bet.

Actually markAsPristine would do what you are expecting but also recalculate the validity based on the form values.

Reset is what would do both clear the form and mark it as it was never touched aka Pristine

So in code you would do something like.

this.locationForm.reset();

Which would mark the fromGroup and all it's children as pristine.
This would effectively reset your form and should not have any validation errors.

Let me know if this helps!

Ex. https://angular-qv2mfx.stackblitz.io


问:
I get an error when I try to install my project packages with npm i
I was getting error installing expressJs to my packages. I have had to do an npm cache clean --force no sucess, then I deleted my node_modules and package-lock.json, I try to reinstall packages using npm i I still got an error.

Now I deleted node.js from my pc windows 10 and downloaded and installed the latest node and tried to reinstall the project packages again. Now the error I get is this

```<code>$ npm i
npm ERR! Unexpected end of JSON input while parsing near '...ncies":{"autoprefixer'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Chioma Onyepere\AppData\Roaming\npm-cache\_logs\2019-05-28T20_26_29_676Z-debug.log
</code>```

My app is built on nextJs

Here's the package.json

```<code>{
  "name": "ratethis",
  "version": "1.0.2",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "now-build": "next build",
    "start": "next start -p %PORT%"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/infinity-web-development/ratethis"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/infinity-web-development/ratethis/issues"
  },
  "homepage": "https://github.com/infinity-web-development/ratethis#readme",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.15.1",
    "faker": "^4.1.0",
    "next": "^8.0.3",
    "next-images": "^1.1.1",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "now": "^15.0.6",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-polls": "^1.2.0",
    "react-redux": "^7.0.1",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.2",
    "shallow-equal": "^1.1.0",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-inline-import": "^3.0.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-react": "^7.11.1",
    "eslint-plugin-standard": "^4.0.0",
    "next-antd-aza-less": "^1.0.2"
  }
}
</code>```

答: I had to delete all of npm-cache directly from my windows 10 pc, from %AppData%, ie ~/AppData\Roaming\npm-cache. Everything works fine now.

Body:
I was getting error installing expressJs to my packages. I have had to do an npm cache clean --force no sucess, then I deleted my node_modules and package-lock.json, I try to reinstall packages using npm i I still got an error.

Now I deleted node.js from my pc windows 10 and downloaded and installed the latest node and tried to reinstall the project packages again. Now the error I get is this

$ npm i
npm ERR! Unexpected end of JSON input while parsing near '...ncies":{"autoprefixer'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Chioma Onyepere\AppData\Roaming\npm-cache\_logs\2019-05-28T20_26_29_676Z-debug.log

My app is built on nextJs

Here's the package.json

{
  "name": "ratethis",
  "version": "1.0.2",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next",
    "build": "next build",
    "now-build": "next build",
    "start": "next start -p %PORT%"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/infinity-web-development/ratethis"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/infinity-web-development/ratethis/issues"
  },
  "homepage": "https://github.com/infinity-web-development/ratethis#readme",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.15.1",
    "faker": "^4.1.0",
    "next": "^8.0.3",
    "next-images": "^1.1.1",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "now": "^15.0.6",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-polls": "^1.2.0",
    "react-redux": "^7.0.1",
    "redux": "^4.0.1",
    "redux-saga": "^1.0.2",
    "shallow-equal": "^1.1.0",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-inline-import": "^3.0.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-react": "^7.11.1",
    "eslint-plugin-standard": "^4.0.0",
    "next-antd-aza-less": "^1.0.2"
  }
}


问:
Using dropdown selection with Plotly Julia
Using Plotly in Julia, I would like to filter the plot data based on the selection event for a dropdown as shown in the example for the similiar case with Plotly in Python that I reproduce here:

I went through the PlotlyJS.jl documentation but could not find how to do it. Is filtering based on dropdown selections currently not supported in Plotly for Julia or am I missing something?

答:
you can use Interact.jl and Plots.jl for this

```<code>using Interact, Plots
some_dataset  = rand( 10, 2)
other_dataset = rand( 10, 2)
datasets=Dict(:some  => some_dataset,
              :other => other_dataset)
@manipulate for dataset = [:some, :other]
    scatter(datasets[dataset])
end
</code>```

Do mind that this will display a multiple-choice widget that's not a drop-down menu, but serves the same purpose. Check the Interact docs for precise information on how to use a drop-down instead.

Body:
you can use Interact.jl and Plots.jl for this

using Interact, Plots
some_dataset  = rand( 10, 2)
other_dataset = rand( 10, 2)
datasets=Dict(:some  => some_dataset,
              :other => other_dataset)
@manipulate for dataset = [:some, :other]
    scatter(datasets[dataset])
end

Do mind that this will display a multiple-choice widget that's not a drop-down menu, but serves the same purpose. Check the Interact docs for precise information on how to use a drop-down instead.


问:
Fixing a SQL Injection Vulnerability on Content Provider Android
I have different apps that share some data with each others, that's done through Content Provider but when I uploaded the apk I received an email saying "Your app(s) are using a content provider that contains a SQL Injection vulnerability."

There are a couple of ways for fixing this according to Google guide:

If an affected ContentProvider needs to be exposed to other apps:

You can prevent SQL Injection into SQLiteDatabase.query by using
strict mode with a projection map. Strict mode protects against
malicious selection clauses and projection map protects against
malicious projection clauses. You must use both of these features to ensure that your queries are safe.

You can prevent SQL Injection into SQLiteDatabase.update and SQLiteDatabase.delete by using a selection clause that uses '?' as a replaceable parameter and a separate array of selection arguments. Your selection clause should not be constructed from untrusted inputs.

But is not clear to me how to proceed with any of the solutions, I don't get exactly how to use the projection map or change the code using selection clause that uses '?'. I mean, I have seen some examples about ProjectionMap but what are the key/value it needs for the query? Do I need to write explicit the values I want? but what if it is a generic method and I don't know in that part of the code what do I want to get? Or how do I convert any query to a ProjectionMap?

I hope I'm explaining myself on this.

Here is my code:

```<code>     @Override
public boolean onCreate() {
    gOpenHelper = new GameDBHelper(getContext());
    return true;
}

/**
 * Builds a UriMatcher that is used to determine witch database request is being made.
 */
public static UriMatcher buildUriMatcher(){
    String content = GamesContract.CONTENT_AUTHORITY;

    // All paths to the UriMatcher have a corresponding code to return
    // when a match is found (the ints above).
    UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    matcher.addURI(content, GamesContract.PATH_GAME, GAME);
    matcher.addURI(content, GamesContract.PATH_GAME + "/#", GAME_ID);

    return matcher;
}

@Override
public String getType(Uri uri) {

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            return GameEntry.CONTENT_TYPE;
        case GAME_ID:
            return GameEntry.CONTENT_ITEM_TYPE;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    Cursor retCursor;
    switch(sUriMatcher.match(uri))
    {
        case GAME:
            retCursor = db.query(
                    GameEntry.TABLE_NAME,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
            );
            break;
        case GAME_ID:
            long _id = ContentUris.parseId(uri);

            retCursor = db.query(
                    GameEntry.TABLE_NAME,
                    projection,
                    GameEntry._ID + " = ?",
                    new String[]{String.valueOf(_id)},
                    null,
                    null,
                    sortOrder
            );
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    retCursor.setNotificationUri(getContext().getContentResolver(), uri);
    return retCursor;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    long _id;
    Uri returnUri;

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            _id = db.insert(GameEntry.TABLE_NAME, null, values);

            if(_id > 0){
                returnUri = GameEntry.BuildGameUri(_id);
            } else{
                throw new UnsupportedOperationException("Unable to insert rows into: " + uri);
            }
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return returnUri;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    int rows; // Number of rows effected

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            rows = db.delete(GameEntry.TABLE_NAME, selection, selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    // Because null could delete all rows:
    if(selection == null || rows != 0){
        getContext().getContentResolver().notifyChange(uri, null);
    }

    return rows;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    int rows;

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            rows = db.update(GameEntry.TABLE_NAME, values, selection, selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    if(rows != 0){
        getContext().getContentResolver().notifyChange(uri, null);
    }

    return rows;
}
</code>```

}

答:
To anyone who can be looking for the answer, it was pretty simpe, I think it was getting hard for me because I wasn't familiar with many concepts about sql on Android.

The problem goes with the queries that require a 'where' clause; in my case update and delete, the things I needed to do in order to fix it was to not use the selection parameter as it is, I needed to do something like:

GamesContract.Games.GAME_NAME + " = ?"

db.delete(GamesContract.Games.TABLE_NAME, GamesContract.Games.GAME_NAME + " = ?", selectionArgs);

Basicaly the table name + " = ?" selection.

This way you are forcing to update only the needed table and prevent the sql injection to modify any place in your database through that same method.

Body:
I have different apps that share some data with each others, that's done through Content Provider but when I uploaded the apk I received an email saying "Your app(s) are using a content provider that contains a SQL Injection vulnerability."

There are a couple of ways for fixing this according to Google guide:

If an affected ContentProvider needs to be exposed to other apps:

You can prevent SQL Injection into SQLiteDatabase.query by using
strict mode with a projection map. Strict mode protects against
malicious selection clauses and projection map protects against
malicious projection clauses. You must use both of these features to ensure that your queries are safe.

You can prevent SQL Injection into SQLiteDatabase.update and SQLiteDatabase.delete by using a selection clause that uses '?' as a replaceable parameter and a separate array of selection arguments. Your selection clause should not be constructed from untrusted inputs.

But is not clear to me how to proceed with any of the solutions, I don't get exactly how to use the projection map or change the code using selection clause that uses '?'. I mean, I have seen some examples about ProjectionMap but what are the key/value it needs for the query? Do I need to write explicit the values I want? but what if it is a generic method and I don't know in that part of the code what do I want to get? Or how do I convert any query to a ProjectionMap?

I hope I'm explaining myself on this.

Here is my code:

     @Override
public boolean onCreate() {
    gOpenHelper = new GameDBHelper(getContext());
    return true;
}

/**
 * Builds a UriMatcher that is used to determine witch database request is being made.
 */
public static UriMatcher buildUriMatcher(){
    String content = GamesContract.CONTENT_AUTHORITY;

    // All paths to the UriMatcher have a corresponding code to return
    // when a match is found (the ints above).
    UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    matcher.addURI(content, GamesContract.PATH_GAME, GAME);
    matcher.addURI(content, GamesContract.PATH_GAME + "/#", GAME_ID);

    return matcher;
}

@Override
public String getType(Uri uri) {

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            return GameEntry.CONTENT_TYPE;
        case GAME_ID:
            return GameEntry.CONTENT_ITEM_TYPE;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    Cursor retCursor;
    switch(sUriMatcher.match(uri))
    {
        case GAME:
            retCursor = db.query(
                    GameEntry.TABLE_NAME,
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
            );
            break;
        case GAME_ID:
            long _id = ContentUris.parseId(uri);

            retCursor = db.query(
                    GameEntry.TABLE_NAME,
                    projection,
                    GameEntry._ID + " = ?",
                    new String[]{String.valueOf(_id)},
                    null,
                    null,
                    sortOrder
            );
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    retCursor.setNotificationUri(getContext().getContentResolver(), uri);
    return retCursor;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    long _id;
    Uri returnUri;

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            _id = db.insert(GameEntry.TABLE_NAME, null, values);

            if(_id > 0){
                returnUri = GameEntry.BuildGameUri(_id);
            } else{
                throw new UnsupportedOperationException("Unable to insert rows into: " + uri);
            }
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return returnUri;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    int rows; // Number of rows effected

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            rows = db.delete(GameEntry.TABLE_NAME, selection, selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    // Because null could delete all rows:
    if(selection == null || rows != 0){
        getContext().getContentResolver().notifyChange(uri, null);
    }

    return rows;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    final SQLiteDatabase db = gOpenHelper.getWritableDatabase();
    int rows;

    switch(sUriMatcher.match(uri))
    {
        case GAME:
            rows = db.update(GameEntry.TABLE_NAME, values, selection, selectionArgs);
            break;
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }

    if(rows != 0){
        getContext().getContentResolver().notifyChange(uri, null);
    }

    return rows;
}

}


问:
How to fix 'string index out of range' error in a function that ciphers a string
I don't know how to efficiently go back to the beginning of the alphabet, when  (index of a letter + 13) is out of range

I've written a function that only works if the (index of a letter + 13) is in range.

```<code>def rot13(message):
    letters = [i for i in message]
    for i in letters:
        if i.isupper():
            letters[letters.index(i)] =
string.ascii_uppercase[string.ascii_uppercase.index(i) + 13]
        elif i.islower():
            letters[letters.index(i)] =
string.ascii_lowercase[string.ascii_lowercase.index(i) + 13]
        else:
            continue
    return ''.join(letters)
</code>```

When I call, e.g. rot13('Test'), of course I get the 'string index is out of range' error, how should i go about that problem?

答:
Use the modulo operator %:

Modulo devides the number by the given factor and keeps the rest, eg:

```<code>27 % 26 = 1
</code>```

In your case it would be this two lines:

```<code>string.ascii_uppercase[(string.ascii_uppercase.index(i) + 13) % 26]

string.ascii_lowercase[(string.ascii_uppercase.index(i) + 13) % 26]
</code>```

Body:
I don't know how to efficiently go back to the beginning of the alphabet, when  (index of a letter + 13) is out of range

I've written a function that only works if the (index of a letter + 13) is in range.

def rot13(message):
    letters = [i for i in message]
    for i in letters:
        if i.isupper():
            letters[letters.index(i)] =
string.ascii_uppercase[string.ascii_uppercase.index(i) + 13]
        elif i.islower():
            letters[letters.index(i)] =
string.ascii_lowercase[string.ascii_lowercase.index(i) + 13]
        else:
            continue
    return ''.join(letters)

When I call, e.g. rot13('Test'), of course I get the 'string index is out of range' error, how should i go about that problem?

Body:
Use the modulo operator %:

Modulo devides the number by the given factor and keeps the rest, eg:

27 % 26 = 1

In your case it would be this two lines:

string.ascii_uppercase[(string.ascii_uppercase.index(i) + 13) % 26]

string.ascii_lowercase[(string.ascii_uppercase.index(i) + 13) % 26]


答:
Add __init__.py to make it a package.
(it could be empty file : __init__.py)

```<code>project
├── __init__.py
├── api.py
├── v0
│   ├── SearchEngine.py     => contains SearchEngine class
│   └── SearchEngineBE.py
</code>```

Edit 1:

try :

```<code>from project.v0.SearchEngine import SearchEngine
</code>```

Title: Python3 imports

Body:
Add __init__.py to make it a package.
(it could be empty file : __init__.py)

project
├── __init__.py
├── api.py
├── v0
│   ├── SearchEngine.py     => contains SearchEngine class
│   └── SearchEngineBE.py

Edit 1:

try :

from project.v0.SearchEngine import SearchEngine


问:
How to input values into already defined arrays?
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

```<code>int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }
</code>```

答:
As vahancho said in a comment, both odd[] and even[] are static arrays. That means once created you can't change the size of any of them. Moreover, when declaring the array, the size cannot be "dynamic", ie int odd[n]; is only valid when n is a compile time constant (note that some compiler offer it as extension but it is not standard c++).

So here we get a bit stuck, and most would consider using the usual std::vector which have a variable size.
Unfortunately, you specified "Use arrays" in your question. Erf, back to square one.

Let's think a little bit and remember that arrays can be seen as pointers. In the following image, we define an array arr[5]. Then arr is a pointer to the adress 1000, the first value of your array :

Spoiler alert : You can create a dynamic array with this property.
Ok, so let's define a pointer for our two arrays of odd and even numbers and let's declare their associated size:

```<code>int * odd_array = NULL;
int * even_array = NULL;

int odd_array_size = 0, even_array_size = 0;
</code>```

Now, the idea is to increase the size of the good array when we find an odd or even number and use the C function void* realloc(void* ptr, size_t size) offered by <cstdlib>to increase the size allocated for your array. In your case you probably want to do that as you are looping over your input array. Here is an exemple of what you can have in your case :

```<code>for (int n = 0; n < 10; n++)
{
    if ((input_array[n]) % 2 != 0) // We find an odd number
    {
        odd_array_size++; // Increase the size of the array
        odd_array = (int*)realloc(odd_array, odd_array_size * sizeof(int)); // Reallocate more memory
        odd_array[odd_array_size-1] = input_array[n]; // Add the value in your new allocated memory
    }
    else
    {
        // Same here, but in the case of an even number
        even_array_size++;
        even_array = (int*)realloc(even_array, even_array_size * sizeof(int));
        even_array[even_array_size-1] = input_array[n];
    }
}
</code>```

With this, you get your two arrays odd_array and even_array, filled respectively with the odd and even numbers of your input_array, which both have their associated size odd_array_size and even_array_size

This is basically a C way to do this. You may probably consider smart pointers (in order to be safe with freeing the memory) and, if you were allowed, std::vectors which are the best way to deal with this problem. So don't forget to free your two arrays at the end of your program if you use this.

I hope this will be helpful and clear, don't hesitate to ask me clarifications in comment if needed.

Body:
Write a program which outputs 10 given numbers into two rows, one for odd and one for even numbers. Use arrays.

After declaring an input array for 10 numbers which the user enters, I tried declaring separate arrays for odd and even values which would later be sorted by a for-loop.

I get stuck when I need to assign these values n to odd or even arrays.

int input[10];
int odd[]{};
int even[]{};
int n;

for(n=0;n<10;n++)
{
    if ((input[n])%2==0)
    {
      odd[n] = n;
    }
    else
    {
      even[n] = n;
    }

Body:
As vahancho said in a comment, both odd[] and even[] are static arrays. That means once created you can't change the size of any of them. Moreover, when declaring the array, the size cannot be "dynamic", ie int odd[n]; is only valid when n is a compile time constant (note that some compiler offer it as extension but it is not standard c++).

So here we get a bit stuck, and most would consider using the usual std::vector which have a variable size.
Unfortunately, you specified "Use arrays" in your question. Erf, back to square one.

Let's think a little bit and remember that arrays can be seen as pointers. In the following image, we define an array arr[5]. Then arr is a pointer to the adress 1000, the first value of your array :

Spoiler alert : You can create a dynamic array with this property.
Ok, so let's define a pointer for our two arrays of odd and even numbers and let's declare their associated size:

int * odd_array = NULL;
int * even_array = NULL;

int odd_array_size = 0, even_array_size = 0;

Now, the idea is to increase the size of the good array when we find an odd or even number and use the C function void* realloc(void* ptr, size_t size) offered by <cstdlib>to increase the size allocated for your array. In your case you probably want to do that as you are looping over your input array. Here is an exemple of what you can have in your case :

for (int n = 0; n < 10; n++)
{
    if ((input_array[n]) % 2 != 0) // We find an odd number
    {
        odd_array_size++; // Increase the size of the array
        odd_array = (int*)realloc(odd_array, odd_array_size * sizeof(int)); // Reallocate more memory
        odd_array[odd_array_size-1] = input_array[n]; // Add the value in your new allocated memory
    }
    else
    {
        // Same here, but in the case of an even number
        even_array_size++;
        even_array = (int*)realloc(even_array, even_array_size * sizeof(int));
        even_array[even_array_size-1] = input_array[n];
    }
}

With this, you get your two arrays odd_array and even_array, filled respectively with the odd and even numbers of your input_array, which both have their associated size odd_array_size and even_array_size

This is basically a C way to do this. You may probably consider smart pointers (in order to be safe with freeing the memory) and, if you were allowed, std::vectors which are the best way to deal with this problem. So don't forget to free your two arrays at the end of your program if you use this.

I hope this will be helpful and clear, don't hesitate to ask me clarifications in comment if needed.


问:
how to make a multiline textbox not accept Enter and Backspace
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

```<code>    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }
</code>```

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

答:
Since you are handling the keys in the KeyDown event handler, why not have your KeyPress handler return that all keystrokes are handled?

So just set e.Handled = true no matter what. I believe the backspace and enter would be interpreted as control characters, also.

Body:
I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.

Can anyone help in this regard. That's all I have to do.

One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:

    private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
    {
        // only modifier keys, escape, enter, backspace etc is accepted now
        e.Handled = !char.IsControl(e.KeyChar);
    }

    private void txtResult_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true)
        {
            if (e.KeyCode == Keys.R)
            {
                // do something
            }
            else
            {
                //do something
            }
        }

        if (e.KeyCode == Keys.Escape)
        {
            //do something
        }
    }

With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??


问:
Invalid character code found for in data for codepage ISO8859-1 (12008)
I have created one new window application using progress 4gl language. The scope of this application is load the excel sheet and parse the data. But I am facing some problem while parsing the data.Let me share my query what i tried

```<code>DEFINE VARIABLE cPartData AS LONGCHAR.
DEFINE VARIABLE gc_FileName            AS CHARACTER  NO-UNDO.
DEFINE VARIABLE gl_OKpressed           AS LOGICAL    NO-UNDO INITIAL TRUE.

DO WITH FRAME {&FRAME-NAME}:
    SYSTEM-DIALOG GET-FILE gc_FileName
        TITLE      "Select Excel File ..."
        FILTERS    "Source Files (*.xlsx)"   "*.xlsx"
        MUST-EXIST
        USE-FILENAME
        UPDATE gl_OKpressed.
    IF gl_OKpressed = TRUE THEN
    DO:
        fiLoadOrderFile:SCREEN-VALUE = gc_FileName.
        COPY-LOB FROM FILE gc_FileName TO cPartData .
        RUN DisplayStatus("Raw Data Copy Completed").
    END.
END.

END PROCEDURE.

</code>```

But the issue i am getting is "Invalid character code found in data for codepage ISO8859-1".

I thought the excel file is encrypted but all the data is visible.

Could you please help this case?

答: There is no way this will work. A .xlsx file is not parsable directly in OpenEdge. You need to extract the data. There are various ways of doing that using COM objects, or better .Net in Windows. You could save the data as a .csv and parse that.</p>

Body:
I have created one new window application using progress 4gl language. The scope of this application is load the excel sheet and parse the data. But I am facing some problem while parsing the data.Let me share my query what i tried

DEFINE VARIABLE cPartData AS LONGCHAR.
DEFINE VARIABLE gc_FileName            AS CHARACTER  NO-UNDO.
DEFINE VARIABLE gl_OKpressed           AS LOGICAL    NO-UNDO INITIAL TRUE.

DO WITH FRAME {&FRAME-NAME}:
    SYSTEM-DIALOG GET-FILE gc_FileName
        TITLE      "Select Excel File ..."
        FILTERS    "Source Files (*.xlsx)"   "*.xlsx"
        MUST-EXIST
        USE-FILENAME
        UPDATE gl_OKpressed.
    IF gl_OKpressed = TRUE THEN
    DO:
        fiLoadOrderFile:SCREEN-VALUE = gc_FileName.
        COPY-LOB FROM FILE gc_FileName TO cPartData .
        RUN DisplayStatus("Raw Data Copy Completed").
    END.
END.

END PROCEDURE.

But the issue i am getting is "Invalid character code found in data for codepage ISO8859-1".

I thought the excel file is encrypted but all the data is visible.

Could you please help this case?


问:
JOI validation is not returning all the errors despite setting abort early false
i've been trying to validate my payload via joi schema. But it's not returning the error what I've written in schema rather it's showing only one error. Even if i give payload like name=int only one custom error is showing up despite giving 2nd input aka username a integer value:

{
   "statusCode": 400,

"error": "Bad Request",

"message": "name expecting a string"
  }

rather it should have printed

{
   "statusCode": 400,

"error": "Bad Request",

"message": "name expecting a string"/"username expecting a string"
  }

this is my code:
server.js

```<code>    const server = Hapi.server({
        port: 3000,
        routes: {
            validate: {
                options: {
                    abortEarly: false
                  },
                failAction: async (request, response, err) => {
                    throw Boom.badRequest(err.message);
                },
            },

        },
    });
</code>```

joi-schmea.js

```<code>const NamePayload = Joi.object().keys({
    name: Joi.string().required().error(new Error('name expecting a string')),
    username: Joi.string().required().error(new Error('username expecting a string')),
    age: Joi.integer().required().error(new Error('age expecting a number')),

});
</code>```

routes.js:

```<code>validate: {
        payload: Schema.NamePayload,

      },
</code>```

I want postman to show all the error message not only the first error message. And I also dont wanna use default error message child must be string/int type error that's why I'm using new error. I've read all the stackoverflow article about that error but nothing solved my problem . This is the hapi and joi version im using:

@hapi/joi: ^15.0.3,

@hapi/hapi: ^18.3.1,

答:
For what I understand, each Joi error throws a ValidationError that contains a key details, which is an array of errors, each one, among other things, has your custom error message, and by doing new Error() in your schema you are overriding that key details. So, this is what I suggest you to do:

Replace your schema errors with this:

```<code>Joi.object().keys({
    name: Joi.string().required().error(() => 'name expecting a string'),
    username: Joi.string().required().error(() => 'username expecting a string'),
    age: Joi.number().integer().required().error(() => 'age expecting a number'),
});
</code>```

And then in your failAction concat those messages that are inside err.details:

```<code>failAction: async (request, response, err) => {
    throw Boom.badRequest(err.details.map((error) => error.message).join('/'));
}
</code>```

For this payload:

```<code>{
   "name": 10
}
</code>```

You will get this response:

```<code>{
   "statusCode": 400,
   "error": "Bad Request",
   "message": "name expecting a string/username expecting a string/age expecting a number"
}
</code>```

Body:
i've been trying to validate my payload via joi schema. But it's not returning the error what I've written in schema rather it's showing only one error. Even if i give payload like name=int only one custom error is showing up despite giving 2nd input aka username a integer value:

{
   "statusCode": 400,

"error": "Bad Request",

"message": "name expecting a string"
  }

rather it should have printed

{
   "statusCode": 400,

"error": "Bad Request",

"message": "name expecting a string"/"username expecting a string"
  }

this is my code:
server.js

    const server = Hapi.server({
        port: 3000,
        routes: {
            validate: {
                options: {
                    abortEarly: false
                  },
                failAction: async (request, response, err) => {
                    throw Boom.badRequest(err.message);
                },
            },

        },
    });

joi-schmea.js

const NamePayload = Joi.object().keys({
    name: Joi.string().required().error(new Error('name expecting a string')),
    username: Joi.string().required().error(new Error('username expecting a string')),
    age: Joi.integer().required().error(new Error('age expecting a number')),

});

routes.js:

validate: {
        payload: Schema.NamePayload,

      },

I want postman to show all the error message not only the first error message. And I also dont wanna use default error message child must be string/int type error that's why I'm using new error. I've read all the stackoverflow article about that error but nothing solved my problem . This is the hapi and joi version im using:

@hapi/joi: ^15.0.3,

@hapi/hapi: ^18.3.1,

Body:
For what I understand, each Joi error throws a ValidationError that contains a key details, which is an array of errors, each one, among other things, has your custom error message, and by doing new Error() in your schema you are overriding that key details. So, this is what I suggest you to do:

Replace your schema errors with this:

Joi.object().keys({
    name: Joi.string().required().error(() => 'name expecting a string'),
    username: Joi.string().required().error(() => 'username expecting a string'),
    age: Joi.number().integer().required().error(() => 'age expecting a number'),
});

And then in your failAction concat those messages that are inside err.details:

failAction: async (request, response, err) => {
    throw Boom.badRequest(err.details.map((error) => error.message).join('/'));
}

For this payload:

{
   "name": 10
}

You will get this response:

{
   "statusCode": 400,
   "error": "Bad Request",
   "message": "name expecting a string/username expecting a string/age expecting a number"
}


问:
How in Java script to find the necessary number from three numbers?
I have four numbers 15 30 70 140. and "x", which can get any number, how to say if ()? that if x is equal to 15 30 70 140, then true, if not, then false.</p>

```<code>const x =....;
if(x===?){....}else{....}
</code>```

答:
Use includes:

const nums = [15, 30, 70, 140];
const x = 70;
if (nums.includes(x)) console.log("Yay :)")
else console.log("Noo :(");```
</div>
</div>
</p>

<p>If the numbers are a space-separated string:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const nums = "15 30 70 140".split(" ").map(e => parseInt(e));
const x = 70;
if (nums.includes(x)) console.log("Yay :)")
else console.log("Noo :(");</code>```

Body:
I have four numbers 15 30 70 140. and "x", which can get any number, how to say if ()? that if x is equal to 15 30 70 140, then true, if not, then false.

const x =....;
if(x===?){....}else{....}

Body:
Use includes:

const nums = [15, 30, 70, 140];
const x = 70;
if (nums.includes(x)) console.log("Yay :)")
else console.log("Noo :(");

If the numbers are a space-separated string:

const nums = "15 30 70 140".split(" ").map(e => parseInt(e));
const x = 70;
if (nums.includes(x)) console.log("Yay :)")
else console.log("Noo :(");


问:
How to import template made by webpack into Laravel
I am developing a Laravel project. And I am using a third party HTML template which is using webpack and laravel mix to compile all assets. I need to know is there any way to import that HTML template to Laravel and compile it within the Laravel project. I am new to frontend technologies like webpack/laravel mix. It would be great if anyone can guide me. Thanks</p>

答:
I'm not familiar with Laravel, but since you have NodeJS in your stack, you should be able to incorporate a build step for copying templates into wherever Laravel needs them (I guess /assets/templates?)

Something like this perhaps?

```<code>const fs = require('fs')
webpack(webpackConfig, error => {
  if (error) console.error(error)
  else {
    fs.copyFileSync('generatedTemplate.js', '/assets/templates')
  }
})
</code>```

I can't offer much more advice without knowing your setup. I think utilizing NodeJS is the solution here though.

Body:
I'm not familiar with Laravel, but since you have NodeJS in your stack, you should be able to incorporate a build step for copying templates into wherever Laravel needs them (I guess /assets/templates?)

Something like this perhaps?

const fs = require('fs')
webpack(webpackConfig, error => {
  if (error) console.error(error)
  else {
    fs.copyFileSync('generatedTemplate.js', '/assets/templates')
  }
})

I can't offer much more advice without knowing your setup. I think utilizing NodeJS is the solution here though.


问:
How can I declare a sub package so it doesn't conflict with the parent in the environment?
A local package will mask any other package with the same name in the environment.

Steps to reproduce:

```<code>mkdir pandas
touch pandas/__init__.py
python
>>> from pandas import DataFrame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name DataFrame
</code>```

If I cd into another directory, then I can import, so obviously my package is masking the parent.

I gave an example with pandas.DataFrame to illustrate my point. What I'm really trying to do is to create a hierarchy of modules within the same package. But some of my modules are already installed with pip and if I try to properly package my new modules, ie with the same package name, I loose access to those modules that are already installed in my environment.

I'd like to keep every module in a separate project/git repository.

PS: I come from java

答:
You can use the . notation for local packages, like in the following:

```<code>from .pandas import DataFrame
</code>```

By the way to avoid confusion it's better to avoid to have the same name of well-known packages like numpy, pandas, etc. Otherwise you can do like

```<code>from mycompany.pandas import DataFrame
</code>```

where you have the following package structure:

```<code>mycompany/
__init__.py
pandas/
__init__.py
</code>```

so to avoid the package naming overlapping at the root package level.

If you are using a package structure like

```<code>mycompany/
__init__.py
tests/
__init__.py
</code>```

and you are calling some framework externally, you have two ways:

1) the worst way: manually import the external folder path to the current path:

```<code>import os
import sys
parentPath = os.path.abspath("..")
if parentPath not in sys.path:
    sys.path.insert(0, parentPath)
</code>```

In this example we import the ../ to the current path if it was not imported before.

2) The better way. You use the __init__.py to export the tests/ packages to the outside world:

```<code># tests/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from my_class_A import ClassA
from my_class_B import ClassB
</code>```

so that you will be able to import the class ClassA in the external file as usual:

```<code># main.py
from tests import ClassA
</code>```

given the following structure:

```<code>mycompany/
__init__.py
main.py
tests/
__init__.py
my_class_A.py
my_class_B.py
</code>```

(This just to have an idea, of course you must adapt the imports and path to your use case).

Body:
A local package will mask any other package with the same name in the environment.

Steps to reproduce:

mkdir pandas
touch pandas/__init__.py
python
>>> from pandas import DataFrame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name DataFrame

If I cd into another directory, then I can import, so obviously my package is masking the parent.

I gave an example with pandas.DataFrame to illustrate my point. What I'm really trying to do is to create a hierarchy of modules within the same package. But some of my modules are already installed with pip and if I try to properly package my new modules, ie with the same package name, I loose access to those modules that are already installed in my environment.

I'd like to keep every module in a separate project/git repository.

PS: I come from java

Body:
You can use the . notation for local packages, like in the following:

from .pandas import DataFrame

By the way to avoid confusion it's better to avoid to have the same name of well-known packages like numpy, pandas, etc. Otherwise you can do like

from mycompany.pandas import DataFrame

where you have the following package structure:

mycompany/
__init__.py
pandas/
__init__.py

so to avoid the package naming overlapping at the root package level.

If you are using a package structure like

mycompany/
__init__.py
tests/
__init__.py

and you are calling some framework externally, you have two ways:

1) the worst way: manually import the external folder path to the current path:

import os
import sys
parentPath = os.path.abspath("..")
if parentPath not in sys.path:
    sys.path.insert(0, parentPath)

In this example we import the ../ to the current path if it was not imported before.

2) The better way. You use the __init__.py to export the tests/ packages to the outside world:

# tests/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from my_class_A import ClassA
from my_class_B import ClassB

so that you will be able to import the class ClassA in the external file as usual:

# main.py
from tests import ClassA

given the following structure:

mycompany/
__init__.py
main.py
tests/
__init__.py
my_class_A.py
my_class_B.py

(This just to have an idea, of course you must adapt the imports and path to your use case).


问:
'Invalid URI: The format of the URI could not be determined.' when calling aspx page from web api
I want to call a aspx page from my method so I use Redirect() method as bellow:

```<code>pubic calsss mainController:ApiController
{
    [HttpPost]
    public void postReport()
    {
         Redirect("/WebForm1.aspx");
    }
}
</code>```

but when I use it it shows this Exception :
'Invalid URI: The format of the URI could not be determined.'

my WebForm1.aspx is an internal page.
can some one help me to solve this problem?

Upadate:

my web config:

```<code>public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "withAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "noApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
</code>```

My project structure :

答:
Try this

If you wish to redirect to the folder that is one level higher than the current folder.

```<code>    Redirect("../WebForm1.aspx");
</code>```

If you wish to redirect to the root directory use the tilde (~)

```<code>    Redirect("~/WebForm1.aspx");
</code>```

sample result: http:www.yoururl.co.uk/directory1/webform1.aspx

Body:
I want to call a aspx page from my method so I use Redirect() method as bellow:

pubic calsss mainController:ApiController
{
    [HttpPost]
    public void postReport()
    {
         Redirect("/WebForm1.aspx");
    }
}

but when I use it it shows this Exception :
'Invalid URI: The format of the URI could not be determined.'

my WebForm1.aspx is an internal page.
can some one help me to solve this problem?

Upadate:

my web config:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "withAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "noApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

My project structure :

Body:
Try this

If you wish to redirect to the folder that is one level higher than the current folder.

    Redirect("../WebForm1.aspx");

If you wish to redirect to the root directory use the tilde (~)

    Redirect("~/WebForm1.aspx");

sample result: http:www.yoururl.co.uk/directory1/webform1.aspx


问:
Updates doesn't take affect in django orm, Is there something wrong in my code?
I need to update multiple rows in a url_field in one of my models, each product_id has its own corresponding new values to be loading. What's wrong with my code? No errors are returned.

```<code>idlist= ["",""]
url = ["https://www.sample.com","https://www.sample2.com"]
i = 0

while i < len(item_idlist):
Model.objects.filter(item_id=idlist[i].update(product_url=url[i]))
i += 1
</code>```

I expect that every iterations will update my data inside the model.

答:
Careful with your parentheses. Your update() should be after your filter(). Not inside.

Are you sure about your idlist ? Because you are filtering with an empty string. So you filter() will return nothing, and update nothing.

You can update your data structure like this. Associate an id with a new url into a dictionary.

```<code>idlist_url = {
 1: "https://www.sample.com",
 2: "https://www.sample2.com"
}

for id, new_url in idlist.items():
    Model.objects.filter(item_id=id).update(product_url=new_url)
</code>```

Body:
I need to update multiple rows in a url_field in one of my models, each product_id has its own corresponding new values to be loading. What's wrong with my code? No errors are returned.

idlist= ["",""]
url = ["https://www.sample.com","https://www.sample2.com"]
i = 0

while i < len(item_idlist):
Model.objects.filter(item_id=idlist[i].update(product_url=url[i]))
i += 1

I expect that every iterations will update my data inside the model.

Body:
Careful with your parentheses. Your update() should be after your filter(). Not inside.

Are you sure about your idlist ? Because you are filtering with an empty string. So you filter() will return nothing, and update nothing.

You can update your data structure like this. Associate an id with a new url into a dictionary.

idlist_url = {
 1: "https://www.sample.com",
 2: "https://www.sample2.com"
}

for id, new_url in idlist.items():
    Model.objects.filter(item_id=id).update(product_url=new_url)


问:
How does this log method work in a .NET application?
I am working on a .NET project using C# and I have the following doubt.

I have this method that write some error information into a .log file in a specific directory on my file system:

```<code>private static void writeErrorLog(string error)
{
    string date = DateTime.Now.ToString("yyyyMMdd_HHmmss");
    string currDir = Directory.GetCurrentDirectory();
    System.IO.File.AppendAllText(currDir + "\\FILE\\LOG\\Error_" + date + ".txt", error);
}
</code>```

Ok this writeErrorLog() method will be called into some try catch block of my code, something like this:

```<code>try
{
    currentAttachmentFileData = currentAttachmentFile.OpenBinary();
    currentAttachementModel = new AttachmentModel(currentAttachment, currentAttachmentFileData);
    attachmentsModelList.Add(currentAttachementModel);
}
catch (Exception ex)
{
    //writeLog(2, String.Format("Unable to read the attachment, it may be corrupted {0} - {1}", fileName, ex.Message));
    writeErrorLog("Errore inserimento attachment. Numero protocollo: " + recNumber
                + " Data protocollo: " + recDate
                + " Nome attachment: " +  currentAttachmentFile
                + " INFO: " + ex.ToString() + " | " + ex.Message + " | " + ex.StackTrace);

}
</code>```

It happens in different places of my code.

My doubt is: the file is the same, so it means that it will be added a new line to this file every time that an error occours.

Is it my reasnong correct?

答:
The file name is string date = DateTime.Now.ToString("yyyyMMdd_HHmmss"); so it changes every second.

You should definitely add some abstraction here and hide writeErrorLog behind an interface. Behind the interface you could have your own implementation of writeErrorLog, but as others suggested I would strongly recommend using libs over your custom solution.

More on available libraries:

benchmarking-5-popular-net-logging-libraries

dotnetlogging.com

Body:
I am working on a .NET project using C# and I have the following doubt.

I have this method that write some error information into a .log file in a specific directory on my file system:

private static void writeErrorLog(string error)
{
    string date = DateTime.Now.ToString("yyyyMMdd_HHmmss");
    string currDir = Directory.GetCurrentDirectory();
    System.IO.File.AppendAllText(currDir + "\\FILE\\LOG\\Error_" + date + ".txt", error);
}

Ok this writeErrorLog() method will be called into some try catch block of my code, something like this:

try
{
    currentAttachmentFileData = currentAttachmentFile.OpenBinary();
    currentAttachementModel = new AttachmentModel(currentAttachment, currentAttachmentFileData);
    attachmentsModelList.Add(currentAttachementModel);
}
catch (Exception ex)
{
    //writeLog(2, String.Format("Unable to read the attachment, it may be corrupted {0} - {1}", fileName, ex.Message));
    writeErrorLog("Errore inserimento attachment. Numero protocollo: " + recNumber
                + " Data protocollo: " + recDate
                + " Nome attachment: " +  currentAttachmentFile
                + " INFO: " + ex.ToString() + " | " + ex.Message + " | " + ex.StackTrace);

}

It happens in different places of my code.

My doubt is: the file is the same, so it means that it will be added a new line to this file every time that an error occours.

Is it my reasnong correct?