问:
Using same javascript function to change preview of multiple image upload
I have written code which allows user to upload multiple file upload :

```<code><asp:Image ID="image01" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image01_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image02" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image02_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image03" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image03_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image04" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image04_update" runat="server" onchange="showPreview(this);"/>
</code>```

The javascript function which shows preview for uploaded image is as follows :

```<code>function showPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image01').css('visibility', 'visible');
                $('#image01').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</code>```

currently preview is working for first image upload only, as i am passing ID- #image01.

I want to use same javascript function to show preview for all four image uploaders.
i.e. when i upload first image from #image01, it must show it's preview, for 2nd it must show 2nd image's preview.. and so on....

NOTE : i am using image upload in form editing mode, if there is no image uploaded ,

```<code>onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"
</code>```

this code will show an alternate image.

答:
Also you can use "data-" propery on button like this.

HTML

```<code><div>
    <div id="image01"></div>
    <button data-id="#image01" id="testBtn">Press me</button>
</div>
</code>```

JS

```<code>$(document).on('click', '#testBtn', function () {
        var id = $(this).data('id');
        $(id).text('testim');
    });
</code>```

Body:
I have written code which allows user to upload multiple file upload :

<asp:Image ID="image01" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image01_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image02" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image02_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image03" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image03_update" runat="server" onchange="showPreview(this);"/>
                                        <asp:Image ID="image04" runat="server" Width="20%" onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"/>
                                        <asp:FileUpload ID="image04_update" runat="server" onchange="showPreview(this);"/>

The javascript function which shows preview for uploaded image is as follows :

function showPreview(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#image01').css('visibility', 'visible');
                $('#image01').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

currently preview is working for first image upload only, as i am passing ID- #image01.

I want to use same javascript function to show preview for all four image uploaders.
i.e. when i upload first image from #image01, it must show it's preview, for 2nd it must show 2nd image's preview.. and so on....

NOTE : i am using image upload in form editing mode, if there is no image uploaded ,

onError="this.onerror=null;this.src='/resourceContent/resaleContent/altImage.png';"

this code will show an alternate image.

Body:
Also you can use "data-" propery on button like this.

HTML

<div>
    <div id="image01"></div>
    <button data-id="#image01" id="testBtn">Press me</button>
</div>

JS

$(document).on('click', '#testBtn', function () {
        var id = $(this).data('id');
        $(id).text('testim');
    });


来源: stackexchange

问:
Python Request Authorization
I need to pull some of my information of a web site for tax purposes, and unfortunately, the "export" features don't give me all the information I need.  The information does exist on the web site, as a single field in each of over 250 web pages.  I can click on each one and save them all and process them with a script, but I'd rather learn something instead.

The request package bills itself as being godsend for this, though I'm not wedded to it.  The problem is that I have to log into my web site.  request's documentation includes this link on authentication, documenting various forms of authentication, but contains no information on how to tell which form of authentication my web site actually uses.  I assume that a cookie of some sort is put on my computer when I log into the web site, and in theory, I could find that on my hard drive and send it along with my requests, but I have next to no experience with cookies and/or authorization and wouldn't know what to send.

If I can make a batch of requests to a list of urls, all on the same site, and download just the html, I can process it and build a report.

In your reply, if there are any links to general knowledge about how http authentication and cookies work together, I'd be happy to read that as well.

Thank you very much for any help you can provide.

答:
Try the following:

I'm using BasicAuth as it is the most common form of Auth; you can change it to any other form by looking at the documentation

Using the below as a "base code", you can create a list or dict of the urls to be visited and loop over them. The above code will also save you the trouble from having to "locate the cookies on the hard disk and load them".

edit: after looking at OP's comments:

```<code>import requests

login_url = "https://www.wyzant.com/sso/login"    # this is the login for's action url, extracted it from the source code

payload = {
    "Username" : "<username>",
    "Password" : "<password>"
}
with requests.Session() as s:
    r = s.post(login_url, data=payload)
    cookies = r.cookies
    r = s.get(url, cookies=cookies)    # do whatever
</code>```

I've tried the exact code above, works perfectly, and I'm able to login and access the Student Dashboard.

Cheers.

ContentLicense: CC BY-SA 3.0

Title: Python Request Authorization

Body:
Try the following:

I'm using BasicAuth as it is the most common form of Auth; you can change it to any other form by looking at the documentation

Using the below as a "base code", you can create a list or dict of the urls to be visited and loop over them. The above code will also save you the trouble from having to "locate the cookies on the hard disk and load them".

edit: after looking at OP's comments:

import requests

login_url = "https://www.wyzant.com/sso/login"    # this is the login for's action url, extracted it from the source code

payload = {
    "Username" : "<username>",
    "Password" : "<password>"
}
with requests.Session() as s:
    r = s.post(login_url, data=payload)
    cookies = r.cookies
    r = s.get(url, cookies=cookies)    # do whatever

I've tried the exact code above, works perfectly, and I'm able to login and access the Student Dashboard.

Cheers.


问:
How to replace Email id text before @ with * in swift 3.0
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

```<code>    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")
</code>```

Any suggestion is accepted.

Thank you.

答:
Use this function .</p>

```<code>func getStarred(_ email : String ) -> String
    {
        var didFoundATRO = false
        var tempString = ""
        for char in email.characters
        {
            if char == "@"
            {
                didFoundATRO = true
            }

            if !didFoundATRO
            {
                tempString += "*"
            }
            else
            {
                tempString.append(char)
            }
        }
        return tempString
    }
</code>```

Body:
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.

Body:
Use this function .

func getStarred(_ email : String ) -> String
    {
        var didFoundATRO = false
        var tempString = ""
        for char in email.characters
        {
            if char == "@"
            {
                didFoundATRO = true
            }

            if !didFoundATRO
            {
                tempString += "*"
            }
            else
            {
                tempString.append(char)
            }
        }
        return tempString
    }


问:
Extracting the keys and values out of a list
I have a string as :

```<code>fmt_string="I am a non-smoker female with a sum assured amount of
1000000 and a policy term for 20 years"
</code>```

After this I have removed the stopwords

```<code>from nltk.corpus import stopwords
stop = set(stopwords.words('english'))
d = [i for i in fmt_string.lower().split() if i not in stop]
</code>```

Now I want my output as :

```<code>{'gender': 'female', 'Sum assured amount': '1000000', 'smoke': 'non-
 smoker', 'Policy term': '20'}
</code>```

for achieving the same I ran the following code:

```<code>print {'smoke':d[0], 'gender':d[1], 'Sum assured amount': d[5],
'Policy term': d[8]}
</code>```

but in the following code I am hard coding my code and giving place values for extracting the values.
Is there a possible way where I don't need to give the exact position of the values in my list and make the code more generalized.

答:
This code will work for this, sentences, you have to playaround with keywords and you also need to set some conditions to check whether the amount and years are integers and if not go for nearby integers. Just this is a way

```<code>def compare(s1,s2):
        slen = len(s1)
        y=0
        while y<slen:
            if s1[y] in words:
                key=words.index(s1[y])
                return key;
            else:
                key=-1
            y+=1

    fmt_string="I am a non-smoker female with a sum assured amount of 1000000 and a policy term for 20 years"
    words = fmt_string.split()
    length=len(words)
    x=0
    gen=["male","female"];
    yrs = ["years","year","annum","per annum"];
    value=["amount","rupees"]
    ske = ["smoke","smoker","non-smoker"]
    gen_value = compare(gen,words)
    yrs_value = compare(yrs,words)
    vlue_value = compare(value,words)
    ske_value = compare(ske,words)
    yrs_value= yrs_value-1;
    amount_value = vlue_value + 2;

    print {'smoke':words[ske_value], 'gender':words[gen_value], 'Sum assured amount': words[amount_value], 'Policy term': words[yrs_value]}
</code>```

Hope you will play around with keywords..!

Body:
I have a string as :

fmt_string="I am a non-smoker female with a sum assured amount of
1000000 and a policy term for 20 years"

After this I have removed the stopwords

from nltk.corpus import stopwords
stop = set(stopwords.words('english'))
d = [i for i in fmt_string.lower().split() if i not in stop]

Now I want my output as :

{'gender': 'female', 'Sum assured amount': '1000000', 'smoke': 'non-
 smoker', 'Policy term': '20'}

for achieving the same I ran the following code:

print {'smoke':d[0], 'gender':d[1], 'Sum assured amount': d[5],
'Policy term': d[8]}

but in the following code I am hard coding my code and giving place values for extracting the values.
Is there a possible way where I don't need to give the exact position of the values in my list and make the code more generalized.

Body:
This code will work for this, sentences, you have to playaround with keywords and you also need to set some conditions to check whether the amount and years are integers and if not go for nearby integers. Just this is a way

def compare(s1,s2):
        slen = len(s1)
        y=0
        while y<slen:
            if s1[y] in words:
                key=words.index(s1[y])
                return key;
            else:
                key=-1
            y+=1

    fmt_string="I am a non-smoker female with a sum assured amount of 1000000 and a policy term for 20 years"
    words = fmt_string.split()
    length=len(words)
    x=0
    gen=["male","female"];
    yrs = ["years","year","annum","per annum"];
    value=["amount","rupees"]
    ske = ["smoke","smoker","non-smoker"]
    gen_value = compare(gen,words)
    yrs_value = compare(yrs,words)
    vlue_value = compare(value,words)
    ske_value = compare(ske,words)
    yrs_value= yrs_value-1;
    amount_value = vlue_value + 2;

    print {'smoke':words[ske_value], 'gender':words[gen_value], 'Sum assured amount': words[amount_value], 'Policy term': words[yrs_value]}

Hope you will play around with keywords..!


问:
IE.document.all returns null element vba
Does anyone know why this ExplorerButton.Click returns a 424 object reference error on run? HTML modules were correctly imported to be able to read the html related commands:

```<code>Private Sub Generate_Click()

Dim IE As New InternetExplorer
Dim ExplorerInput As HTMLInputElement
Dim ExplorerButton As HTMLInputElement

'Loading Page
IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loade
WaitIE IE
'Select document
Set IEDoc = IE.document

'Select Button
 Set ExplorerButton = IEDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424

End Sub

Sub WaitIE(IE As InternetExplorer)
   'Loop until load
   Do Until IE.readyState = READYSTATE_COMPLETE
      DoEvents
   Loop
End Sub
</code>```

I indicated the error with --> ERROR 424. I must be miss-referencing the page... When I looked up tutorials like this one http://qwazerty.developpez.com/tutoriels/vba/ie-et-vba-excel/ , which is really well brought about, this is how the reference was adressed and it seemed to work for him (and for me on the page he mentions). So I guess I must be omitting something when defining the button element. Any help much appreciated!

Thanks!
D.

答:
There is an iframe in the page. That's the issue.

You have to first get the iframe element, and then get the document associated with the iframe.

The fileupload button is in that iframe.

```<code>IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loaded
WaitIE IE
'Select document
Set IEDoc = IE.document

 Dim iBox As HTMLIFrame
 Set iBox = doc.all("iframe1")

 Dim iframeDoc As HTMLDocument
 Set iframeDoc = iBox.contentDocument
'Select Button
 Set ExplorerButton = iframeDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424
</code>```

Body:
Does anyone know why this ExplorerButton.Click returns a 424 object reference error on run? HTML modules were correctly imported to be able to read the html related commands:

Private Sub Generate_Click()

Dim IE As New InternetExplorer
Dim ExplorerInput As HTMLInputElement
Dim ExplorerButton As HTMLInputElement

'Loading Page
IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loade
WaitIE IE
'Select document
Set IEDoc = IE.document

'Select Button
 Set ExplorerButton = IEDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424

End Sub

Sub WaitIE(IE As InternetExplorer)
   'Loop until load
   Do Until IE.readyState = READYSTATE_COMPLETE
      DoEvents
   Loop
End Sub

I indicated the error with --> ERROR 424. I must be miss-referencing the page... When I looked up tutorials like this one http://qwazerty.developpez.com/tutoriels/vba/ie-et-vba-excel/ , which is really well brought about, this is how the reference was adressed and it seemed to work for him (and for me on the page he mentions). So I guess I must be omitting something when defining the button element. Any help much appreciated!

Thanks!
D.

Body:
There is an iframe in the page. That's the issue.

You have to first get the iframe element, and then get the document associated with the iframe.

The fileupload button is in that iframe.

IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loaded
WaitIE IE
'Select document
Set IEDoc = IE.document

 Dim iBox As HTMLIFrame
 Set iBox = doc.all("iframe1")

 Dim iframeDoc As HTMLDocument
 Set iframeDoc = iBox.contentDocument
'Select Button
 Set ExplorerButton = iframeDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424


问:
Apache Tomcat Maven plugin war not found
I'm following the documentation here but I end up with a jar that doesn't find the war to execute. Here's the error:

```<code>java.io.FileNotFoundException: C:\Users\ortizj\Documents\NetBeansProjects\valida
tion-manager\Validation-Manager-Web\target\.extract\webapps\ROOT.war (The system
 cannot find the file specified)
</code>```

For some reason the war file is not added to the jar so it fails when it's extracting it.

ROOT.war exists and is present in the target folder.

Here's the relevant POM contents:

POM Project:

```<code> <profile>
        <id>installer</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <executions>
                        <execution>
                            <id>tomcat-run</id>
                            <goals>
                                <goal>exec-war-only</goal>
                            </goals>
                            <phase>package</phase>
                            <configuration>
                                <warRunDependency>
                                    <dependency>
                                        <groupId>${project.groupId}</groupId>
                                        <artifactId>Validation-Manager-Web</artifactId>
                                        <version>${project.version}</version>
                                        <type>war</type>
                                    </dependency>
                                    <charset>utf-8</charset>
                                    <httpPort>9078</httpPort>
                                    <contextPath>/</contextPath>
                                </warRunDependency>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</code>```

答:
You are missing the decency on your war. Therefore it is not included:</p>

```<code><warRunDependencies>
  <warRunDependency>
    <dependency>
      <groupId>a groupId</groupId>
      <artifactId>and artifactId</artifactId>
      <version>version</version>
      <type>war</type>
    </dependency>
    <contextPath>/</contextPath>
  </warRunDependency>
</warRunDependencies>
</code>```

Body:
I'm following the documentation here but I end up with a jar that doesn't find the war to execute. Here's the error:

java.io.FileNotFoundException: C:\Users\ortizj\Documents\NetBeansProjects\valida
tion-manager\Validation-Manager-Web\target\.extract\webapps\ROOT.war (The system
 cannot find the file specified)

For some reason the war file is not added to the jar so it fails when it's extracting it.

ROOT.war exists and is present in the target folder.

Here's the relevant POM contents:

POM Project:

 <profile>
        <id>installer</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <executions>
                        <execution>
                            <id>tomcat-run</id>
                            <goals>
                                <goal>exec-war-only</goal>
                            </goals>
                            <phase>package</phase>
                            <configuration>
                                <warRunDependency>
                                    <dependency>
                                        <groupId>${project.groupId}</groupId>
                                        <artifactId>Validation-Manager-Web</artifactId>
                                        <version>${project.version}</version>
                                        <type>war</type>
                                    </dependency>
                                    <charset>utf-8</charset>
                                    <httpPort>9078</httpPort>
                                    <contextPath>/</contextPath>
                                </warRunDependency>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>

Body:
You are missing the decency on your war. Therefore it is not included:

<warRunDependencies>
  <warRunDependency>
    <dependency>
      <groupId>a groupId</groupId>
      <artifactId>and artifactId</artifactId>
      <version>version</version>
      <type>war</type>
    </dependency>
    <contextPath>/</contextPath>
  </warRunDependency>
</warRunDependencies>


问:
Html Anchor doesn't redirect
Here is main site link where each link working fine:
  http://www.hipackages.com/

but when redirect to bellow link, then links on the menubar doesn't responding:
 http://www.hipackages.com/lifestyle/page_detail/1

i try to redirect like this:
 http://www.hipackages.com#body

but this didn't redirect me to the required page.

Thanks to all for any response.

答:
I believe your site doesn't re-route because of jQuery click events. On your main page, your anchor tags most likely have an event.preventDefault() deal setup, notice that they have a link, but they don't refresh your main page, they just scroll to the section. Anchor tags (by default) do not do that, they will always load the page in their href attribute. This means that your javascript (particularly jQuery) is preventing the anchor tags from firing a window.location.href method and simply overriding their default action with scrolling.

Now, when you go to another page and use the same nav bar with the same settings, it will NOT redirect back to your homepage because of your click listeners in your jQuery. You need to go find them and disable them on all pages except for the main home/landing page. Then they anchor tags will work like default and will redirect you no problem. Does that make sense?

Title: Html Anchor doesn't redirect


问:
How do I explicitly run the static constructor of an unknown type?

Possible Duplicate:

  How do I invoke a static constructor with reflection?

I've got some initialization code in the static constructor of various classes. I can't create instances, nor do I know the types in advance. I would like to ensure the classes are loaded.

I tried this:

```<code>fooType.TypeInitializer.Invoke (new object[0]);
</code>```

But got a MemberAccessException: Type initializer was not callable.

I'm assuming this is because the cctor is private? Is there a way to fix this without changing the architecture?

Edit: I found a workaround using RuntimeHelpers.RunClassConstructor, but this way seems to be barely documented in the MSDN and I'm not sure if it is a hack or a reasonable, prod system like way.

答:
EDIT: explicitly won't work as-is, as poster states can't know the types in advance. Leaving here as might help clarification for future readers ...

If I understand your needs correctly -- in similar circumstances I create a wrapper that references the static class but remains part of the test suite. You can then instantiate the wrapper and have the static initialized on demand. It'd mean you can leave the architecture unchanged, and keep the wrapper as part of the test framework.

```
public static class MyStatic
{
    public static string SomeToolMethod()
    {
        return "Hello";
    }
}

public class MyStaticWrapper // or proxy, technically?
{
    public static string SomeToolMethod()
    {
        return MyStatic.SomeToolMethod();
    }
}

fooType.TypeInitializer.Invoke(new MyStaticWrapper()); /// untested, not sure of syntax here
```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  How do I invoke a static constructor with reflection?

I've got some initialization code in the static constructor of various classes. I can't create instances, nor do I know the types in advance. I would like to ensure the classes are loaded.

I tried this:

fooType.TypeInitializer.Invoke (new object[0]);

But got a MemberAccessException: Type initializer was not callable.

I'm assuming this is because the cctor is private? Is there a way to fix this without changing the architecture?

Edit: I found a workaround using RuntimeHelpers.RunClassConstructor, but this way seems to be barely documented in the MSDN and I'm not sure if it is a hack or a reasonable, prod system like way.

Body:
EDIT: explicitly won't work as-is, as poster states can't know the types in advance. Leaving here as might help clarification for future readers ...

If I understand your needs correctly -- in similar circumstances I create a wrapper that references the static class but remains part of the test suite. You can then instantiate the wrapper and have the static initialized on demand. It'd mean you can leave the architecture unchanged, and keep the wrapper as part of the test framework.

public static class MyStatic
{
    public static string SomeToolMethod()
    {
        return "Hello";
    }
}

public class MyStaticWrapper // or proxy, technically?
{
    public static string SomeToolMethod()
    {
        return MyStatic.SomeToolMethod();
    }
}

fooType.TypeInitializer.Invoke(new MyStaticWrapper()); /// untested, not sure of syntax here


问:
docker-compose up command not working on console
I have 5 images and try to run docker images through docker-compose up, but it is showing nothing on the console.
while running the docker-compose --version it is showing nothing.

答:
docker-compose does not come bundled with the docker-engine. You need to install it separately after installing the engine. Follow the instructions given in this link:

https://docs.docker.com/compose/install/


问:
Why is this Typescript object not assignable to generic type T, which is a Union including the type of the object
Obviously a contrived example, but why am I unable to assign an object of type ISpeaker3 to a generic type T that is a union including ISpeaker3? And why is there a need for the double cast shown below. </p>

```<code>interface ISpeaker {
    greeting: string;
    speak: Function;
}

interface ISpeaker1 extends ISpeaker {
    introduction: string;
    firstArgument: string;
}

interface ISpeaker2 extends ISpeaker {
    secondArgument: string;
}

interface ISpeaker3 extends ISpeaker {
    rebuttal: string;
}

class Speaker3 implements ISpeaker3 {
    public greeting: string = "hello I'm Speaker Three."
    public rebuttal: string = "what a lot of nonsense!"
    speak(){console.log(this.greeting + this.rebuttal)}
}

class Debate<T extends ISpeaker | ISpeaker3> {
    speakers: Array<T>
    randomSpeaker: T
    constructor(spkrs: Array<T>) {
        for (let s of spkrs) {
            if (s.constructor.name === 'Speaker3') {
                (s as ISpeaker3).rebuttal = "Some other argument..." // OK.
                let tempSpeaker = s as ISpeaker as ISpeaker3 // OK, but why the double cast necessary?
                this.randomSpeaker = tempSpeaker // Error - ISpeaker3 is not assignable to type T
            }
            else this.randomSpeaker = s // OK
        }
    }
}
</code>```

答:
The explanation could be find here:

Narrowing breaking changes #7662

Let me cite:

Type narrowing does not work for captured variables in functions and    class expressions

```<code>export class Class {
    constructor(public p) { }
}

var c: Class | string;
var x: Class;

if (c instanceof Class) {
    function inner() {
        x = c; // Error, type of c is not narrowed, c is Class | string
    }
    x = c; // OK, c is Class
}
</code>```

Body:
Obviously a contrived example, but why am I unable to assign an object of type ISpeaker3 to a generic type T that is a union including ISpeaker3? And why is there a need for the double cast shown below.

interface ISpeaker {
    greeting: string;
    speak: Function;
}

interface ISpeaker1 extends ISpeaker {
    introduction: string;
    firstArgument: string;
}

interface ISpeaker2 extends ISpeaker {
    secondArgument: string;
}

interface ISpeaker3 extends ISpeaker {
    rebuttal: string;
}

class Speaker3 implements ISpeaker3 {
    public greeting: string = "hello I'm Speaker Three."
    public rebuttal: string = "what a lot of nonsense!"
    speak(){console.log(this.greeting + this.rebuttal)}
}

class Debate<T extends ISpeaker | ISpeaker3> {
    speakers: Array<T>
    randomSpeaker: T
    constructor(spkrs: Array<T>) {
        for (let s of spkrs) {
            if (s.constructor.name === 'Speaker3') {
                (s as ISpeaker3).rebuttal = "Some other argument..." // OK.
                let tempSpeaker = s as ISpeaker as ISpeaker3 // OK, but why the double cast necessary?
                this.randomSpeaker = tempSpeaker // Error - ISpeaker3 is not assignable to type T
            }
            else this.randomSpeaker = s // OK
        }
    }
}

Body:
The explanation could be find here:

Narrowing breaking changes #7662

Let me cite:

Type narrowing does not work for captured variables in functions and    class expressions

export class Class {
    constructor(public p) { }
}

var c: Class | string;
var x: Class;

if (c instanceof Class) {
    function inner() {
        x = c; // Error, type of c is not narrowed, c is Class | string
    }
    x = c; // OK, c is Class
}


问:
Convert multiple lists to dataframe python
I want to put list in dataframe, my code is,

```<code>webpage_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]

    for i in webpage_urls:
        wiki2 = i
        page= urllib.request.urlopen(wiki2)

        soup = BeautifulSoup(page)

        # fetching organisations

        data3 = soup.find_all('li', class_="nav-item active")

        lobbying1 = []
        for element in data3:
            lobbying1.append(element.span.get_text())
        print(lobbying1)

        df = pd.DataFrame({'Organisation':lobbying1})
</code>```

My above code is giving output as:

```<code>['Reserve Bank of Aus... (24)', 'Business Support an... (24)']
['Department of Finance (16)', 'Business Support an... (16)']
['Department of Agric... (13)', 'Business Support an... (13)']...so on
</code>```

Which is multiple lists, not a nested one and I am getting data frame as follows only:

```<code>   Organisation
0  Australian Charitie... (1)
1  Business Support an... (1)
</code>```

I want output as two columns first element of list in column in column 1 and second element of list in column 2, and I want all entries:

```<code>Organisation            Groups
Australian Cha...      Business Support and...
</code>```

Help me out in this.

答:
I think you need add [] for list of lists and then use DataFrame constructor:

```<code>    df = pd.DataFrame([lobbying1], columns=['Organization','Groups'])
    print (df)

                  Organization        Groups
0  Department of Agric... (35)  Science (35)
                 Organization       Groups
0  Commonwealth Scient... (8)  Science (8)
                Organization       Groups
0  Bureau of Meteorology (4)  Science (4)
                 Organization       Groups
0  Tasmanian Museum an... (1)  Science (1)
                 Organization       Groups
0  Department of Indus... (1)  Science (1)
</code>```

If need one DataFrame for all data append lobbying1 to data list and then call DataFrame constructor out of loop:

```<code>data = []
for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)

    soup = BeautifulSoup(page)
    # fetching organisations
    data3 = soup.find_all('li', class_="nav-item active")

    lobbying1 = []
    for element in data3:
        lobbying1.append(element.span.get_text())
    data.append(lobbying1)

df = pd.DataFrame(data, columns=['Organization','Groups'])
print (df)
                  Organization        Groups
0  Department of Agric... (35)  Science (35)
1   Commonwealth Scient... (8)   Science (8)
2    Bureau of Meteorology (4)   Science (4)
3   Tasmanian Museum an... (1)   Science (1)
4   Department of Indus... (1)   Science (1)
</code>```

Body:
I want to put list in dataframe, my code is,

webpage_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]

    for i in webpage_urls:
        wiki2 = i
        page= urllib.request.urlopen(wiki2)

        soup = BeautifulSoup(page)

        # fetching organisations

        data3 = soup.find_all('li', class_="nav-item active")

        lobbying1 = []
        for element in data3:
            lobbying1.append(element.span.get_text())
        print(lobbying1)

        df = pd.DataFrame({'Organisation':lobbying1})

My above code is giving output as:

['Reserve Bank of Aus... (24)', 'Business Support an... (24)']
['Department of Finance (16)', 'Business Support an... (16)']
['Department of Agric... (13)', 'Business Support an... (13)']...so on

Which is multiple lists, not a nested one and I am getting data frame as follows only:

   Organisation
0  Australian Charitie... (1)
1  Business Support an... (1)

I want output as two columns first element of list in column in column 1 and second element of list in column 2, and I want all entries:

Organisation            Groups
Australian Cha...      Business Support and...

Help me out in this.

Body:
I think you need add [] for list of lists and then use DataFrame constructor:

    df = pd.DataFrame([lobbying1], columns=['Organization','Groups'])
    print (df)

                  Organization        Groups
0  Department of Agric... (35)  Science (35)
                 Organization       Groups
0  Commonwealth Scient... (8)  Science (8)
                Organization       Groups
0  Bureau of Meteorology (4)  Science (4)
                 Organization       Groups
0  Tasmanian Museum an... (1)  Science (1)
                 Organization       Groups
0  Department of Indus... (1)  Science (1)

If need one DataFrame for all data append lobbying1 to data list and then call DataFrame constructor out of loop:

data = []
for i in webpage_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)

    soup = BeautifulSoup(page)
    # fetching organisations
    data3 = soup.find_all('li', class_="nav-item active")

    lobbying1 = []
    for element in data3:
        lobbying1.append(element.span.get_text())
    data.append(lobbying1)

df = pd.DataFrame(data, columns=['Organization','Groups'])
print (df)
                  Organization        Groups
0  Department of Agric... (35)  Science (35)
1   Commonwealth Scient... (8)   Science (8)
2    Bureau of Meteorology (4)   Science (4)
3   Tasmanian Museum an... (1)   Science (1)
4   Department of Indus... (1)   Science (1)


问:
Change the TEXT (not background) color of a spinner when an item is selected
I have a spinner with several options, each displaying a simple string. Initially, the text is all white. However, if the user selects an option (causing it to become what is displayed on top), I would like that text to become red.

How can I do this?

EDIT : solved

```<code>public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
   ((TextView) arg1).setTextColor(Color.parseColor("#E3170D"));
}
</code>```

答:
some of you that using MaterialBetterSpinner and Binding your Layouts,
 all the above won't help, try this, hope it helps you:

```<code>public class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
        rowBinding.tv1.setText(mMy.getValues().get(position));
        if(position == mMy.getCurrentIndex()) {
            rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
            rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
        }
        return rowBinding.getRoot();
    }
}
</code>```

yourXML is something like this:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/colorBackgroundStart">
    <TextView
        android:id="@+id/tv1"
        android:layout_width="0dp"
        android:layout_weight="0.7"
        android:layout_height="30dp"
        android:textColor="#fff"
        android:textSize="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="8dp"/>

</layout>
</code>```

create a spinner with this adapter and yourXML :

```<code>final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
</code>```

Body:
I have a spinner with several options, each displaying a simple string. Initially, the text is all white. However, if the user selects an option (causing it to become what is displayed on top), I would like that text to become red.

How can I do this?

EDIT : solved

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
   ((TextView) arg1).setTextColor(Color.parseColor("#E3170D"));
}

Body:
some of you that using MaterialBetterSpinner and Binding your Layouts,
 all the above won't help, try this, hope it helps you:

public class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
        rowBinding.tv1.setText(mMy.getValues().get(position));
        if(position == mMy.getCurrentIndex()) {
            rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
            rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
        }
        return rowBinding.getRoot();
    }
}

yourXML is something like this:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/colorBackgroundStart">
    <TextView
        android:id="@+id/tv1"
        android:layout_width="0dp"
        android:layout_weight="0.7"
        android:layout_height="30dp"
        android:textColor="#fff"
        android:textSize="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="8dp"/>

</layout>

create a spinner with this adapter and yourXML :

final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);


问:
Using abstract class in C++ for dependency injection
With the reference of this Stackoverflow question, I'm not able to figure out the same problem of implementing DI using interface in c++ style, i.e. abstract class. Instead of bumping up old thread I created this one. Compiler throws error for the last line.</p>

```<code>class IService {
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : IService {
    void DoWork() {
        std::cout << "Work in progress inside A";
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : IService {
    void DoWork() {
        std::cout << "Work in progress inside B";
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
    Server(IService* service) : _service(service)
    { }

    // Error: this declaration has no storage class or type specifier
    // Compiler: MSVC 2017
    _service->DoWork();
};
</code>```

答:
I believe this is what you wanted:

```<code>#include <iostream>
using namespace std;

struct IService {
    virtual ~IService() = default; // Remember about virtual dtor to avoid memory leaks!
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : public IService {
    void DoWork() {
        std::cout << "Work in progress inside A" << endl;
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : public IService {
    void DoWork() {
        std::cout << "Work in progress inside B" << endl;
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
public:
    Server(IService* service) : _service(service)
    { }

    void doStuff() {
        _service->DoWork();
    }
};

int main() {

    ClientA a;
    ClientB b;
    Server sa(&a), sb(&b);
    cout << "ServerA: " << endl;
    sa.doStuff();
    cout << "ServerB: " << endl;
    sb.doStuff();
    return 0;
}
</code>```

Ideone

You need to get yourself familiar with the concept of access specifiers in C++. See here

Body:
With the reference of this Stackoverflow question, I'm not able to figure out the same problem of implementing DI using interface in c++ style, i.e. abstract class. Instead of bumping up old thread I created this one. Compiler throws error for the last line.

class IService {
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : IService {
    void DoWork() {
        std::cout << "Work in progress inside A";
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : IService {
    void DoWork() {
        std::cout << "Work in progress inside B";
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
    Server(IService* service) : _service(service)
    { }

    // Error: this declaration has no storage class or type specifier
    // Compiler: MSVC 2017
    _service->DoWork();
};

Body:
I believe this is what you wanted:

#include <iostream>
using namespace std;

struct IService {
    virtual ~IService() = default; // Remember about virtual dtor to avoid memory leaks!
    virtual void DoWork() = 0;
    virtual bool IsRunning() = 0;
};

class ClientA : public IService {
    void DoWork() {
        std::cout << "Work in progress inside A" << endl;
    }
    bool IsRunning() {
        return true;
    }
};

class ClientB : public IService {
    void DoWork() {
        std::cout << "Work in progress inside B" << endl;
    }
    bool IsRunning() {
        return true;
    }
};

class Server {
    IService* _service;
public:
    Server(IService* service) : _service(service)
    { }

    void doStuff() {
        _service->DoWork();
    }
};

int main() {

    ClientA a;
    ClientB b;
    Server sa(&a), sb(&b);
    cout << "ServerA: " << endl;
    sa.doStuff();
    cout << "ServerB: " << endl;
    sb.doStuff();
    return 0;
}

Ideone

You need to get yourself familiar with the concept of access specifiers in C++. See here


问:
Remove tiny scroll bar - Ionic 3
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

```<code> .height-70 {
        height: 70px;
        overflow: hidden;
    }
</code>```

.html

```<code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon><span>Continue with Linkedin</span></button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

答:
Try like this file app.scss under /src/app/

```<code>[scrollbar-y-auto] .scroll-content {
  overflow-y: false !important;
}
</code>```

and
Your code :

```<code><ion-content scrollbar-y-auto>
</code>```

Not tested Check and let me know

Title: Remove tiny scroll bar - Ionic 3

Body:
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

 .height-70 {
        height: 70px;
        overflow: hidden;
    }

.html

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon>Continue with Linkedin</button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

Body:
Try like this file app.scss under /src/app/

[scrollbar-y-auto] .scroll-content {
  overflow-y: false !important;
}

and
Your code :

<ion-content scrollbar-y-auto>

Not tested Check and let me know


问:
all strings of length k that can be formed from a set of n characters
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

```<code>input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')
</code>```

答:
I'm not proud of how this looks, but it works...

allcombs <- function(x, k) {

  apply(expand.grid(split(t(replicate(k, x)), seq_len(k))), 1, paste, collapse = "")

}

allcombs(letters[1:2], 2)
#> [1] "aa" "ba" "ab" "bb"

allcombs(letters[1:2], 4)
#>  [1] "aaaa" "baaa" "abaa" "bbaa" "aaba" "baba" "abba" "bbba" "aaab" "baab"
#> [11] "abab" "bbab" "aabb" "babb" "abbb" "bbbb"
```

Body:
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')


问:
Access Denied to all SVN Directories
I'm trying to delete several working copy directories, but I get an Access Denied on all the SVN files, running as admin or normal user.  I've killed the Tortoise cache process, and cannot figure what is wrong.

Any suggestions?

答:
I had heinous problems with this until I disabled my Norton Autoprotect anti-virus software.

http://subversion.tigris.org/faq.html#windows-access-denied

SO posting tip: include version, OS, etc. of your environment.

OwnerDisplayName: ProfK

Title: Access Denied to all SVN Directories

OwnerDisplayName: Mark


问:
How to Parameterize in Soap UI Load Test
I have a Webservice Request which is Exposed..

I need to use parameterization for each Request. I have used Groovy Script to Change couple of values in serial.

This is the result when not parameterization using groovy script in load test.

But When I introduce Groovy script to randomize some values. I am not getting proper result.. All are displayed as Zero even if it shows 100% completed
Once it is completed. it is not showing result.

When I Stop Running it is displaying result but it is drastic change in the result. How to parameterize in load test.

答: When I check the highlighted items. It is working fine..


问:
PHP: How to remove/disable a selection from a checkbox group if the value is already selected and stored in database previously
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

```<code>subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic
</code>```

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

```<code>    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3
</code>```

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.

答:
This is just an idea:

On your #2 where a table will store student_id and subject_id, I think it's best that whenever you store value to subject_id- you just serialize the value by storing it on an php array in that way you can iterate the whole array if the field was checked or not.

Json_encode is also good since it will be a string and same as serialize

Example:

```<code>Student_id       Subject_ID
999-0518         a:{this is the serialize value };
</code>```

Then when you query the result it will be serialize, then use unserialize function and do a loop to iterate the results, same goes when you json_encode; just perform json_decode() function and perform loop.

Body:
Right now I am coding in PHP & HTML

I need to make a selection from the checkbox group
and it goes like this:

The value in the dropdown menu is retrieved from the value stored in the database in table subject. So the checkbox options will appears as (for example) Mathematics, Algebra, Calculus, English, Linguistic etc. -- I have no problem with displaying this one.

Table subject

subject_id       subject_name
==========       ============
     1            Mathematics
     2            Algebra
     3            Calculus
     4            English
     5            Linguistic

So after that, a student can choose their subject and it will be stored in another table named student_subject where it stores the student_id and the subject_id (to store what subjects did a student chose)
Example:

table student_subject

    student_id       subject_id
    ==========       ===========
        1                 1
        1                 2
        1                 3
        2                 1
        2                 3

Now, the student comes again to add another subject to his profile. The same checkbox option will be displayed as mentioned earlier in (1) but I would love to disabled/remove/not display the already selected option from being selectable again to avoid redundancy.

I really have no idea on how to create this function. I know there are a lot of experienced programmers and developera here so I wish you could show me the right way. Your guidance is highly appreciated.

Body:
This is just an idea:

On your #2 where a table will store student_id and subject_id, I think it's best that whenever you store value to subject_id- you just serialize the value by storing it on an php array in that way you can iterate the whole array if the field was checked or not.

Json_encode is also good since it will be a string and same as serialize

Example:

Student_id       Subject_ID
999-0518         a:{this is the serialize value };

Then when you query the result it will be serialize, then use unserialize function and do a loop to iterate the results, same goes when you json_encode; just perform json_decode() function and perform loop.


问:
Adding custom images to ggplot facets
I'd like to add a custom image to each facet. Using annotation_custom duplicates an image across all facets, e.g:

```<code>require(ggplot2); require(grid); require(png); require(RCurl)

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species)

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png'))
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png'))
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png'))

a1 = annotation_custom(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)
a2 = annotation_custom(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)
a3 = annotation_custom(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)

p + a1
</code>```

Is there an alternative method to achieve this so img1-3 populate the respective facets correctly?

答:
For completeness, I'm adding the answer. All credit goes to @baptiste who suggested the annotation_custom2 function.

```<code>require(ggplot2); require(grid); require(png); require(RCurl)

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species)

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png'))
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png'))
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png'))

annotation_custom2 <-
function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data){ layer(data = data, stat = StatIdentity, position = PositionIdentity,
        geom = ggplot2:::GeomCustomAnn,
        inherit.aes = TRUE, params = list(grob = grob,
                                          xmin = xmin, xmax = xmax,
                                          ymin = ymin, ymax = ymax))}

a1 = annotation_custom2(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[1,])
a2 = annotation_custom2(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[51,])
a3 = annotation_custom2(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[101,])

p + a1 + a2 + a3
</code>```

Output:

Title: Adding custom images to ggplot facets

Body:
I'd like to add a custom image to each facet. Using annotation_custom duplicates an image across all facets, e.g:

require(ggplot2); require(grid); require(png); require(RCurl)

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species)

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png'))
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png'))
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png'))

a1 = annotation_custom(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)
a2 = annotation_custom(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)
a3 = annotation_custom(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5)

p + a1

Is there an alternative method to achieve this so img1-3 populate the respective facets correctly?

Body:
For completeness, I'm adding the answer. All credit goes to @baptiste who suggested the annotation_custom2 function.

require(ggplot2); require(grid); require(png); require(RCurl)

p = ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_wrap(~Species)

img1 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png'))
img2 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png'))
img3 = readPNG(getURLContent('https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png'))

annotation_custom2 <-
function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data){ layer(data = data, stat = StatIdentity, position = PositionIdentity,
        geom = ggplot2:::GeomCustomAnn,
        inherit.aes = TRUE, params = list(grob = grob,
                                          xmin = xmin, xmax = xmax,
                                          ymin = ymin, ymax = ymax))}

a1 = annotation_custom2(rasterGrob(img1, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[1,])
a2 = annotation_custom2(rasterGrob(img2, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[51,])
a3 = annotation_custom2(rasterGrob(img3, interpolate=TRUE), xmin=7, xmax=8, ymin=3.75, ymax=4.5, data=iris[101,])

p + a1 + a2 + a3

Output:


问:
swagger securityDefinition with Resteasy
I did configure swagger with an Application subclass and the beanConfig object, my securityDefinition must allow swagger ui to show de api_key field to allow authentication for all my services layer. </p>

```<code>    BeanConfig beanConfig = new BeanConfig();
    beanConfig.setSchemes(new String[] { "http" });
    beanConfig.setHost("192.168.4.9:8080");
    beanConfig.setBasePath("/cjppa/rest");
    beanConfig.setResourcePackage("com.cjppa.fpuna.backend.resources");
    beanConfig.setScan(true);
    beanConfig.setPrettyPrint(true);

    io.swagger.models.Info info = new io.swagger.models.Info();
    io.swagger.models.Contact contact = new io.swagger.models.Contact();
    info.setVersion("1.0");
    beanConfig.setInfo(info);

    io.swagger.models.auth.ApiKeyAuthDefinition apikey = new
    io.swagger.models.auth.ApiKeyAuthDefinition();
    apikey.setName("x-token");
    apikey.setIn(In.HEADER);

    Swagger swagger = new Swagger().info(info);
    swagger.securityDefinition("api_key", apikey);

    beanConfig.configure(swagger);
</code>```

<p>the expected api_key comes in the "x-token" http header </p>

答:
you can implements io.swagger.jaxrs.config.ReaderListener ,addSecurity in afterScan method . eg:</p>

```<code>@SwaggerDefinition(securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = {
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "token", name = "E-token"),
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "userId", name = "E-userId"),
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "corpId", name = "E-corpId") }) )
public class SwaggerCustomizeDefinition implements ReaderListener {

    @Override
    public void beforeScan(Reader reader, Swagger swagger) {

    }

    @Override
    public void afterScan(Reader reader, Swagger swagger) {
        swagger.addSecurity(new SecurityRequirement().requirement("token"));
        swagger.addSecurity(new SecurityRequirement().requirement("userId"));
        swagger.addSecurity(new SecurityRequirement().requirement("corpId"));
    }

}
</code>```

Body:
I did configure swagger with an Application subclass and the beanConfig object, my securityDefinition must allow swagger ui to show de api_key field to allow authentication for all my services layer.

    BeanConfig beanConfig = new BeanConfig();
    beanConfig.setSchemes(new String[] { "http" });
    beanConfig.setHost("192.168.4.9:8080");
    beanConfig.setBasePath("/cjppa/rest");
    beanConfig.setResourcePackage("com.cjppa.fpuna.backend.resources");
    beanConfig.setScan(true);
    beanConfig.setPrettyPrint(true);

    io.swagger.models.Info info = new io.swagger.models.Info();
    io.swagger.models.Contact contact = new io.swagger.models.Contact();
    info.setVersion("1.0");
    beanConfig.setInfo(info);

    io.swagger.models.auth.ApiKeyAuthDefinition apikey = new
    io.swagger.models.auth.ApiKeyAuthDefinition();
    apikey.setName("x-token");
    apikey.setIn(In.HEADER);

    Swagger swagger = new Swagger().info(info);
    swagger.securityDefinition("api_key", apikey);

    beanConfig.configure(swagger);

the expected api_key comes in the "x-token" http header

Body:
you can implements io.swagger.jaxrs.config.ReaderListener ,addSecurity in afterScan method . eg:

@SwaggerDefinition(securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = {
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "token", name = "E-token"),
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "userId", name = "E-userId"),
    @ApiKeyAuthDefinition(in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = "corpId", name = "E-corpId") }) )
public class SwaggerCustomizeDefinition implements ReaderListener {

    @Override
    public void beforeScan(Reader reader, Swagger swagger) {

    }

    @Override
    public void afterScan(Reader reader, Swagger swagger) {
        swagger.addSecurity(new SecurityRequirement().requirement("token"));
        swagger.addSecurity(new SecurityRequirement().requirement("userId"));
        swagger.addSecurity(new SecurityRequirement().requirement("corpId"));
    }

}


问:
Hive: PARTITIONED BY and SERDEPROPERTIES
I am trying to create a hive table with partition by a single field. The data that i wanted to process is log data. Format of log is:

DATE  TIME    IPAddress   HTTP_METHOD     MESSAGE

Create table hive query:

```<code>CREATE EXTERNAL TABLE test_Part(
logdate string,
logtime string,
ip string,
message string)
PARTITIONED BY(method string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
"input.regex" = "(\\d{4}-\\d{2}-\\d{2})\\s(\\d{2}:\\d{2}:\\d{2})\\s(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S+)\\s(.*$)",
"output.format.string" = "%1$s %2$s %3$s %5$s %4$s"
)
STORED AS TEXTFILE;
</code>```

And load script:

```<code>LOAD DATA LOCAL INPATH '/home/user/tools/apache-hive-1.2.2-bin/scripts/sample1.log' OVERWRITE INTO TABLE test_Part PARTITION(method='GET');
</code>```

When i run a select query on the above table, it gives me error message as

Failed with exception
  java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException:
  Number of matching groups doesn't match the number  of columns

What am i missing ?

答:
Partitions reflect a condition where rows characterized by specific value(s) (partition column(s) values) are accessible directly without the need access additional unnecessary data.

This is clearly not the case here, so you can't declare a partitioned table over your data file(s).

From this point you can do the following:

1.

leave out the partitions.

```<code>CREATE EXTERNAL TABLE test_Part_stg(
logdate string,
logtime string,
ip string,
method string,
message string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
"input.regex" = "(\\d{4}-\\d{2}-\\d{2})\\s(\\d{2}:\\d{2}:\\d{2})\\s(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S+)\\s(.*$)"
)
STORED AS TEXTFILE;
</code>```

2. (optional)

Create an additional partitioned table and fill it using the table from the previous step.

(This table storage does not have to be TEXTFILE)

```<code>CREATE EXTERNAL TABLE test_Part(
logdate string,
logtime string,
ip string,
message string)
PARTITIONED BY(method string)
STORED AS TEXTFILE;
</code>```

```<code>set hive.exec.dynamic.partition.mode=nonstrict
;
</code>```

```<code>insert into test_Part partition (method)
select logdate,logtime,ip,message,method
from   test_Part_stg
;
</code>```

or

```<code>insert into test_Part partition (method) (logdate,logtime,ip,method,message)
select *
from   test_Part_stg
;
</code>```

P.s.

output.format.string was deprecated, it is not defined in the RegexSerDe and it has no functional meaning as any other undefined SerDe parameter.

Body:
I am trying to create a hive table with partition by a single field. The data that i wanted to process is log data. Format of log is:

DATE  TIME    IPAddress   HTTP_METHOD     MESSAGE

Create table hive query:

CREATE EXTERNAL TABLE test_Part(
logdate string,
logtime string,
ip string,
message string)
PARTITIONED BY(method string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
"input.regex" = "(\\d{4}-\\d{2}-\\d{2})\\s(\\d{2}:\\d{2}:\\d{2})\\s(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S+)\\s(.*$)",
"output.format.string" = "%1$s %2$s %3$s %5$s %4$s"
)
STORED AS TEXTFILE;

And load script:

LOAD DATA LOCAL INPATH '/home/user/tools/apache-hive-1.2.2-bin/scripts/sample1.log' OVERWRITE INTO TABLE test_Part PARTITION(method='GET');

When i run a select query on the above table, it gives me error message as

Failed with exception
  java.io.IOException:org.apache.hadoop.hive.serde2.SerDeException:
  Number of matching groups doesn't match the number  of columns

What am i missing ?

Body:
Partitions reflect a condition where rows characterized by specific value(s) (partition column(s) values) are accessible directly without the need access additional unnecessary data.

This is clearly not the case here, so you can't declare a partitioned table over your data file(s).

From this point you can do the following:

1.

leave out the partitions.

CREATE EXTERNAL TABLE test_Part_stg(
logdate string,
logtime string,
ip string,
method string,
message string)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
"input.regex" = "(\\d{4}-\\d{2}-\\d{2})\\s(\\d{2}:\\d{2}:\\d{2})\\s(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S+)\\s(.*$)"
)
STORED AS TEXTFILE;

2. (optional)

Create an additional partitioned table and fill it using the table from the previous step.

(This table storage does not have to be TEXTFILE)

CREATE EXTERNAL TABLE test_Part(
logdate string,
logtime string,
ip string,
message string)
PARTITIONED BY(method string)
STORED AS TEXTFILE;

set hive.exec.dynamic.partition.mode=nonstrict
;

insert into test_Part partition (method)
select logdate,logtime,ip,message,method
from   test_Part_stg
;

or

insert into test_Part partition (method) (logdate,logtime,ip,method,message)
select *
from   test_Part_stg
;

P.s.

output.format.string was deprecated, it is not defined in the RegexSerDe and it has no functional meaning as any other undefined SerDe parameter.


问:
Node server: is it safe to put security credentials in npm scripts?
Often credentials are required for NodeJs server, e.g. express session key. Since environment variables can be supplied in npm scripts, is it considered a good practice to put the credentials there?

For example(in package.json):

```<code>"scripts": {
    "start": "EXPRESS_SESSION_KEY=mysessionkey node server server/index.js",
}
</code>```

So when I do npm start the credentials are also supplied.

P.S. Git repository is private so package.json is not likely to leak.

答:
No, it's not safe.

Even if git repository is private and package.json is not publicly available, this package.json file with sensitive information is available to all developers -- whoever has authority to access the git repository would be able to access the key, which is a big problem -- more people access the key, more risks.

To fix the security issue, my suggestion is using 2 keys, one for development & test, one for production. In package.json, development key is set, so that developers can easily clone code and launch the program:

```<code>"scripts": {
  "start": "DEV_KEY=devsessionkey node server server/index.js",
}
</code>```

In the code where KEY is used, PROD_KEY (key for production) would be checked and used first. DEV_KEY is used only if there is no PROD_KEY:

```<code>var key = process.env.PROD_KEY ? process.env.PROD_KEY : process.env.DEV_KEY;
</code>```

When DevOps engineer deploy  the code, he/she will set environment variable PROD_KEY in operating system and then launch the program. By this way, only specific DevOps engineer know the production key, which makes it much safer.

Body:
Often credentials are required for NodeJs server, e.g. express session key. Since environment variables can be supplied in npm scripts, is it considered a good practice to put the credentials there?

For example(in package.json):

"scripts": {
    "start": "EXPRESS_SESSION_KEY=mysessionkey node server server/index.js",
}

So when I do npm start the credentials are also supplied.

P.S. Git repository is private so package.json is not likely to leak.

Body:
No, it's not safe.

Even if git repository is private and package.json is not publicly available, this package.json file with sensitive information is available to all developers -- whoever has authority to access the git repository would be able to access the key, which is a big problem -- more people access the key, more risks.

To fix the security issue, my suggestion is using 2 keys, one for development & test, one for production. In package.json, development key is set, so that developers can easily clone code and launch the program:

"scripts": {
  "start": "DEV_KEY=devsessionkey node server server/index.js",
}

In the code where KEY is used, PROD_KEY (key for production) would be checked and used first. DEV_KEY is used only if there is no PROD_KEY:

var key = process.env.PROD_KEY ? process.env.PROD_KEY : process.env.DEV_KEY;

When DevOps engineer deploy  the code, he/she will set environment variable PROD_KEY in operating system and then launch the program. By this way, only specific DevOps engineer know the production key, which makes it much safer.


问:
Wildfly Swarm security domain configuration
We are trying to migrate a project from Wildfly 10 to Wildfly Swarm 2017.6, and we have a reached a stumbling block porting the security-domain. Our security domain is configured as follows:

```<code><security-domain name="sec-id">
   <authentication-jaspi>
   <login-module-stack name="sec-id-module-stack">
   <login-module code="com.obbi.domain.security.loginmodule.jwt.JWTLoginModule" flag="sufficient" module="com.obbi.domain.security">
   <module-option name="expectedIssuer" value="CN=DI SIT signer"/>
   <module-option name="expectedAudience" value="Obbi"/>
   <module-option name="allowedClockSkewInSeconds" value="30"/>
   <module-option name="validateTokenSignature" value="false"/>
   <module-option name="maxFutureValidityInMinutes" value="525600"/>
   <module-option name="keyStoreFilePath" value="C:/wildfly-10.1.0.Final/standalone/configuration/keystore.jks"/>
   <module-option name="keyStorePassword" value="obbi123"/>
   <module-option name="validateCertificate" value="false"/>
   <module-option name="loadSystemPrincipals" value="true"/>
   <module-option name="loadSystemPrincipalsEndpoint" value="https://test.obbi.co.za:9443/services/v1/obbi-id?page=0&size=1000&username=%s"/>
   <module-option name="skipAllValidators" value="true"/>
   </login-module>
   </login-module-stack>
   <auth-module code="com.obbi.domain.security.JASPICServerAuthModule" flag="required" login-module-stack-ref="sec-id-module-stack"/>
   </authentication-jaspi>
</security-domain>
</code>```

We also have a standard module configured on com.obbi.domain.security. The module is just a standard module as follows:

```<code><module xmlns="urn:jboss:module:1.3" name="com.obbi.domain.security">
  <resources>
    <resource-root path="domain-service-security-jboss-2.0-SNAPSHOT.jar"/>
    <resource-root path="domain-service-security-client-2.0-SNAPSHOT.jar"/>
    <resource-root path="jose4j-0.5.0.jar"/>
  </resources>
  <dependencies>
    <module name="org.jboss.as.web"/>
    <module name="org.jboss.logging"/>
    <module name="org.picketbox"/>
    <module name="javax.api"/>
    <module name="javax.security.auth.message.api"/>
    <module name="javax.servlet.api"/>
  </dependencies>
</module>
</code>```

I can't find any wildfly swarm security fragment mappings that match to the subsystem. May I ask if they do exist, and if there is any documentation on them, of if anyone can assist in this forum can assist?

Regards

答:
Managed to configure it as follows:</p>

```<code>swarm.fraction(new SecurityFraction()
        .securityDomain("sec-id", (sd) -> {
        sd.jaspiAuthentication(jaspi -> {
        jaspi.authModule("basic", value -> {
        value.code("com.obbi.domain.security.loginmodule.jwt.JWTLoginModule")
        .flag(Flag.SUFFICIENT)
        .module("com.obbi.domain.security")
        .moduleOption("expectedIssuer", "CN=DI SIT signer")
        .moduleOption("expectedAudience", "Obbi")
        .moduleOption("allowedClockSkewInSeconds", "30")
        .moduleOption("validateTokenSignature", "false")
        .moduleOption("maxFutureValidityInMinutes", "525600")
        .moduleOption("keyStoreFilePath", "C:/wildfly-10.1.0.Final/standalone/configuration/keystore.jks")
        .moduleOption("keyStorePassword", "pass123")
        .moduleOption("validateCertificate", "false")
        .moduleOption("loadSystemPrincipals", "true")
        .moduleOption("loadSystemPrincipalsEndpoint", "https://test.obbi.co.za:9443/services/v1/obbi-id?page=0&size=1000&username=%s")
        .moduleOption("skipAllValidators", "true");
        });
        });
        }));
</code>```

Body:
We are trying to migrate a project from Wildfly 10 to Wildfly Swarm 2017.6, and we have a reached a stumbling block porting the security-domain. Our security domain is configured as follows:

<security-domain name="sec-id">
   <authentication-jaspi>
   <login-module-stack name="sec-id-module-stack">
   <login-module code="com.obbi.domain.security.loginmodule.jwt.JWTLoginModule" flag="sufficient" module="com.obbi.domain.security">
   <module-option name="expectedIssuer" value="CN=DI SIT signer"/>
   <module-option name="expectedAudience" value="Obbi"/>
   <module-option name="allowedClockSkewInSeconds" value="30"/>
   <module-option name="validateTokenSignature" value="false"/>
   <module-option name="maxFutureValidityInMinutes" value="525600"/>
   <module-option name="keyStoreFilePath" value="C:/wildfly-10.1.0.Final/standalone/configuration/keystore.jks"/>
   <module-option name="keyStorePassword" value="obbi123"/>
   <module-option name="validateCertificate" value="false"/>
   <module-option name="loadSystemPrincipals" value="true"/>
   <module-option name="loadSystemPrincipalsEndpoint" value="https://test.obbi.co.za:9443/services/v1/obbi-id?page=0&size=1000&username=%s"/>
   <module-option name="skipAllValidators" value="true"/>
   </login-module>
   </login-module-stack>
   <auth-module code="com.obbi.domain.security.JASPICServerAuthModule" flag="required" login-module-stack-ref="sec-id-module-stack"/>
   </authentication-jaspi>
</security-domain>

We also have a standard module configured on com.obbi.domain.security. The module is just a standard module as follows:

<module xmlns="urn:jboss:module:1.3" name="com.obbi.domain.security">
  <resources>
    <resource-root path="domain-service-security-jboss-2.0-SNAPSHOT.jar"/>
    <resource-root path="domain-service-security-client-2.0-SNAPSHOT.jar"/>
    <resource-root path="jose4j-0.5.0.jar"/>
  </resources>
  <dependencies>
    <module name="org.jboss.as.web"/>
    <module name="org.jboss.logging"/>
    <module name="org.picketbox"/>
    <module name="javax.api"/>
    <module name="javax.security.auth.message.api"/>
    <module name="javax.servlet.api"/>
  </dependencies>
</module>

I can't find any wildfly swarm security fragment mappings that match to the subsystem. May I ask if they do exist, and if there is any documentation on them, of if anyone can assist in this forum can assist?

Regards

Body:
Managed to configure it as follows:

swarm.fraction(new SecurityFraction()
        .securityDomain("sec-id", (sd) -> {
        sd.jaspiAuthentication(jaspi -> {
        jaspi.authModule("basic", value -> {
        value.code("com.obbi.domain.security.loginmodule.jwt.JWTLoginModule")
        .flag(Flag.SUFFICIENT)
        .module("com.obbi.domain.security")
        .moduleOption("expectedIssuer", "CN=DI SIT signer")
        .moduleOption("expectedAudience", "Obbi")
        .moduleOption("allowedClockSkewInSeconds", "30")
        .moduleOption("validateTokenSignature", "false")
        .moduleOption("maxFutureValidityInMinutes", "525600")
        .moduleOption("keyStoreFilePath", "C:/wildfly-10.1.0.Final/standalone/configuration/keystore.jks")
        .moduleOption("keyStorePassword", "pass123")
        .moduleOption("validateCertificate", "false")
        .moduleOption("loadSystemPrincipals", "true")
        .moduleOption("loadSystemPrincipalsEndpoint", "https://test.obbi.co.za:9443/services/v1/obbi-id?page=0&amp;size=1000&amp;username=%s")
        .moduleOption("skipAllValidators", "true");
        });
        });
        }));


问:
find duplicate addresses in database, stop users entering them early?
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

```<code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code>```

I'm talking German addresses...
Thanks!

答:
I'm looking for an answer addressing United States addresses

The issue in question is prevent users from entering duplicates like

Quellenstrasse 66/11 and
Quellenstr. 66a-11

This happens when you let your user enter the complete address in input box.

There are some methods you can use to prevent this.

1. Uniform formatting using RegEx

You can prompt users to enter the details in a uniform format.

That is very efficient while querying too

test the user entered value against some regular expressions and if failed, ask user to correct it.

2.Use a map api like google maps and ask the user to select details from it.

If you choose google maps, you can achieve it using Reverse Geocoding.

From Google Developer's guide,

The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the opposite, translating a location on the map into a human-readable address, is known as reverse geocoding.

3. Allow heterogeneous data as shown in the question and compare it with different formatting.

In the question, the OP allow address in different format.

In such case, you can change it to different forms and check it with database to get a solution.

This may take more time and the time is completely depends on the number of test cases.

4. Split the address into different parts and store it in db and provide such a form to user.

That is provide different fields to store Street, city, state etc in database.

Also provide the different input fields to user to enter street, city, state, etc in top down format.

When user enter state, narrow the query to find dupes to that state only.

When user enter city, narrow it to that city only.

When user enter the street, narrow it to that street.

And finally

When user enter the address, change it to different formats and test it against Data Base.

This is efficient even the number of test cases may high, the number of entries you test against will be very less and so it will consume very less amount of time.

OwnerDisplayName: Johannes

Body:
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?

Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like:

Quellenstrasse 66/11
Quellenstr. 66a-11

I'm talking German addresses...
Thanks!

LastEditorDisplayName: Remou


问:
Efficient number reading in Haskell
I'm looking for an efficient way to read numbers from a text file without installing additional packages. Data.ByteString.Lazy.Char8.readInt seems to do the trick for integers. I've read that ByteString now has a readDouble method, but when I write import Data.ByteString.Lex.Lazy.Double (readDouble) the compiler complains:

```
    Main.hs:4:7:
        Could not find module `Data.ByteString.Lex.Lazy.Double':
          locations searched:
            Data/ByteString/Lex/Lazy/Double.hs
            Data/ByteString/Lex/Lazy/Double.lhs
```

My bytestring package version is 0.9.1.5.

So, am I doing something wrong? Or maybe there is a better solution for the problem? Thanks.

Update: OK, seems that readDouble is in package bytestring-lexer which is not installed by default. Any other idea?

答:
The only time I encountered parsing doubles on the critical path, I used this:

```<code>{-# LANGUAGE ForeignFunctionInterface #-}
import qualified Data.ByteString.Char8 as B
import Foreign.C.Types
import Foreign.C.String
import System.IO.Unsafe

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO CDouble
unsafeReadDouble = unsafePerformIO . flip B.useAsCString c_atof
</code>```

There wasn't anything that looked like a readDouble in bytestring at that time, though.  That would probably be a better solution if it's now standard.

Title: Efficient number reading in Haskell

Body:
I'm looking for an efficient way to read numbers from a text file without installing additional packages. Data.ByteString.Lazy.Char8.readInt seems to do the trick for integers. I've read that ByteString now has a readDouble method, but when I write import Data.ByteString.Lex.Lazy.Double (readDouble) the compiler complains:

    Main.hs:4:7:
        Could not find module `Data.ByteString.Lex.Lazy.Double':
          locations searched:
            Data/ByteString/Lex/Lazy/Double.hs
            Data/ByteString/Lex/Lazy/Double.lhs

My bytestring package version is 0.9.1.5.

So, am I doing something wrong? Or maybe there is a better solution for the problem? Thanks.

Update: OK, seems that readDouble is in package bytestring-lexer which is not installed by default. Any other idea?

Body:
The only time I encountered parsing doubles on the critical path, I used this:

{-# LANGUAGE ForeignFunctionInterface #-}
import qualified Data.ByteString.Char8 as B
import Foreign.C.Types
import Foreign.C.String
import System.IO.Unsafe

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO CDouble
unsafeReadDouble = unsafePerformIO . flip B.useAsCString c_atof

There wasn't anything that looked like a readDouble in bytestring at that time, though.  That would probably be a better solution if it's now standard.


问:
What is the default HTTP verb in WebApi ? GET or POST?
Just curios. I was looking at one of the web projects at internet.

And the code flow is like this:

```<code>[RoutePrefix("/person")]
public class PersonController : ApiController
{

    //....
    [Route("/register")]
    public IHttpACtionResult RegisterPerson(PersonDto personDto)
    {
        //....
    }
    //....
}
</code>```

Did you notice the above code? There is no [HttpGet()] or [HttpPost()] specified. Yet the above code fails for a GET call but works for a POST call.

Any ideas how this method's HTTP-Verb is resolved ?

Note: I know that if a methodname starts with GET or POST, then correspondingly the method is invoked via HTTPGet or HTTPPost. But the method name here starts with Register....

Any ideas how this works?

答:
It Depends on you Action Name if it matches any on the Http Verb. For example

In my API i used an Action to get vendors list, now see how it works:

```<code>    [Route("Get")]
    public IHttpActionResult GetVendor()
    {
        var vendor = _ivs.GetVendorDetails();

        return Ok(vendor);
    }
</code>```

Now when i am hitting api using HttpPost I am getting following message:

{
    "Message": "The requested resource does not support http method 'POST'."
}

however if I am hitting API using HttpGet I am getting the data

```<code> {
   "VendorId": "cc0e7ea1-4751-467b-b60b-be9b5202a511",

    "VendorCode": "Vend1",
    "VendorName": "testvendor",
    "AddressLine1": "AddressLine1",
    "AddressLine2": "AddressLine2",
    "AddressLine3": "AddressLine3",
    "City": "City                          ",
    "PINCode": "12345   ",
    "province": "province                      ",
    "Phone1": "Phone1",
    "Phone2": "Phone2",
    "Phone3": "Phone3",
    "PrimaryPhone": "Phone3    ",
    "CreatedDate": "2017-06-21T15:49:30.207",
    "CreatedBy": "e465e3e2-4156-434e-a444-f9a9626e1cf6",
    "UpdatedDate": "1900-01-01T00:00:00",
    "UpdatedBy": null,
    "IsActive": true
}
</code>```

Now i am changing the method name

```<code>    [Route("Get")]
    public IHttpActionResult Vendor()
    {
        var vendor = _ivs.GetVendorDetails();

        return Ok(vendor);
    }
</code>```

and hitting API using HttpGet

Now response i am having is:

{ "Message": "The requested resource does not support http method 'GET'." }

Body:
Just curios. I was looking at one of the web projects at internet.

And the code flow is like this:

[RoutePrefix("/person")]
public class PersonController : ApiController
{

    //....
    [Route("/register")]
    public IHttpACtionResult RegisterPerson(PersonDto personDto)
    {
        //....
    }
    //....
}

Did you notice the above code? There is no [HttpGet()] or [HttpPost()] specified. Yet the above code fails for a GET call but works for a POST call.

Any ideas how this method's HTTP-Verb is resolved ?

Note: I know that if a methodname starts with GET or POST, then correspondingly the method is invoked via HTTPGet or HTTPPost. But the method name here starts with Register....

Any ideas how this works?

Body:
It Depends on you Action Name if it matches any on the Http Verb. For example

In my API i used an Action to get vendors list, now see how it works:

    [Route("Get")]
    public IHttpActionResult GetVendor()
    {
        var vendor = _ivs.GetVendorDetails();

        return Ok(vendor);
    }

Now when i am hitting api using HttpPost I am getting following message:

{
    "Message": "The requested resource does not support http method 'POST'."
}

however if I am hitting API using HttpGet I am getting the data

 {
   "VendorId": "cc0e7ea1-4751-467b-b60b-be9b5202a511",

    "VendorCode": "Vend1",
    "VendorName": "testvendor",
    "AddressLine1": "AddressLine1",
    "AddressLine2": "AddressLine2",
    "AddressLine3": "AddressLine3",
    "City": "City                          ",
    "PINCode": "12345   ",
    "province": "province                      ",
    "Phone1": "Phone1",
    "Phone2": "Phone2",
    "Phone3": "Phone3",
    "PrimaryPhone": "Phone3    ",
    "CreatedDate": "2017-06-21T15:49:30.207",
    "CreatedBy": "e465e3e2-4156-434e-a444-f9a9626e1cf6",
    "UpdatedDate": "1900-01-01T00:00:00",
    "UpdatedBy": null,
    "IsActive": true
}

Now i am changing the method name

    [Route("Get")]
    public IHttpActionResult Vendor()
    {
        var vendor = _ivs.GetVendorDetails();

        return Ok(vendor);
    }

and hitting API using HttpGet

Now response i am having is:

{ "Message": "The requested resource does not support http method 'GET'." }