问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答:
In theory, yes. When developing, there are a lot of things that could go awry, like @Oded mentioned. By having a dedicated webserver run your main site, you avoid the complexity of having duplicated databases, virtual hosts, etc. You could certainly make test.mysite.com publicly available, though.

As a customer, often times, the first thing I do is visit a company's website. If the site is inaccessible, even briefly, it looks unprofessional and I quickly lose interest. You do not want to lose business because you were too cheap to buy one extra computer!

Edit: I see from your comments above that this is indeed a business server. Answer updated.


来源: stackexchange

问:
How to set the value in hashmap key:value pair conditionally?
I'am using grails.
I want to set the values in map conditionally.
For Eg:

```<code>HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }
</code>```

So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".

Output I'am Getting

```<code>mymap:[TITLE: NA]
</code>```

Output I want

```<code>mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]
</code>```

Something like this

Thanks in advance.

答:
Shorter variant:</p>

```<code>HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'am using grails.
I want to set the values in map conditionally.
For Eg:

HashMap<String, String> mymap= new HashMap<String, String>();
    if (author != null){
        mymap['TITLE'] = book.title
    }else{
        mymap['TITLE'] = 'NA'
    }

So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".

Output I'am Getting

mymap:[TITLE: NA]

Output I want

mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]

Something like this

Thanks in advance.

Body:
Shorter variant:

HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )


问:
golang extract unique key, value from a key=value pair string using regex
I have the following go string:

```<code>dbConnStr := "user=someone password=something host=superduperhost sslmode=something"
</code>```

but the k=v pair code may be in any order, for example:

```<code>dbConnStr := "host=superduperhost user=someone password=something"
</code>```

Notice the difference in the key order and also the missing "sslmode" key in the str.

Also, it is possible that instead of whitespace, the individual k,v pairs may be separated by newline too.

Now I want to extract the unique keys and their corresponding values from the given string, using regexp. If it will help, I can give a list of all the possible keys that may come (username, password, host, sslmode), but I would ideally like a regex solution that works with any list of keys and values.

How to do this ? I understand that it may be possible with regexp.FindStringSubmatch but not able to wrap my head around writing the regexp.

答:
Got answer to this from golang nuts group.

```<code>    var rex = regexp.MustCompile("(\\w+)=(\\w+)")

    conn := `user=someone password=something host=superduperhost
sslmode=something`
    data := rex.FindAllStringSubmatch(conn, -1)

    res := make(map[string]string)
    for _, kv := range data {
        k := kv[1]
        v := kv[2]
        res[k] = v
    }
    fmt.Println(res)
</code>```

Golang Playground url: https://play.golang.org/p/xSEX1CAcQE

Body:
I have the following go string:

dbConnStr := "user=someone password=something host=superduperhost sslmode=something"

but the k=v pair code may be in any order, for example:

dbConnStr := "host=superduperhost user=someone password=something"

Notice the difference in the key order and also the missing "sslmode" key in the str.

Also, it is possible that instead of whitespace, the individual k,v pairs may be separated by newline too.

Now I want to extract the unique keys and their corresponding values from the given string, using regexp. If it will help, I can give a list of all the possible keys that may come (username, password, host, sslmode), but I would ideally like a regex solution that works with any list of keys and values.

How to do this ? I understand that it may be possible with regexp.FindStringSubmatch but not able to wrap my head around writing the regexp.

Body:
Got answer to this from golang nuts group.

    var rex = regexp.MustCompile("(\\w+)=(\\w+)")

    conn := `user=someone password=something host=superduperhost
sslmode=something`
    data := rex.FindAllStringSubmatch(conn, -1)

    res := make(map[string]string)
    for _, kv := range data {
        k := kv[1]
        v := kv[2]
        res[k] = v
    }
    fmt.Println(res)

Golang Playground url: https://play.golang.org/p/xSEX1CAcQE

ContentLicense: CC BY-SA 4.0


问:
Does rest_framework coreapi not support PUT / PATCH?
I'm wanting to use the Python Client Library, but having no end of pain getting PUT/PATCH to work. Whenever I try using update / partial_update, the URL param isn't interpolated from the dictionary, and the server returns a 404.

```<code>[06-Jun-2017 12:30:05] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23
</code>```

Which clearly shows that the {cid} param was never replaced with the actual value. Which brings me to the TL/DR version of my question, does CoreAPI not support PUT / PATCH?

The PUT / PATCH options are correctly setup, according to this info:

```<code>GET /api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e90c/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
</code>```

```<code>{
    "url": "http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/",
    "created": "2016-04-16T19:35:02.169898Z",
    "modified": "2017-05-30T17:25:29.768740Z",
    "cid": "2892c424-3a86-16bb-8b60-12a79900e8fb",
    "name": "10.0.0.0/8",
    "comments": "Local Area Network - 10.x",
    "builtin": true
}
</code>```

Now that I've blown most of a morning trying to make this work, I realize that there's no documentation example showing update / partial update.

So I thought I'd try using coreapi-cli instead, but I have the same problem.

```<code>coreapi action networks partial_update --param cid='2892c424-3a86-16bb-8b60-12a79900e8fb' --param comments='this is WAAAY too hard'
<Error: 404 Not Found>
    detail: "Not found."
</code>```

Django's logline shows that the URL param was never substituted from the 'cid' param provided:

```<code>[06-Jun-2017 13:07:01] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23
</code>```

I can use override params to force the URL, and this now updates as anticipated.

```<code>client.action(['networks', 'partial_update'],
          params={'comments': 'this is WAAAY too hard', 'cid': '2892c424-3a86-16bb-8b60-12a79900e8fb'},
          overrides={'url': 'http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/'},
          )
</code>```

But that feels haaacky, and should be utterly unnecessary. So...

Is this a bug?

Have I gotten the function signature wrong?

Does CoreAPI not support PUT / PATCH methods?

Edit

Here's the viewset

```<code>class LCModelViewSet(mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.ListModelMixin,
                     GenericViewSet):
    """
    Base ModelViewSet
    """
    lookup_field = 'cid'

class NetworksViewSet(LCModelViewSet):
    queryset = Networks.objects.all()
    serializer_class = NetworksSerializer
    filter_class = NetworksFilter
</code>```

and the Router

```<code>router = DefaultRouter()
router.register(r'accounts/networks', av.NetworksViewSet, base_name='api-networks')
</code>```

and the output of router.routes

```<code>[Route(url='^{prefix}{trailing_slash}$', mapping={'get': 'list', 'post': 'create'}, name='{basename}-list', initkwargs={'suffix': 'List'}),
 DynamicListRoute(url='^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}),
 Route(url='^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}, name='{basename}-detail', initkwargs={'suffix': 'Instance'}),
 DynamicDetailRoute(url='^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={})]
</code>```

Edit #2

At hurturk's suggestion, I reduced everything to defaults - views.ModelViewset and serializers.ModelSerializer, and put the lookup_field on the NetworksViewSet. Still same problem.

Then I removed the custom lookup field and just tried using the default id field (cid is not the PK), and VOILA, PUT/PATCH then worked - URL generated correctly! So, I wondered if for some reason it's a UUID-related issue.

Since name is a unique field, I set lookup_field = name. The same behavior as UUID. GET/POST methods work. PUT/PATCH don't "PATCH /api/accounts/networks/%7Bname%7D/ HTTP/1.1" 404 23.

So it seems to come to this, that when the lookup_field is the PK, then PUT/PATCH url is generated correctly. When lookup_field is some other field, then the URL lookup_field placeholder is never interpolated.

I don't know what to do. CID is a must-have requirement...

答:
Well, I found the issue. :-)  cid must be set to readonly, and then the URL for PUT/PATCH is correctly formed.

Why must a lookup_field be readonly? If it's incorrect and unworkable to have a lookup_field be writable, an error message would be very helpful, instead of the current behavior.

Edit

Well thank you, @hurkurk! I didn't notice your PR! That does fix my problem, at least when the cid doesn't need to be edited. It really would be great to have the path param specified separately from the request data, so that the lookup_field value could be changed on PUT/PATCH. But that's another discussion.

Body:
I'm wanting to use the Python Client Library, but having no end of pain getting PUT/PATCH to work. Whenever I try using update / partial_update, the URL param isn't interpolated from the dictionary, and the server returns a 404.

[06-Jun-2017 12:30:05] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23

Which clearly shows that the {cid} param was never replaced with the actual value. Which brings me to the TL/DR version of my question, does CoreAPI not support PUT / PATCH?

The PUT / PATCH options are correctly setup, according to this info:

GET /api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e90c/
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "url": "http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/",
    "created": "2016-04-16T19:35:02.169898Z",
    "modified": "2017-05-30T17:25:29.768740Z",
    "cid": "2892c424-3a86-16bb-8b60-12a79900e8fb",
    "name": "10.0.0.0/8",
    "comments": "Local Area Network - 10.x",
    "builtin": true
}

Now that I've blown most of a morning trying to make this work, I realize that there's no documentation example showing update / partial update.

So I thought I'd try using coreapi-cli instead, but I have the same problem.

coreapi action networks partial_update --param cid='2892c424-3a86-16bb-8b60-12a79900e8fb' --param comments='this is WAAAY too hard'
<Error: 404 Not Found>
    detail: "Not found."

Django's logline shows that the URL param was never substituted from the 'cid' param provided:

[06-Jun-2017 13:07:01] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23

I can use override params to force the URL, and this now updates as anticipated.

client.action(['networks', 'partial_update'],
          params={'comments': 'this is WAAAY too hard', 'cid': '2892c424-3a86-16bb-8b60-12a79900e8fb'},
          overrides={'url': 'http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/'},
          )

But that feels haaacky, and should be utterly unnecessary. So...

Is this a bug?

Have I gotten the function signature wrong?

Does CoreAPI not support PUT / PATCH methods?

Edit

Here's the viewset

class LCModelViewSet(mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.ListModelMixin,
                     GenericViewSet):
    """
    Base ModelViewSet
    """
    lookup_field = 'cid'

class NetworksViewSet(LCModelViewSet):
    queryset = Networks.objects.all()
    serializer_class = NetworksSerializer
    filter_class = NetworksFilter

and the Router

router = DefaultRouter()
router.register(r'accounts/networks', av.NetworksViewSet, base_name='api-networks')

and the output of router.routes

[Route(url='^{prefix}{trailing_slash}$', mapping={'get': 'list', 'post': 'create'}, name='{basename}-list', initkwargs={'suffix': 'List'}),
 DynamicListRoute(url='^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={}),
 Route(url='^{prefix}/{lookup}{trailing_slash}$', mapping={'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}, name='{basename}-detail', initkwargs={'suffix': 'Instance'}),
 DynamicDetailRoute(url='^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={})]

Edit #2

At hurturk's suggestion, I reduced everything to defaults - views.ModelViewset and serializers.ModelSerializer, and put the lookup_field on the NetworksViewSet. Still same problem.

Then I removed the custom lookup field and just tried using the default id field (cid is not the PK), and VOILA, PUT/PATCH then worked - URL generated correctly! So, I wondered if for some reason it's a UUID-related issue.

Since name is a unique field, I set lookup_field = name. The same behavior as UUID. GET/POST methods work. PUT/PATCH don't "PATCH /api/accounts/networks/%7Bname%7D/ HTTP/1.1" 404 23.

So it seems to come to this, that when the lookup_field is the PK, then PUT/PATCH url is generated correctly. When lookup_field is some other field, then the URL lookup_field placeholder is never interpolated.

I don't know what to do. CID is a must-have requirement...


问:
How can I compute simple addition on multiple .xyz files?
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3
```

<p>and the list:</p>

<pre class="lang-none prettyprint-override"><code>(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1
</code>```

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4
```

<p>Currently my is giving me the error:</p>

<pre class="lang-none prettyprint-override"><code>TypeError: float() argument must be a string or a number
</code>```

and my code is:

```<code>def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()
</code>```

答:
In your function:

```<code>with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
    for line1 in myfile_1.readlines():
        parts1 = line1.split('\n')
    for line2 in myfile_2.readlines():
        parts2 = line2.split('\n')
</code>```

You need to split your lines by whitespace, as it's only split on new line characters (which .readlines() already does).

What your code does: parts1 = "1 1 1"

What you want it to do: parts1 = ["1", "1", "1"]

Split line1 and line2 with .split() to split on all whitespace instead.

Edit: You'll also need to indent the portion of writing to the output file to be inside the loop, since parts1 and parts2 are overwritten each time. Try unifying all your code in a manner similar to this:

```<code>with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2, open(outfile, 'w') as outputfile:
    for line1, line2 in zip(myfile_1.readlines(), myfile_2.readlines()):
        parts1 = line1.split()
        parts2 = line2.split()
        totalenergy = []
        for part1, part2 in zip(parts1, parts2):
            totalenergy.append(float(part1) + float(part2))
        outputfile.write(str(totalenergy) + '\n')
</code>```

Body:
I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3

and the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4

Currently my is giving me the error:

TypeError: float() argument must be a string or a number

and my code is:

def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()

Body:
In your function:

with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
    for line1 in myfile_1.readlines():
        parts1 = line1.split('\n')
    for line2 in myfile_2.readlines():
        parts2 = line2.split('\n')

You need to split your lines by whitespace, as it's only split on new line characters (which .readlines() already does).

What your code does: parts1 = "1 1 1"

What you want it to do: parts1 = ["1", "1", "1"]

Split line1 and line2 with .split() to split on all whitespace instead.

Edit: You'll also need to indent the portion of writing to the output file to be inside the loop, since parts1 and parts2 are overwritten each time. Try unifying all your code in a manner similar to this:

with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2, open(outfile, 'w') as outputfile:
    for line1, line2 in zip(myfile_1.readlines(), myfile_2.readlines()):
        parts1 = line1.split()
        parts2 = line2.split()
        totalenergy = []
        for part1, part2 in zip(parts1, parts2):
            totalenergy.append(float(part1) + float(part2))
        outputfile.write(str(totalenergy) + '\n')


问:
Disabling UAC with Powershell
I'm trying to disable UAC (i.e. set to the minimum level) using Powershell. So I'm running:

```<code>Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0
</code>```

I've also tried this with -Force added on the end.

This code has the intended effect of setting UAC to minimum but also the undesired effect of preventing built-in Windows applications (including Edge) from running, returning an error that the application can't be run using the built-in administrator account (despite the fact that it's being run with a user account that simply has UAC disabled).

So if anyone has some insight as to why this is happening and how to resolve it, that would be ideal. Failing that, if there's an alternative Powershell command I can run to disable UAC then that could also be worth a shot.

答:
Looks like this did the trick:

```<code>Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0
</code>```

Edge still running after reboot and annoying UAC prompts gone, so think that's a win.

Title: Disabling UAC with Powershell

Body:
I'm trying to disable UAC (i.e. set to the minimum level) using Powershell. So I'm running:

Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0

I've also tried this with -Force added on the end.

This code has the intended effect of setting UAC to minimum but also the undesired effect of preventing built-in Windows applications (including Edge) from running, returning an error that the application can't be run using the built-in administrator account (despite the fact that it's being run with a user account that simply has UAC disabled).

So if anyone has some insight as to why this is happening and how to resolve it, that would be ideal. Failing that, if there's an alternative Powershell command I can run to disable UAC then that could also be worth a shot.

Body:
Looks like this did the trick:

Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System -Name ConsentPromptBehaviorAdmin -Value 0

Edge still running after reboot and annoying UAC prompts gone, so think that's a win.


问:
To fault or not to fault
I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.

One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:

ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)

GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found

The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.

What do you think?

答:
I believe it is good practice to separate error handling and fault handling. Any error case should be dealt by your program - fault handling is reserved for exceptional conditions. As a guide to the separation of the two I found it useful when considering such cases to remember that there are only three types of error (when handling data and messages) and only one type of fault.
The error types are related to different types of validation:

Message validation - you can determine from the message contents that the data is valid or invalid.

Example: content that is intended to be a date of birth - you can tell from the data whether it is valid or not.

Context validation - you can only determine that content is invalid by reference to the message
combined with the system state.

Example: a valid date of joining a company is earlier than that persons date of birth.

Lies to the system - you can only determine that a message was in error when a later message
throws up an anomaly.

Example: Valid date of birth stored and inspection of the person's birth certificate shows this to be incorrect. Correction of lies to the system generally require action outside of the system, for instance invoking legal or disciplinary remedies.

Your system MUST deal with all classes of error - though in case three this may be limited to issuing an alert.

Faults (exceptions) by contrast only have one cause - data corruption (which includes data truncation).  Example: validation parameters are not passed.

Here the appropriate mechanism is fault or exception handling - basically handing off the problem to some other part of the system that is capable of dealing with it (which is why there should be an ultimate destination for unhandled faults).

ContentLicense: CC BY-SA 2.5

Title: To fault or not to fault


问:
New Tab does not open the new url in Firefox using selenium
The part of the code which opens a new tab and opens a url in that new tab does not work. It opens the new tab but opens the new url in the previous tab itself. Can anyone help?    </p>

```<code>public class PractiseSession1
{
public static void main(String[] args)

{
    // TODO Auto-generated method stub
    String URL="http://www.google.com";

    System.setProperty("webdriver.gecko.driver", "D:\\Sourav Mukherjee\\BP-Oyster\\S2\\Selenium Server\\geckodriver-v0.16.1-win64\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);

    //Open a url in a new tab
    driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL+ "t");
    driver.get("http://facebook.com/");

}
}
</code>```

答:
Here is the Answer to your Question:

To open an URL then again to open a second URL in another tab you can use JavascriptExecutor. Here is your own code which opens http://www.google.com in one tab and next opens http://facebook.com/ in another tab:

```<code>    String URL="http://www.google.com";
    System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);
    ((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");
</code>```

Let me know if this Answers your Question.

Body:
The part of the code which opens a new tab and opens a url in that new tab does not work. It opens the new tab but opens the new url in the previous tab itself. Can anyone help?

public class PractiseSession1
{
public static void main(String[] args)

{
    // TODO Auto-generated method stub
    String URL="http://www.google.com";

    System.setProperty("webdriver.gecko.driver", "D:\\Sourav Mukherjee\\BP-Oyster\\S2\\Selenium Server\\geckodriver-v0.16.1-win64\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);

    //Open a url in a new tab
    driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL+ "t");
    driver.get("http://facebook.com/");

}
}

Body:
Here is the Answer to your Question:

To open an URL then again to open a second URL in another tab you can use JavascriptExecutor. Here is your own code which opens http://www.google.com in one tab and next opens http://facebook.com/ in another tab:

    String URL="http://www.google.com";
    System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);
    ((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");

Let me know if this Answers your Question.


问:
IsGenerator implementation
I previously relied on the following definition of how to detect a generator:

```<code>function isGenerator(func) {
    return func instanceof Function && func.constructor.name === 'GeneratorFunction';
}
</code>```

Since then however I came across various other verifications, including checks for next and throw functions on the prototype.

Is there a way to implement isGenerator function to be considered comprehensive within the realm of NodeJS 0.10 - 5.x?

The application in which I intend to use is to pick up any generator (or even iterator), and wrap it up into a promise that would make use of functions next and throw.

For that I'm using a modified example from here:

```<code>/////////////////////////////////
// Generator-to-Promise adapter;
function asyncAdapter(generator) {
    return function () {
        var g = generator.apply(this, arguments);

        function handle(result) {
            if (result.done) {
                return Promise.resolve(result.value);
            }
            return Promise.resolve(result.value)
                .then(function (res) {
                    return handle(g.next(res));
                }, function (err) {
                    return handle(g.throw(err));
                });
        }

        return handle(g.next());
    }
}
</code>```

答:
ES 6 says

9.2.6 GeneratorFunctionCreate (kind, ParameterList, Body, Scope, Strict)

The abstract operation GeneratorFunctionCreate requires the arguments: kind which is one of (Normal, Method), a parameter list production specified by ParameterList, a body production specified by Body, a Lexical Environment specified by Scope, and a Boolean flag Strict.

GeneratorFunctionCreate performs the following steps:

Let functionPrototype be the intrinsic object %Generator%.

Let F be FunctionAllocate(functionPrototype, Strict, "generator").

Return FunctionInitialize(F, kind, ParameterList, Body, Scope).

so you could get close by checking that the prototype
is that appropriate for a generator.  Object.getPrototypeOf lets us test whether the value of functionPrototype is the builtin %Generator% though proxy objects can control the result of Object.getPrototypeOf.  Treating proxies of generators as generators might be a good thing.

```<code>function isGenerator(functionThatMightBeGenerator) {
  function *nullGenerator() {}
  return (functionThatMightBeGenerator
          &&  Object.getPrototypeOf(functionThatMightBeGenerator)
          === Object.getPrototypeOf(nullGenerator));
}
</code>```

If you're concerned about distinguishing between proxies of generators and generators, you might look at 14.5.14#6.g.i.  That requires that class declaration forbids generators as super types so provides a direct check whether the FunctionKind internal slot is "generator".

This is probably overkill, but something like

```<code>function isGeneratorAndProbablyNotProxyThereof(functionThatMightBeGenerator) {
  function *nullGenerator() {}
  if (!functionThatMightBeGenerator
      || (Object.getPrototypeOf(functionThatMightBeGenerator)
          !== Object.getPrototypeOf(nullGenerator))) {
    return false;
  }
  function defineAndThrowawaySubClass(superType) {
    class C extends superType {}
  }
  let isGenerator = false;
  try {
    defineAndThrowawaySubClass(functionThatMightBeGenerator);
  } catch (e) {
    isGenerator = e instanceof TypeError;
  }
  return isGenerator;
}
</code>```

should do it though a sufficiently motivated proxy writer could probably spoof this too.

Title: IsGenerator implementation

Body:
I previously relied on the following definition of how to detect a generator:

function isGenerator(func) {
    return func instanceof Function && func.constructor.name === 'GeneratorFunction';
}

Since then however I came across various other verifications, including checks for next and throw functions on the prototype.

Is there a way to implement isGenerator function to be considered comprehensive within the realm of NodeJS 0.10 - 5.x?

The application in which I intend to use is to pick up any generator (or even iterator), and wrap it up into a promise that would make use of functions next and throw.

For that I'm using a modified example from here:

/////////////////////////////////
// Generator-to-Promise adapter;
function asyncAdapter(generator) {
    return function () {
        var g = generator.apply(this, arguments);

        function handle(result) {
            if (result.done) {
                return Promise.resolve(result.value);
            }
            return Promise.resolve(result.value)
                .then(function (res) {
                    return handle(g.next(res));
                }, function (err) {
                    return handle(g.throw(err));
                });
        }

        return handle(g.next());
    }
}

Body:
ES 6 says

9.2.6 GeneratorFunctionCreate (kind, ParameterList, Body, Scope, Strict)

The abstract operation GeneratorFunctionCreate requires the arguments: kind which is one of (Normal, Method), a parameter list production specified by ParameterList, a body production specified by Body, a Lexical Environment specified by Scope, and a Boolean flag Strict.

GeneratorFunctionCreate performs the following steps:

Let functionPrototype be the intrinsic object %Generator%.

Let F be FunctionAllocate(functionPrototype, Strict, "generator").

Return FunctionInitialize(F, kind, ParameterList, Body, Scope).

so you could get close by checking that the prototype
is that appropriate for a generator.  Object.getPrototypeOf lets us test whether the value of functionPrototype is the builtin %Generator% though proxy objects can control the result of Object.getPrototypeOf.  Treating proxies of generators as generators might be a good thing.

function isGenerator(functionThatMightBeGenerator) {
  function *nullGenerator() {}
  return (functionThatMightBeGenerator
          &&  Object.getPrototypeOf(functionThatMightBeGenerator)
          === Object.getPrototypeOf(nullGenerator));
}

If you're concerned about distinguishing between proxies of generators and generators, you might look at 14.5.14#6.g.i.  That requires that class declaration forbids generators as super types so provides a direct check whether the FunctionKind internal slot is "generator".

This is probably overkill, but something like

function isGeneratorAndProbablyNotProxyThereof(functionThatMightBeGenerator) {
  function *nullGenerator() {}
  if (!functionThatMightBeGenerator
      || (Object.getPrototypeOf(functionThatMightBeGenerator)
          !== Object.getPrototypeOf(nullGenerator))) {
    return false;
  }
  function defineAndThrowawaySubClass(superType) {
    class C extends superType {}
  }
  let isGenerator = false;
  try {
    defineAndThrowawaySubClass(functionThatMightBeGenerator);
  } catch (e) {
    isGenerator = e instanceof TypeError;
  }
  return isGenerator;
}

should do it though a sufficiently motivated proxy writer could probably spoof this too.


问:
Why does a call to `fn pop(&mut self) -> Result<T, &str>` continue to borrow my data structure?
I am developing some basic data structures to learn the syntax and Rust in general. Here is what I came up with for a stack:

```<code>#[allow(dead_code)]
mod stack {
    pub struct Stack<T> {
        data: Vec<T>,
    }

    impl<T> Stack<T> {
        pub fn new() -> Stack<T> {
            return Stack { data: Vec::new() };
        }

        pub fn pop(&mut self) -> Result<T, &str> {
            let len: usize = self.data.len();

            if len > 0 {
                let idx_to_rmv: usize = len - 1;
                let last: T = self.data.remove(idx_to_rmv);
                return Result::Ok(last);
            } else {
                return Result::Err("Empty stack");
            }
        }

        pub fn push(&mut self, elem: T) {
            self.data.push(elem);
        }

        pub fn is_empty(&self) -> bool {
            return self.data.len() == 0;
        }
    }
}

mod stack_tests {
    use super::stack::Stack;

    #[test]
    fn basics() {
        let mut s: Stack<i16> = Stack::new();

        s.push(16);
        s.push(27);

        let pop_result = s.pop().expect("");

        assert_eq!(s.pop().expect("Empty stack"), 27);
        assert_eq!(s.pop().expect("Empty stack"), 16);

        let pop_empty_result = s.pop();

        match pop_empty_result {
            Ok(_) => panic!("Should have had no result"),
            Err(_) => {
                println!("Empty stack");
            }
        }

        if s.is_empty() {
            println!("O");
        }
    }
}
</code>```

I get this interesting error:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:58:12
   |
49 |         let pop_empty_result = s.pop();
   |                                - mutable borrow occurs here
...
58 |         if s.is_empty() {
   |            ^ immutable borrow occurs here
...
61 |     }
   |     - mutable borrow ends here
```

Why can't I just call pop on my mutable struct?

Why does pop borrow the value? If I add a .expect() after it, it is ok, it doesn't trigger that error. I know that is_empty takes an immutable reference, if I switch it to mutable I just get a second mutable borrow.

答:
Your pop function is declared as:

```<code>pub fn pop(&mut self) -> Result<T, &str>
</code>```

Due to lifetime elision, this expands to

```<code>pub fn pop<'a>(&'a mut self) -> Result<T, &'a str>
</code>```

This says that the Result::Err variant is a string that lives as long as the stack you are calling it on. Since the input and output lifetimes are the same, the returned value might be pointing somewhere into the Stack data structure so the returned value must continue to hold the borrow.

If I add a .expect() after it, it is ok, it doesn't trigger that error.

That's because expect consumes the Result, discarding the Err variant without ever putting it into a variable binding. Since that's never stored, the borrow cannot be saved anywhere and it is released.

To solve the problem, you need to have distinct lifetimes between the input reference and output reference. Since you are using a string literal, the easiest solution is to denote that using the 'static lifetime:

```<code>pub fn pop(&mut self) -> Result<T, &'static str>
</code>```

Extra notes:

Don't call return explicitly at the end of the block / method: return Result::Ok(last) => Result::Ok(last).

Result, Result::Ok, and Result::Err are all imported via the prelude, so you don't need to qualify them: Result::Ok(last) => Ok(last).

There's no need to specify types in many cases let len: usize = self.data.len() => let len = self.data.len().

Body:
I am developing some basic data structures to learn the syntax and Rust in general. Here is what I came up with for a stack:

#[allow(dead_code)]
mod stack {
    pub struct Stack<T> {
        data: Vec<T>,
    }

    impl<T> Stack<T> {
        pub fn new() -> Stack<T> {
            return Stack { data: Vec::new() };
        }

        pub fn pop(&mut self) -> Result<T, &str> {
            let len: usize = self.data.len();

            if len > 0 {
                let idx_to_rmv: usize = len - 1;
                let last: T = self.data.remove(idx_to_rmv);
                return Result::Ok(last);
            } else {
                return Result::Err("Empty stack");
            }
        }

        pub fn push(&mut self, elem: T) {
            self.data.push(elem);
        }

        pub fn is_empty(&self) -> bool {
            return self.data.len() == 0;
        }
    }
}

mod stack_tests {
    use super::stack::Stack;

    #[test]
    fn basics() {
        let mut s: Stack<i16> = Stack::new();

        s.push(16);
        s.push(27);

        let pop_result = s.pop().expect("");

        assert_eq!(s.pop().expect("Empty stack"), 27);
        assert_eq!(s.pop().expect("Empty stack"), 16);

        let pop_empty_result = s.pop();

        match pop_empty_result {
            Ok(_) => panic!("Should have had no result"),
            Err(_) => {
                println!("Empty stack");
            }
        }

        if s.is_empty() {
            println!("O");
        }
    }
}

I get this interesting error:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> src/main.rs:58:12
   |
49 |         let pop_empty_result = s.pop();
   |                                - mutable borrow occurs here
...
58 |         if s.is_empty() {
   |            ^ immutable borrow occurs here
...
61 |     }
   |     - mutable borrow ends here

Why can't I just call pop on my mutable struct?

Why does pop borrow the value? If I add a .expect() after it, it is ok, it doesn't trigger that error. I know that is_empty takes an immutable reference, if I switch it to mutable I just get a second mutable borrow.

Body:
Your pop function is declared as:

pub fn pop(&mut self) -> Result<T, &str>

Due to lifetime elision, this expands to

pub fn pop<'a>(&'a mut self) -> Result<T, &'a str>

This says that the Result::Err variant is a string that lives as long as the stack you are calling it on. Since the input and output lifetimes are the same, the returned value might be pointing somewhere into the Stack data structure so the returned value must continue to hold the borrow.

If I add a .expect() after it, it is ok, it doesn't trigger that error.

That's because expect consumes the Result, discarding the Err variant without ever putting it into a variable binding. Since that's never stored, the borrow cannot be saved anywhere and it is released.

To solve the problem, you need to have distinct lifetimes between the input reference and output reference. Since you are using a string literal, the easiest solution is to denote that using the 'static lifetime:

pub fn pop(&mut self) -> Result<T, &'static str>

Extra notes:

Don't call return explicitly at the end of the block / method: return Result::Ok(last) => Result::Ok(last).

Result, Result::Ok, and Result::Err are all imported via the prelude, so you don't need to qualify them: Result::Ok(last) => Ok(last).

There's no need to specify types in many cases let len: usize = self.data.len() => let len = self.data.len().


问:
How to change the opacity of background without changing the content of it?
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>

      </div>
    </div>
  </div>
</section></code>```

答:
You can use the ::before´-pseudo-element.

.about-section {
  position:relative; /* Notice this */
  height: 100%;
  padding-top: 50px;
  text-align: center;
}

.about-section::before {
  content:'';
  position:absolute;
  width:100%;
  height:100%;
  left:0px;
  top:0px;
  background: #000; /* change to whatever you want */
  opacity:0.3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>
      </div>
    </div>
  </div>
</section></code>```

Body:
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}

About Us

Body:
You can use the ::before´-pseudo-element.

.about-section {
  position:relative; /* Notice this */
  height: 100%;
  padding-top: 50px;
  text-align: center;
}

.about-section::before {
  content:'';
  position:absolute;
  width:100%;
  height:100%;
  left:0px;
  top:0px;
  background: #000; /* change to whatever you want */
  opacity:0.3;
}

<section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>
      </div>
    </div>
  </div>
</section>


问:
How do I encode URI parameter values?
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

http://google.com/resource?key=value1 & value2

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

答: I think that the URI class is the one that you are looking for.</p>

OwnerDisplayName: Gili

Title: How do I encode URI parameter values?

LastEditorDisplayName: Gili

OwnerDisplayName: Glenn


问:
wpf class library with resource dictionary
Is it possible to have a resource dictionary in a WPF class library assembly (.dll)? I ask this because I have an "Application WPF" assembly (.exe), if I try to turn the type of the assembly to "WPF Class Library" I get the error:

Impossible to specify the element ApplicationDefinition in the project file of the Library

How can I make it work?

答: You get that error because one of your XAML files has a Build Action set to ApplicationDefinition. Usually, that is App.xaml. Remove that file or change it's Build Action from Properties Window to Page to stop getting that error.


问:
Create dynamic overlapping divs which will change height based on inner content
I want to create a structure in which there is a background container which will contain some image and will have some min-height. On top of that container there will be another container which will have some text content in it. Now if the text content increases, my parent container's height need to get increased.

I've implemented this using position:relative and absolute properties of css. The content div being absolute doesn't allow the parent div's height to get increased once the content increases.

Can I get some solutions for this. I don't want the change the existing implementation and need some fix in this one only.

I've created a dummy fiddle for this:

Thanks for helping..!!

.parent{
          position:relative;
          min-height:300px;
          border:1px solid;
}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div></code>```

https://jsfiddle.net/arpagrawal/kd144czz/1/

答:
there are a few solution to this

use background-image and don't use position absolute . see snippet below

.parent {
  position: relative;
  min-height: 300px;
  border: 1px solid;
  background-image: url('https://via.placeholder.com/350x150');
  background-repeat: no-repeat;
  background-size: cover;
}

.child {
  width: 200px;
  height: auto;
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div></code>```

use jQuery to give the parent same height as child and use img tag

$(".parent").height($(".child").height())```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent{
          position:relative;
          min-height:200px;
          border:1px solid;
}
.parent img {
 width:100%;
 height:100%;

}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
     top:0;
}</code>```

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

```

Body:
I want to create a structure in which there is a background container which will contain some image and will have some min-height. On top of that container there will be another container which will have some text content in it. Now if the text content increases, my parent container's height need to get increased.

I've implemented this using position:relative and absolute properties of css. The content div being absolute doesn't allow the parent div's height to get increased once the content increases.

Can I get some solutions for this. I don't want the change the existing implementation and need some fix in this one only.

I've created a dummy fiddle for this:

Thanks for helping..!!

.parent{
          position:relative;
          min-height:300px;
          border:1px solid;
}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
}

        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

https://jsfiddle.net/arpagrawal/kd144czz/1/

Body:
there are a few solution to this

use background-image and don't use position absolute . see snippet below

.parent {
  position: relative;
  min-height: 300px;
  border: 1px solid;
  background-image: url('https://via.placeholder.com/350x150');
  background-repeat: no-repeat;
  background-size: cover;
}

.child {
  width: 200px;
  height: auto;
  border: 1px solid;
}

<div class="parent">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div>

use jQuery to give the parent same height as child and use img tag

$(".parent").height($(".child").height())

.parent{
          position:relative;
          min-height:200px;
          border:1px solid;
}
.parent img {
 width:100%;
 height:100%;

}
.child{
          position:absolute;
          width:200px;
          height:auto;
          border:1px solid;
     top:0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<img src="http://via.placeholder.com/350x150">
    <div class="child">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

    </div>
</div>


问:
JMS Durable subscription. Subscriber do not receive messages
Learning durable subscription. I tweaked the example given here. I have written two programs. In one I create topic and send message with PERSISTENCE mode. In other program I create durable subscribers for same topic and try to receive.

I run first program. It finishes successfully. Then I run second(consumer) program. But there it does not get any message. receive() message remains blocked.

What am I missing?

Main part of producer program is

```<code>ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
try{
    con = connectionFactory.createConnection();
    con.setClientID("DurabilityTest");
    con.start();
    session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic  myFirstTopic =  session.createTopic("myFirstTopic");
    MessageProducer producer = session.createProducer(myFirstTopic);
    // Registering consumers. But not calling receive on them
    MessageConsumer  consumer1 = session.createDurableSubscriber(myFirstDurableTopic, "consumer1", "", false);
    MessageConsumer  consumer2 = session.createDurableSubscriber(myFirstDurableTopic,"consumer2", "", false);
    TextMessage txtMsg = session.createTextMessage("Namaskar mitranno2!!");
    producer.send(myFirstTopic, txtMsg, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE+10000);
}catch(JMSException e){
    e.printStackTrace();
}
</code>```

Main part of consumer program is

```<code>ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
try{
    con = connectionFactory.createConnection();
    con.setClientID("DurabilityTest");
    con.start();
    session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic  myFirstTopic =  session.createTopic("myFirstTopic");
    MessageConsumer  consumer1 = session.createDurableSubscriber(myFirstTopic, "consumer1", "", false);
    processMessage(consumer1,consumer1.receive());
    MessageConsumer  consumer2 = session.createDurableSubscriber(myFirstTopic,"consumer2", "", false);
    processMessage(consumer2,consumer2.receive());
}catch(JMSException e){
    e.printStackTrace();
}
</code>```

答:
A durable Topic subscription only starts to retain messages after it has been created.  So if you send messages to the Topic and there's no durable topic subscriptions registered on the broker those message are discarded regardless of the persistence mode of the message.

If you redo your testing and first create a durable topic subscription and then close the consumer you can send persistent messages to the Topic and then later when you run the durable consumer test again it will get the message sent while it was offline.

It's tricky to know what exactly is going on in your application but the use of a VM broker could be at play here, there's no certainty given the code given that each of these two bits producer / consumer aren't creating their own instance of a VM broker, are they being run in the same VM?

Why don't you stand up a broker and connect to it using your client programs?

Body:
Learning durable subscription. I tweaked the example given here. I have written two programs. In one I create topic and send message with PERSISTENCE mode. In other program I create durable subscribers for same topic and try to receive.

I run first program. It finishes successfully. Then I run second(consumer) program. But there it does not get any message. receive() message remains blocked.

What am I missing?

Main part of producer program is

ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
try{
    con = connectionFactory.createConnection();
    con.setClientID("DurabilityTest");
    con.start();
    session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic  myFirstTopic =  session.createTopic("myFirstTopic");
    MessageProducer producer = session.createProducer(myFirstTopic);
    // Registering consumers. But not calling receive on them
    MessageConsumer  consumer1 = session.createDurableSubscriber(myFirstDurableTopic, "consumer1", "", false);
    MessageConsumer  consumer2 = session.createDurableSubscriber(myFirstDurableTopic,"consumer2", "", false);
    TextMessage txtMsg = session.createTextMessage("Namaskar mitranno2!!");
    producer.send(myFirstTopic, txtMsg, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE+10000);
}catch(JMSException e){
    e.printStackTrace();
}

Main part of consumer program is

ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
try{
    con = connectionFactory.createConnection();
    con.setClientID("DurabilityTest");
    con.start();
    session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic  myFirstTopic =  session.createTopic("myFirstTopic");
    MessageConsumer  consumer1 = session.createDurableSubscriber(myFirstTopic, "consumer1", "", false);
    processMessage(consumer1,consumer1.receive());
    MessageConsumer  consumer2 = session.createDurableSubscriber(myFirstTopic,"consumer2", "", false);
    processMessage(consumer2,consumer2.receive());
}catch(JMSException e){
    e.printStackTrace();
}


问:
Intersection and union of ArrayLists in Java
Are there any methods to do so? I was looking but couldn't find any.

Another question: I need these methods so I can filter files.
Some are AND filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

答:
First, I am copying all values of arrays into a single array then I am removing duplicates values into the array. Line 12, explaining if same number occur more than time then put some extra garbage value into "j" position. At the end, traverse from start-end and check if same garbage value occur then discard.</p>

```<code>public class Union {
public static void main(String[] args){

    int arr1[]={1,3,3,2,4,2,3,3,5,2,1,99};
    int arr2[]={1,3,2,1,3,2,4,6,3,4};
    int arr3[]=new int[arr1.length+arr2.length];

    for(int i=0;i<arr1.length;i++)
        arr3[i]=arr1[i];

    for(int i=0;i<arr2.length;i++)
        arr3[arr1.length+i]=arr2[i];
    System.out.println(Arrays.toString(arr3));

    for(int i=0;i<arr3.length;i++)
    {
        for(int j=i+1;j<arr3.length;j++)
        {
            if(arr3[i]==arr3[j])
                arr3[j]=99999999;          //line  12
        }
    }
    for(int i=0;i<arr3.length;i++)
    {
        if(arr3[i]!=99999999)
            System.out.print(arr3[i]+" ");
    }
}
}
</code>```

Body:
First, I am copying all values of arrays into a single array then I am removing duplicates values into the array. Line 12, explaining if same number occur more than time then put some extra garbage value into "j" position. At the end, traverse from start-end and check if same garbage value occur then discard.

public class Union {
public static void main(String[] args){

    int arr1[]={1,3,3,2,4,2,3,3,5,2,1,99};
    int arr2[]={1,3,2,1,3,2,4,6,3,4};
    int arr3[]=new int[arr1.length+arr2.length];

    for(int i=0;i<arr1.length;i++)
        arr3[i]=arr1[i];

    for(int i=0;i<arr2.length;i++)
        arr3[arr1.length+i]=arr2[i];
    System.out.println(Arrays.toString(arr3));

    for(int i=0;i<arr3.length;i++)
    {
        for(int j=i+1;j<arr3.length;j++)
        {
            if(arr3[i]==arr3[j])
                arr3[j]=99999999;          //line  12
        }
    }
    for(int i=0;i<arr3.length;i++)
    {
        if(arr3[i]!=99999999)
            System.out.print(arr3[i]+" ");
    }
}
}


问:
How can I align some text vertically in the middle of an HTML image?
I have this:
http://jsfiddle.net/8KWtH/

I would like to move the > so it is in the middle vertically of the two images.

How can i do this?

答:
I whipped out something here

From what I can see it is basically a variation on the other answers but it gets the job done


问:
Is it possible to use MSAL.js to get refresh token?
I want to integrate with Miscrosoft Outlook. I am able to login with MSAL.js and get an access token, but I am not able to get a refresh token. Is there a way to do it?</p>

答:
I'll assume that since you're using the MSAL.js (https://github.com/AzureAD/microsoft-authentication-library-for-js) that you're using implicit flow for authentication and authorization.

Implicit flow doesn't support refresh tokens, but you can request a new token silently. This is done similarly to how you request the token (id or access) in the first place. Unfortunately, I haven't found that MSAL.js does this transparently and I've needed to detect expired tokens and request the new tokens in my code. You can read more about refreshing tokens here.

Alternatively, if what you're implementing allows you to use one of the other MSAL libraries (for example, the .Net one) then you can use one of the other OAuth flows that explicitly support refresh tokens.


问:
Set value of cloned fieldset input field
This is a follow on question to the question I asked here. Everything is working as desired except the setting of the value for the 2nd input field, named misc_value, in the example below.

The desire is to have the first input field group1 be blank so the placeholder is shown and have the second input field contain a default value of 0.

If I examine the elements of the cloned fieldset I do see that value="0" is shown for the 2nd input field but nothing is actually displayed and that value is NOT returned on form submission.

I have tried a number of variations on the $('input[name="misc_value"]').val("0"); line in the example but the result has always been the same.

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Testing Input Value</title>

Testing Input Value

<form method="post" action="WeedsTest.html">

<fieldset id="fsgroup1">
Group 1
<input placeholder="Enter misc description" type="text" name="group1[]" value="" size="255" maxlength="255" />

$ Amount
<input type="text" name="misc_value[]" size="15" maxlength="15" value="0" />
Add
</fieldset>

</form>

```

答:
Your problems were:

No var next to newFS inside AddGroup1()

You weren't using newFS as the parent element to find misc_value

Your names for misc_value and group1 were misc_value[] and group1[], respectively, in your HTML, so find was not working correctly.

See the working example below:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Testing Input Value</title>

Testing Input Value

<form method="post" action="WeedsTest.html">

<fieldset id="fsgroup1">
Group 1
<input placeholder="Enter misc description" type="text" name="group1" value="" size="255" maxlength="255" />

$ Amount
<input type="text" name="misc_value" size="15" maxlength="15" value="0" />
Add
</fieldset>

</form>

```

Body:
Your problems were:

No var next to newFS inside AddGroup1()

You weren't using newFS as the parent element to find misc_value

Your names for misc_value and group1 were misc_value[] and group1[], respectively, in your HTML, so find was not working correctly.

See the working example below:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Testing Input Value</title>
<script type="text/javascript" src="//code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script type="text/javascript">

function AddGroup1() {

 var newFS = $('#fsgroup1').clone(true).removeProp("id");
 newFS.find('a').replaceWith('<a href="#" onclick="deleteID(this);return false;" title="Delete This Entry">Delete</a>');
 newFS.find("input:text").val("").end()
 newFS.find('input[name="misc_value"]').val("0");
 $("#moregroup1").append(newFS);

}  // end of the AddGroup1 function

function deleteID(button) {

 var fieldset = $(button).parent();
 $(fieldset).remove();

}  // end of the deleteID function
</script>
</head>
<body>
<h1>Testing Input Value</h1>
<form method="post" action="WeedsTest.html">

<fieldset id="fsgroup1">
<label for="group1">Group 1</label>
<input placeholder="Enter misc description" type="text" name="group1" value="" size="255" maxlength="255" />

<label for="misc_value">$ Amount</label>
<input type="text" name="misc_value" size="15" maxlength="15" value="0" />
<a href="#" onclick="AddGroup1();return false;" title="Add Additional Entry">Add</a>
</fieldset>

<div id="moregroup1"></div>

</form>
</body>
</html>


问:
Cannot assign an empty string to a string offset
I've just installed PHP 7.1 and now I am seeing this error :

```<code>PHP Warning:  Cannot assign an empty string to a string offset in /postfixadmin/variables.inc.php on line 31
</code>```

Line #31 :

```<code>$fDomains[0] = "";
</code>```

How does on clear $fDomains[0] now in PHP 7.1?

答:
According to bug #71572 it's not permitted to assign empty string. Then use:

```<code>substr(fDomains,1); //like Kris Roofe wrote;
</code>```

or use solutions like this:

```<code>$fDomainsTmp = $fDomains;
for($x = 0 ; $x < length($fDomains); $x ++){
    if(condition character allow in string){
      $fDomainsTmp .= $fDomains[$x];
    }
}
$fDomains = $fDomainsTmp;
</code>```

Body:
I've just installed PHP 7.1 and now I am seeing this error :

PHP Warning:  Cannot assign an empty string to a string offset in /postfixadmin/variables.inc.php on line 31

Line #31 :

$fDomains[0] = "";

How does on clear $fDomains[0] now in PHP 7.1?

Body:
According to bug #71572 it's not permitted to assign empty string. Then use:

substr(fDomains,1); //like Kris Roofe wrote;

or use solutions like this:

$fDomainsTmp = $fDomains;
for($x = 0 ; $x < length($fDomains); $x ++){
    if(condition character allow in string){
      $fDomainsTmp .= $fDomains[$x];
    }
}
$fDomains = $fDomainsTmp;


问:
feof() returning true when EOF is not reached
I'm trying to read from a file at a specific offset (simplified version):

```<code>typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);
</code>```

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

答:
Opening a file in text mode, like you're doing, makes the library translate some of the file contents to other stuff, potentially triggering a unwarranted EOF or bad offset calculations.

Open the file in binary mode by passing the "b" option to the fopen call

```<code>fopen(filename, "rb");
</code>```

Body:
I'm trying to read from a file at a specific offset (simplified version):

typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

Body:
Opening a file in text mode, like you're doing, makes the library translate some of the file contents to other stuff, potentially triggering a unwarranted EOF or bad offset calculations.

Open the file in binary mode by passing the "b" option to the fopen call

fopen(filename, "rb");


问:
Multiple page app - react native with native base
My first attempt of a any kind of app using react native. I am using native base for the components / styling. I have managed to get a very basic page but I am trying to work out how I go from this to a page which moves to different pages when clicked from say the footer.

```<code>import React, { Component } from 'react';
import { Navigator, Container, Content, Header, Title, Button, Left, Right, Body, Icon, Footer, FooterTab } from 'native-base';
import { Col, Row, Grid } from 'react-native-easy-grid';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class AwesomeNativeBase extends Component {
  render() {
    return (
      <Container>
          <Header>
              <Body>
                  <Title>Kays Hairdressing</Title>
              </Body>
          </Header>
          <Content>
            <Grid>
                <Col style={{ backgroundColor: '#635DB7', height: 550 }}></Col>
                <Col style={{ backgroundColor: '#00CE9F', height: 550  }}></Col>
            </Grid>
          </Content>
          <Footer>
            <FooterTab>
                <Button>
                    <Text>Bookings</Text>
                    <Icon name="ios-book-outline" />
                </Button>
                <Button>
                    <Text>Blockout</Text>
                    <Icon name="ios-calendar-outline" />
                </Button>
            </FooterTab>
          </Footer>
      </Container>
    );
  }
}

AppRegistry.registerComponent('AwesomeNativeBase', () => AwesomeNativeBase);
</code>```

I have worked out I need to use the 'navigator' option but I haven't been able to get it working as I am not sure how classes work in this setup.

答:
Use a navigation library such as React Navigation or React native navigation

React Navigation is a JavaScript based option whereas React native navigation is a more native implementation

Give them a try

Body:
My first attempt of a any kind of app using react native. I am using native base for the components / styling. I have managed to get a very basic page but I am trying to work out how I go from this to a page which moves to different pages when clicked from say the footer.

import React, { Component } from 'react';
import { Navigator, Container, Content, Header, Title, Button, Left, Right, Body, Icon, Footer, FooterTab } from 'native-base';
import { Col, Row, Grid } from 'react-native-easy-grid';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class AwesomeNativeBase extends Component {
  render() {
    return (
      <Container>

                  <Title>Kays Hairdressing</Title>

          <Content>
            <Grid>
                <Col style={{ backgroundColor: '#635DB7', height: 550 }}></Col>
                <Col style={{ backgroundColor: '#00CE9F', height: 550  }}></Col>
            </Grid>
          </Content>

            <FooterTab>
                <Button>
                    <Text>Bookings</Text>
                    <Icon name="ios-book-outline" />
                </Button>
                <Button>
                    <Text>Blockout</Text>
                    <Icon name="ios-calendar-outline" />
                </Button>
            </FooterTab>

      </Container>
    );
  }
}

AppRegistry.registerComponent('AwesomeNativeBase', () => AwesomeNativeBase);

I have worked out I need to use the 'navigator' option but I haven't been able to get it working as I am not sure how classes work in this setup.


答:
You can use pseudo elements to get it
just like following

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(http://lorempixel.com/400/200/);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  position: relative;
}

.about-section::after {
  content: '';
  height: 100%;
  width: 100%;
  background: rgba(255, 255, 255, 0.5); /*Change as your need */
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>

      </div>
    </div>
  </div>
</section></code>```

Title: How to change the opacity of background without changing the content of it?

Body:
You can use pseudo elements to get it
just like following

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(http://lorempixel.com/400/200/);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  position: relative;
}

.about-section::after {
  content: '';
  height: 100%;
  width: 100%;
  background: rgba(255, 255, 255, 0.5); /*Change as your need */
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

<section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>

      </div>
    </div>
  </div>
</section>