问:
Why Request and Response blank in listener when run jmx via command line
When I run JMX via command line, After completion of test when I load .JTL file to any listener , I can see data only in tab "Sample Result". Request and response both blank. Am I missing any configuration?

UPDATE

Already added following in file /bin/user.properties :

```<code>jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.url=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.samplerData=true
</code>```

答:
View results Tree listener is used for debugging purpose only. You can configure your user.properties file to see the response and request. But it is highly discouraged.

In your user.properties file add these config:

```<code>jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.url=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.samplerData=true
</code>```

Then restart your JMeter and collect your jtl file from non gui mode and then open the jtl file in gui mode. You will see your request and response there.

UPDATE:
You can also try this when you running your test:

```<code> ./jmeter -Jjmeter.save.saveservice.output_format=xml -Jjmeter.save.saveservice.response_data=true -Jjmeter.save.saveservice.samplerData=true -Jjmeter.save.saveservice.requestHeaders=true -Jjmeter.save.saveservice.url=true -Jjmeter.save.saveservice.responseHeaders=true -n -t your_test_plan.jmx -l result.jtl
</code>```

Now when you extract your result.jtl file, you will see the request, response etc.

It is highly discouraged because it will save huge data when there are so many requests. I would prefer to use Wireshark for this purpose.

Body:
When I run JMX via command line, After completion of test when I load .JTL file to any listener , I can see data only in tab "Sample Result". Request and response both blank. Am I missing any configuration?

UPDATE

Already added following in file /bin/user.properties :

jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.url=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.samplerData=true

Body:
View results Tree listener is used for debugging purpose only. You can configure your user.properties file to see the response and request. But it is highly discouraged.

In your user.properties file add these config:

jmeter.save.saveservice.output_format=xml
jmeter.save.saveservice.response_data=true
jmeter.save.saveservice.url=true
jmeter.save.saveservice.requestHeaders=true
jmeter.save.saveservice.samplerData=true

Then restart your JMeter and collect your jtl file from non gui mode and then open the jtl file in gui mode. You will see your request and response there.

UPDATE:
You can also try this when you running your test:

 ./jmeter -Jjmeter.save.saveservice.output_format=xml -Jjmeter.save.saveservice.response_data=true -Jjmeter.save.saveservice.samplerData=true -Jjmeter.save.saveservice.requestHeaders=true -Jjmeter.save.saveservice.url=true -Jjmeter.save.saveservice.responseHeaders=true -n -t your_test_plan.jmx -l result.jtl

Now when you extract your result.jtl file, you will see the request, response etc.

It is highly discouraged because it will save huge data when there are so many requests. I would prefer to use Wireshark for this purpose.


来源: stackexchange

问:
MS Access: How to Programmatically Add a Subform
Is there a way to programmatically add a subform to a form using Access VBA?  I have a temporary table that is generated dynamically when requested by the user.  If possible, I would like to create a form based on the temporary table and add it as a subform to a pre-existing form.</p>

答:
The best bet is to create the subform control and set the source object to either a table or a query.

```<code>Me.NameOfSubformControl.SourceObject = "Query.Query1"
Me.NameOfSubformControl.SourceObject = "Table.Temp"
</code>```

It is also possible to update the sql of a saved query to reference the new temp table.

ContentLicense: CC BY-SA 2.5

Body:
The best bet is to create the subform control and set the source object to either a table or a query.

Me.NameOfSubformControl.SourceObject = "Query.Query1"
Me.NameOfSubformControl.SourceObject = "Table.Temp"

It is also possible to update the sql of a saved query to reference the new temp table.


问:
Facebook pages plugin not showing on website
I am currently writing a website for a local charity run preschool and they would like their Facebook feed on the site.
For this I have used the Facebook Pages plugin. Unfortunately, following their instructions, I don't get anything on the website.

I'm not getting any errors in the console, and the Facebook URL is valid.
I understand to view this specific page the user needs to be logged in to Facebook, which I am, and I'm also able to view the page in the same browser with no problems.

The code I have is:

```<code><div id="fb-root"></div>
<script>
(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.8&appId=261857213845517";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</code>```

and the HTML is:

```<code>  < div class="fb-page" data-href="https://www.facebook.com/thevillageplaygroup/" data-tabs="timeline" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true">< /div>
</code>```

(note, I've added spaces in the div opening and closing tags as I couldn't get it to show up otherwise, sorry).

I've tried changing the Facebook URL to https://www.facebook.com/facebook as in the examples and that works so I'm presuming it's something to do with the page itself but I can't find any privacy or security settings which seem relevant.

EDIT
The page has security restrictions in place which mean the user needs to be logged in to Facebook and in the UK.
My account is able to access it ok through Facebook, just not using the plugin on the website

Any help is greatly appreciated.

答:
As pointed out by CBroe, it looks to be an issue with using the page feed for a page with privacy restrictions

“Facebook Pages with privacy restrictions cannot be embedded.”

I, wrongly, assumed that seeing as was logged into Facebook and could access the page that I would be able to see the feed. It seems Facebook disallow use of the plugin for pages with privacy restrictions regardless.

ContentLicense: CC BY-SA 4.0

Body:
I am currently writing a website for a local charity run preschool and they would like their Facebook feed on the site.
For this I have used the Facebook Pages plugin. Unfortunately, following their instructions, I don't get anything on the website.

I'm not getting any errors in the console, and the Facebook URL is valid.
I understand to view this specific page the user needs to be logged in to Facebook, which I am, and I'm also able to view the page in the same browser with no problems.

The code I have is:

and the HTML is:

(note, I've added spaces in the div opening and closing tags as I couldn't get it to show up otherwise, sorry).

I've tried changing the Facebook URL to https://www.facebook.com/facebook as in the examples and that works so I'm presuming it's something to do with the page itself but I can't find any privacy or security settings which seem relevant.

EDIT
The page has security restrictions in place which mean the user needs to be logged in to Facebook and in the UK.
My account is able to access it ok through Facebook, just not using the plugin on the website

Any help is greatly appreciated.

ContentLicense: CC BY-SA 3.0


问:
Java Search a .txt file for a given number with different format (100,50 or 100.50)
I want to search a given txt file for a number and return the line where it was found. This number can have different formats. It can be written with a , or . or something completely different. I know that the input number always looks like this: 100.50; 3424.00; 0.12 ...

My current code detects these numbers only if they are in a line without other characters.
The code divides the number into two parts (100.50 -> front: 100 and back: 50). Then I add the wildcard "." and use the method matches(front + "." + back)

How I can find the number if it is in a line that isn't just the number?

Thank you for your help!

```<code>private static int searchTotal(String pictureID, String value) throws IOException {

    int counter = 0;
    String front = value.substring(0, value.length() - 3);   //dividing the value into 100,50 -> 100 and 50
    String back = value.substring(value.length() - 2);

    BufferedReader br = new BufferedReader(
            new FileReader(pathTXTFiles + "/" + pictureID +".txt")); //input txt
    String s;

    while ((s = br.readLine()) != null) {
        counter++;
        if (s.matches(front + "." + back)) { //searching with the wildcard
            return counter;         //counter gives me the line of the searched number
        }
    }
    return 0;
}
</code>```

答:
You'll have to allow other characters before and after:

```<code>s.matches(".*"+front + "[.,]" + back+".*");
</code>```

otherwise matches will only return true if the line consists only of one decimal number.

Body:
I want to search a given txt file for a number and return the line where it was found. This number can have different formats. It can be written with a , or . or something completely different. I know that the input number always looks like this: 100.50; 3424.00; 0.12 ...

My current code detects these numbers only if they are in a line without other characters.
The code divides the number into two parts (100.50 -> front: 100 and back: 50). Then I add the wildcard "." and use the method matches(front + "." + back)

How I can find the number if it is in a line that isn't just the number?

Thank you for your help!

private static int searchTotal(String pictureID, String value) throws IOException {

    int counter = 0;
    String front = value.substring(0, value.length() - 3);   //dividing the value into 100,50 -> 100 and 50
    String back = value.substring(value.length() - 2);

    BufferedReader br = new BufferedReader(
            new FileReader(pathTXTFiles + "/" + pictureID +".txt")); //input txt
    String s;

    while ((s = br.readLine()) != null) {
        counter++;
        if (s.matches(front + "." + back)) { //searching with the wildcard
            return counter;         //counter gives me the line of the searched number
        }
    }
    return 0;
}

Body:
You'll have to allow other characters before and after:

s.matches(".*"+front + "[.,]" + back+".*");

otherwise matches will only return true if the line consists only of one decimal number.


问:
currency with comma as a seperator not dot in access
I am designing dataentry form and I am preparing tables. later I want to get report according to my data.
in the table one field is for amount of fee , it should be at most 8 digits. without decimal . (this amount can be in 3 currency EUR, USD, pound so I have another field with combo box for it)

what I did is, I chose currency as a data type and I chose standard as a format ( I dont want to see any $ or eruo sign as I said I have another field to define it thats why I chose standard) and changed decimal to 0 ( I dont have any decimal) and limited input mask to 9999999.
I want to have , (comma) as a seperator not (.)dot . how should I change dot to comma ?
I want to see 4,300 not 4.300

Go to the top of the pageReport Post

答:
If you environment doesn't change too much, you may get away with:</p>

```<code>Amount = 4300
CommaSeparatedAmount = Replace(Format(Amount, "#,##0"), ".", ",")

' Returns 4,300
</code>```

Body:
If you environment doesn't change too much, you may get away with:

Amount = 4300
CommaSeparatedAmount = Replace(Format(Amount, "#,##0"), ".", ",")

' Returns 4,300


问:
Regex : Looking for dots in a sentence except inside braquets
I'm looking for a regex to split a java string on "dots" in a sentence except if these dots are between brackets.
This is to say that in this example sentence :

```<code>word1.word2.word3[word4.word5[word6.word7]].word8
</code>```

I would like to split only the first two ones and the last one (just before "word8").

I managed to get to this regex :

```<code>\.(?![^\[]*?\])
</code>```

But it's not good enough as it also splits on the dot between words 4 and 5 :-(

Any idea to solve this particuliar case ?

答:
By looking at PerlMonks discussions I don't think the problem can be solved in Java by a single regex.

If you are okay with using multiple steps, then you could first remove all pairs of brackets (starting with the innermost) and then split the remaining string by dots:

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

    String str = "word1.word2.word3[word4.word5[word6.word7]].word8";
    final Pattern BRACKET_PAIR = Pattern.compile("\\[[^\\[\\]]+\\]");

    while (BRACKET_PAIR.matcher(str).find()) {
        str = BRACKET_PAIR.matcher(str).replaceFirst("");
    }

    for (String word: str.split("\\.")) {
        System.out.println(word);
    }
}
</code>```

Resulting in the output:

```<code>word1
word2
word3
word8
</code>```

Body:
I'm looking for a regex to split a java string on "dots" in a sentence except if these dots are between brackets.
This is to say that in this example sentence :

word1.word2.word3[word4.word5[word6.word7]].word8

I would like to split only the first two ones and the last one (just before "word8").

I managed to get to this regex :

\.(?![^\[]*?\])

But it's not good enough as it also splits on the dot between words 4 and 5 :-(

Any idea to solve this particuliar case ?

Body:
By looking at PerlMonks discussions I don't think the problem can be solved in Java by a single regex.

If you are okay with using multiple steps, then you could first remove all pairs of brackets (starting with the innermost) and then split the remaining string by dots:

public static void main (String[] args) {

    String str = "word1.word2.word3[word4.word5[word6.word7]].word8";
    final Pattern BRACKET_PAIR = Pattern.compile("\\[[^\\[\\]]+\\]");

    while (BRACKET_PAIR.matcher(str).find()) {
        str = BRACKET_PAIR.matcher(str).replaceFirst("");
    }

    for (String word: str.split("\\.")) {
        System.out.println(word);
    }
}

Resulting in the output:

word1
word2
word3
word8


问:
How to skip case statement in sql?
I am using a sql statement in Postgresql. Inside my statment is a case expression. How can I skip a row if case statement is not acceptet

Code:

```<code>SELECT *
FROM (SELECT a.link_id AS LinkID,

CASE
    WHEN a.From_Ref_Speed_Limit is null and a.To_Ref_Speed_Limit is not null THEN a.To_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit is not null and a.To_Ref_Speed_Limit is null THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit < a.To_Ref_Speed_Limit THEN a.To_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit > a.To_Ref_Speed_Limit THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit = a.To_Ref_Speed_Limit THEN a.To_Ref_Speed_Limit
    ELSE 0 --unknown
END as SpeedLimit,...
</code>```

If no condition inside my case statement is guilty it should skip the row and select the next one.
Like in case else it should not return NULL it should skip the row and should be go on with the next one.
How can I realize this?

答:
Your case can be replaced by greatest and lateral avoids a nested query:

```<code>select *
from
    a
    inner join lateral (
        select greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    ) s on s.SpeedLimit is not null
;
 from_ref_speed_limit | to_ref_speed_limit | speedlimit
----------------------+--------------------+------------
                    1 |                  0 |          1
                    0 |                  1 |          1
                      |                  1 |          1
                    0 |                    |          0
</code>```

For versions prior to 9.4 (no lateral) a nested query is necessary:

```<code>with a (From_Ref_Speed_Limit, To_Ref_Speed_Limit) as ( values
    (1,0),(0,1),(null,1),(0,null),(null,null)
)
select *
from (
    select a.*, greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    from a
) s
where s.SpeedLimit is not null
;
</code>```

Title: How to skip case statement in sql?

Body:
I am using a sql statement in Postgresql. Inside my statment is a case expression. How can I skip a row if case statement is not acceptet

Code:

SELECT *
FROM (SELECT a.link_id AS LinkID,

CASE
    WHEN a.From_Ref_Speed_Limit is null and a.To_Ref_Speed_Limit is not null THEN a.To_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit is not null and a.To_Ref_Speed_Limit is null THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit  a.To_Ref_Speed_Limit THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit = a.To_Ref_Speed_Limit THEN a.To_Ref_Speed_Limit
    ELSE 0 --unknown
END as SpeedLimit,...

If no condition inside my case statement is guilty it should skip the row and select the next one.
Like in case else it should not return NULL it should skip the row and should be go on with the next one.
How can I realize this?

Body:
Your case can be replaced by greatest and lateral avoids a nested query:

select *
from
    a
    inner join lateral (
        select greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    ) s on s.SpeedLimit is not null
;
 from_ref_speed_limit | to_ref_speed_limit | speedlimit
----------------------+--------------------+------------
                    1 |                  0 |          1
                    0 |                  1 |          1
                      |                  1 |          1
                    0 |                    |          0

For versions prior to 9.4 (no lateral) a nested query is necessary:

with a (From_Ref_Speed_Limit, To_Ref_Speed_Limit) as ( values
    (1,0),(0,1),(null,1),(0,null),(null,null)
)
select *
from (
    select a.*, greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    from a
) s
where s.SpeedLimit is not null
;


问:
initial= not working on Form inputs
I have a simple search form on my page /.

```<code>class SearchForm(Form):
    query = CharField(max_length=256,
                      label="Search",
                      required=False,
                      widget=TextInput(attrs={'placeholder': 'Search …',
                                              'class': 'form-control'}))

    page = IntegerField(min_value=8, initial=1, widget=HiddenInput())
    sort = CharField(max_length=16, initial="id", widget=HiddenInput())
    order = CharField(max_length=4, initial="asc", widget=HiddenInput())
</code>```

My (simplified) view is this:

```<code>def search(request):
    search_form = SearchForm(request.GET)
    return render(request, "search.html", {'search_form': search_form})
</code>```

My goal is to have search_form.cleaned_data['<FIELD>'] return the initial values I set in the class SearchForm, without having to check wether they are exist None or are empty ''.

Unfortunately my code does not work as the input elements are renderd like this:

```<code><input id="id_page" name="page" type="hidden" />
<input id="id_sort" maxlength="16" name="sort" type="hidden" />
<input id="id_order" maxlength="4" name="order" type="hidden" />
</code>```

Any ideas?

答:
you need to specify the initial parameter when instantiating the form to get the value. Using the initial in form declaration is only for unbound form.
try:</p>

```<code>search_form = SearchForm(request.GET, initial={
    'page': 1,
    'sort': 'id',
    'order': 'asc'
})
</code>```

Title: initial= not working on Form inputs

Body:
I have a simple search form on my page /.

class SearchForm(Form):
    query = CharField(max_length=256,
                      label="Search",
                      required=False,
                      widget=TextInput(attrs={'placeholder': 'Search …',
                                              'class': 'form-control'}))

    page = IntegerField(min_value=8, initial=1, widget=HiddenInput())
    sort = CharField(max_length=16, initial="id", widget=HiddenInput())
    order = CharField(max_length=4, initial="asc", widget=HiddenInput())

My (simplified) view is this:

def search(request):
    search_form = SearchForm(request.GET)
    return render(request, "search.html", {'search_form': search_form})

My goal is to have search_form.cleaned_data['<FIELD>'] return the initial values I set in the class SearchForm, without having to check wether they are exist None or are empty ''.

Unfortunately my code does not work as the input elements are renderd like this:

<input id="id_page" name="page" type="hidden" />
<input id="id_sort" maxlength="16" name="sort" type="hidden" />
<input id="id_order" maxlength="4" name="order" type="hidden" />

Any ideas?

Body:
you need to specify the initial parameter when instantiating the form to get the value. Using the initial in form declaration is only for unbound form.
try:

search_form = SearchForm(request.GET, initial={
    'page': 1,
    'sort': 'id',
    'order': 'asc'
})


问:
Bootstrap tooltip doesn't show style of the tooltip, only data
Trying to make Bootstrap show the tooltip function, I have followed exactly as Bootstrap DOC about Tooltips and declare my attribute and properties. when I hover over the text the data Some tooltip text! shows as there is alt="" function only, but not in style as Bootstrap mentioned in their document.

Steps I have taken to resolve this issue:

Include tooltip.js from external CDN

activate tooltip throw

Add Google API of jQuery (I know is not neccessery)

check if the page is loading the Bootstrap CDN and external ones (All Do!)

Header HTML Markup

```<code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/style.css" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</code>```

HTML Markup

```<code><a href="#" data-toggle="tooltip" title="Some tooltip text!">Hover over me</a>
</code>```

Here is an image of how it shows.

答:
Remember also that Bootstrap Tooltip don't like jQuery UI (there are a few names conflict and 'tooltip' is one of them).

The solution is changing the script loading order: jQuery UI first, bootstrap.js after.

Body:
Trying to make Bootstrap show the tooltip function, I have followed exactly as Bootstrap DOC about Tooltips and declare my attribute and properties. when I hover over the text the data Some tooltip text! shows as there is alt="" function only, but not in style as Bootstrap mentioned in their document.

Steps I have taken to resolve this issue:

Include tooltip.js from external CDN

activate tooltip throw

Add Google API of jQuery (I know is not neccessery)

check if the page is loading the Bootstrap CDN and external ones (All Do!)

Header HTML Markup

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="css/style.css" rel="stylesheet">

HTML Markup

Hover over me

Here is an image of how it shows.


问:
Set focus on textfield when un-focused
I want a text field to always be focused. When they click out of the textfield, I want the focus to go back into the textfield.

How would I accomplish this with jQuery?

```<code>$('input').focus();

$('input').**unfocused?**( function($) { $('input').focus();} );
</code>```

答:
Bind to get the change event, and check if focus must be forced to this input if so, insert some data in the document. $(document).data(‘_force_focus’, e.target)

```<code>$('input.force').bind('change', function(e) {
        if( need_force_focus() ) {
                $(document).data('_force_focus', e.target);
        } else {
                $(document).removeData('_force_focus');
        }
   });
</code>```

Now on the document bind to the focusin event, testing if document have the “_force_focus” data. If so set the focus to the value. It’s important prevent the focusin retrigger by testing against e.target

```<code>$(document).bind('focusin', function (e) {
     var t = $.data(document, '_force_focus');
             if( t && e.target !== t ) {
                     $(t).trigger('focus');
                     return false;
             }
             return true;
     });
</code>```

Title: Set focus on textfield when un-focused

Body:
I want a text field to always be focused. When they click out of the textfield, I want the focus to go back into the textfield.

How would I accomplish this with jQuery?

$('input').focus();

$('input').**unfocused?**( function($) { $('input').focus();} );

Body:
Bind to get the change event, and check if focus must be forced to this input if so, insert some data in the document. $(document).data(‘_force_focus’, e.target)

$('input.force').bind('change', function(e) {
        if( need_force_focus() ) {
                $(document).data('_force_focus', e.target);
        } else {
                $(document).removeData('_force_focus');
        }
   });

Now on the document bind to the focusin event, testing if document have the “_force_focus” data. If so set the focus to the value. It’s important prevent the focusin retrigger by testing against e.target

$(document).bind('focusin', function (e) {
     var t = $.data(document, '_force_focus');
             if( t && e.target !== t ) {
                     $(t).trigger('focus');
                     return false;
             }
             return true;
     });


问:
Using Django Restframework to create Single User Sign On
I am currently using the Django Rest Framework.
However an external cloud service provider would require a SSO.

I was browsing through some answers but didn't get anything helpful.

I can authenticate the user for the api

```<code>curl -X POST -d "email=useremail&password=password" 127.0.0.1:8000
</code>```

I get the token back.
Now i can make api requests.

I read something about using SAML, however all the packages are outdated.

I was thinking about rewriting the authentication() function, to take in the username and the token to verify the user and redirect him to the App Dashboard.

To clarify an external Cloud Service is trying to log in a user into our APP with a direct link.

I can't find a nice, clean approach to use here.

I don't think i should use something like request.GET.get('username') request.GET.get('password') because i don't think that will be very secure.

On the other hand the curl call is pretty much doing the same thing to get the token.

Any Advice, Ideas?

答:
Did you take a look at the python-saml library?
https://github.com/onelogin/python-saml</p>

Body:
I am currently using the Django Rest Framework.
However an external cloud service provider would require a SSO.

I was browsing through some answers but didn't get anything helpful.

I can authenticate the user for the api

curl -X POST -d "email=useremail&password=password" 127.0.0.1:8000

I get the token back.
Now i can make api requests.

I read something about using SAML, however all the packages are outdated.

I was thinking about rewriting the authentication() function, to take in the username and the token to verify the user and redirect him to the App Dashboard.

To clarify an external Cloud Service is trying to log in a user into our APP with a direct link.

I can't find a nice, clean approach to use here.

I don't think i should use something like request.GET.get('username') request.GET.get('password') because i don't think that will be very secure.

On the other hand the curl call is pretty much doing the same thing to get the token.

Any Advice, Ideas?


问:
wxPython caret move event
What event is called when the caret inside a TextCtrl / Styled TextCtrl has its position changed? I need to bind the event to show in the status bar, the current position of the caret.</p>

答: In order to know when mouse is placed inside any window you can bind wx.EVT_ENTER_WINDOW (see here)</p>

Title: wxPython caret move event


问:
Conditionally apply a CSS
I have a style defined that needs to be applied only if there is an icon, but not if there isn't.

The html structure with an icon is as follows:

```<code><li class="g-menu-item g-menu-item-226 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/services/visas">
    <i class="fa fa-id-badge"></i>
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Visas</span>
    </span>
  </a>
</li>
</code>```

The structure without an icon is as follows:

```<code><li class="g-menu-item g-menu-item-232 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/destinations/australia/adelaide">
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Adelaide</span>
    </span>
  </a>
</li>
</code>```

The SCSS I have worked fine on items with an icon. It moves the span with the class g-menu-item-title to the right by 1.25rem and up by 1rem:

```<code>.aside-nav {
  .g-menu-item-container {
    .g-menu-item-content {
      margin-left: 1.25rem !important;
      margin-top: -1rem !important;
    }
  }
}
</code>```

However, when there is no icon, it makes the menu items in the sidebar squished into each other.

How do I change this SCSS so that it only applies to menu items in the aside where the item has an icon, but not when there isn't an icon.

答:
You can use an Adjacent sibling selector,

It'll let you target an element that is next to another element:

i + .g-menu-item-content {
   margin-left: 1.25rem !important;
   margin-top: -1rem !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<ul>
<li class="g-menu-item g-menu-item-232 g-menu-item-type-component g-standard">

    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Adelaide</span>
    </span>

</li>

<li class="g-menu-item g-menu-item-226 g-menu-item-type-component g-standard">

    <i class="fa fa-id-badge"></i>
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Visas</span>
    </span>

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

Title: Conditionally apply a CSS

Body:
I have a style defined that needs to be applied only if there is an icon, but not if there isn't.

The html structure with an icon is as follows:

      Visas

The structure without an icon is as follows:

      Adelaide

The SCSS I have worked fine on items with an icon. It moves the span with the class g-menu-item-title to the right by 1.25rem and up by 1rem:

.aside-nav {
  .g-menu-item-container {
    .g-menu-item-content {
      margin-left: 1.25rem !important;
      margin-top: -1rem !important;
    }
  }
}

However, when there is no icon, it makes the menu items in the sidebar squished into each other.

How do I change this SCSS so that it only applies to menu items in the aside where the item has an icon, but not when there isn't an icon.

Body:
You can use an Adjacent sibling selector,

It'll let you target an element that is next to another element:

i + .g-menu-item-content {
   margin-left: 1.25rem !important;
   margin-top: -1rem !important;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<ul>
<li class="g-menu-item g-menu-item-232 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/destinations/australia/adelaide">
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Adelaide</span>
    </span>
  </a>
</li>

<li class="g-menu-item g-menu-item-226 g-menu-item-type-component g-standard">
  <a class="g-menu-item-container" href="/en/services/visas">
    <i class="fa fa-id-badge"></i>
    <span class="g-menu-item-content">
      <span class="g-menu-item-title">Visas</span>
    </span>
  </a>
</li>
</ul>


问:
Edittext password is always showing the password
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

```<code><EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>
</code>```

drawable file ss:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />
</code>```

Complete Layout:

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>
</code>```

答:
I also encountered this issue what work for me is:

I added this xml property to my EditText and it works fine:

```<code>android:singleLine="true"
</code>```

I know its deprecated, but android:maxLines="1" not working although its the replacement for singleLine.

Body:
I have an EditText to enter the password and i set inputType as "textPassword". But when i run it in app or emulator the password is visible. Why it is showing password instead of dots?

<EditText
 android:id="@+id/etPassword"
 android:layout_width="match_parent"
 android:inputType="textPassword"
 android:layout_height="wrap_content"
 android:hint="@string/Password"
 android:layout_marginBottom="10dp"
 android:maxLength="15"
 android:background="@drawable/ss"/>

drawable file ss:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="10dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<solid android:color="#ffffffff"/>
<stroke android:width="1dp" android:color="#CCCCCC" />

Complete Layout:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:background="#ffffffff"
        android:gravity="center_vertical" >

        <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/foodstall"
         android:layout_gravity="center"
         android:layout_marginBottom="10dp"/>

        <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:background="#ffffffff">

        <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/Username"
        android:maxLength="15"
        android:background="@drawable/ss"
        android:layout_marginBottom="10dp"/>

        <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:inputType="textPassword"
        android:layout_height="wrap_content"                                                     android:hint="@string/Password"
        android:layout_marginBottom="10dp"
        android:maxLength="15"
        android:background="@drawable/ss"
                android:text="askdjhkashdjasdksakdkaskdhkashkdhkashdkjhakshdkjhaskhdkj"/>

        <Button
        android:id="@+id/bLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_activity_login"
        android:background="@color/button"
        android:textColor="#ffffffff"
        android:layout_weight="1" />

        </LinearLayout>

        <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearlayout"
        android:background="@drawable/ss"
        android:layout_marginTop="10dp">

        <TextView
        android:id="@+id/tvRegisterLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/Newuser"
        android:gravity="center"
        android:layout_weight="1"
        android:textStyle="bold"/>

        <TextView
        android:id="@+id/fpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/title_activity_forgotpass"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"/>

        </LinearLayout>

        </LinearLayout>

Body:
I also encountered this issue what work for me is:

I added this xml property to my EditText and it works fine:

android:singleLine="true"

I know its deprecated, but android:maxLines="1" not working although its the replacement for singleLine.


问:
How to retrieve session value in jsp using struts2?
I want to store session value in String object in jsp using struts2.

FILE : header.jsp

```<code><%
name = (String)session.getAttribute("name");
/* name = (String)request.getSession().getAttribute("name"); */
if(name.equals("cmp")
{  // show something   }
else if(name.equals("emp")
{  // show something   }
else
{  // show something   }
%>
</code>```

When i try to get session value using this syntax i get error : HTTP Status 500 - java.lang.NullPointerException

FILE : loginAction.java

```<code>public class LoginAction extends ActionSupport implements SessionAware
{
    private Map<String, Object> session;
    private String name;
    //setters and getters
    public String execute()
    {
        session.put("name", name);
        return SUCCESS;
    }
}
</code>```

I set name value based on the user enter name in login page.

Based on the user type i change my header view.

So suggest me how can i get value from the session in jsp and then store into String object.

答:
FILE : header.jsp

```<code><s:if test="#session.role=='cmp'">
    // show something
<s:if>
<s:elseif test="#session.role=='emp'">
    // show something
<s:elseif>
<s:else>
    // show something
<s:else>
</code>```

Body:
I want to store session value in String object in jsp using struts2.

FILE : header.jsp

<%
name = (String)session.getAttribute("name");
/* name = (String)request.getSession().getAttribute("name"); */
if(name.equals("cmp")
{  // show something   }
else if(name.equals("emp")
{  // show something   }
else
{  // show something   }
%>

When i try to get session value using this syntax i get error : HTTP Status 500 - java.lang.NullPointerException

FILE : loginAction.java

public class LoginAction extends ActionSupport implements SessionAware
{
    private Map<String, Object> session;
    private String name;
    //setters and getters
    public String execute()
    {
        session.put("name", name);
        return SUCCESS;
    }
}

I set name value based on the user enter name in login page.

Based on the user type i change my header view.

So suggest me how can i get value from the session in jsp and then store into String object.

Body:
FILE : header.jsp

<s:if test="#session.role=='cmp'">
    // show something
<s:if>
<s:elseif test="#session.role=='emp'">
    // show something
<s:elseif>
<s:else>
    // show something
<s:else>


问:
spring-boot - turn off console logging
Want to configure a spring-boot (1.3.5) application to send log-output only to a file -- turn off the console.

It looks very easy, according to the docs:
howto-logging.html -- section
  § 72.1.1 Configure logback for file only output

But I just cannot get this to work -- it still logs both to file and console, whatever I try.
Been googling for hours, but cannot find any suggestion that actually works.

Any clue what the issue might be?

EDIT: Please dont mark this as "duplicate" -- I have read them all -- and none of the suggested solutions work here.

答: Setting logging.pattern.console= (value is left blank) in application.properties, works for me.

Title: spring-boot - turn off console logging


问:
Mozilla extension namespace: How to differentiate between my function and functions from other packages?
I am developing a Firefox (FF) extension and am calling a function when a particular button on FF is pressed. Sometimes, FF is not able to find my function from my script file even if it is there. Instead, it searches for it in the browser extension and throws an error.

In general, how do I use namespace before my function that will clearly differentiate it from functions of perhaps the same name in other packages.

For e.g.: Is there something like:

```<code><script type="application/javascript" src="chrome://mythird/content/script.js"/>
<statusbar id="status-bar">
    <statusbarpanel id="mythird-statusbarpanel" label="mythird" onclick="chrome://mythird/myalert();"/>
</statusbar>
</code>```

instead of just:

```<code>    <statusbarpanel id="mythird-statusbarpanel" label="mythird" onclick="myalert();"/>
</code>```

答:
You can use a normal object as namespace of your functions. Give the object the name of your extension (which should be unique and awesome) and you should be pretty save.

In your script file:

```<code>var gYourExtensionName = {};

gYourExtensionName.myalert = function(){/*...*/};
</code>```

and in XUL:

```<code><script type="application/javascript" src="chrome://mythird/content/script.js"/>
<statusbar id="status-bar">
    <statusbarpanel id="mythird-statusbarpanel"
                    label="mythird"
                    onclick="gYourExtensionName.myalert()" />
</statusbar>
</code>```

You should also read: Firefox Extensions: Global Namespace Pollution

Body:
You can use a normal object as namespace of your functions. Give the object the name of your extension (which should be unique and awesome) and you should be pretty save.

In your script file:

var gYourExtensionName = {};

gYourExtensionName.myalert = function(){/*...*/};

and in XUL:

<script type="application/javascript" src="chrome://mythird/content/script.js"/>
<statusbar id="status-bar">
    <statusbarpanel id="mythird-statusbarpanel"
                    label="mythird"
                    onclick="gYourExtensionName.myalert()" />
</statusbar>

You should also read: Firefox Extensions: Global Namespace Pollution


问:
angular 2 sort and filter
In Angularjs 1 it is possible to sort and filter the following way:

{{friend.name}}

```

But I could not find any examples of how to do this in Angularjs 2.0. My question is how to sort and filter in Angularjs 2.0? If it is still not supported, does anyone know when or if it will be put into Angularjs 2.0?

答:
It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1. </p>

<p>You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better. </p>

Title: angular 2 sort and filter

Body:
In Angularjs 1 it is possible to sort and filter the following way:

{{friend.name}}

But I could not find any examples of how to do this in Angularjs 2.0. My question is how to sort and filter in Angularjs 2.0? If it is still not supported, does anyone know when or if it will be put into Angularjs 2.0?

Body:
It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.

You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.


问:
Close multiple popup windows using only one button
I have a small problem.
I am making a website that, when a button is pressed, creates 2 popup windows. One shows one image and the other shows a bunch of controls, including two buttons. I want the buttons to close both popups at the same time.

I've tried to attribute the window to a variable, but then, upon trying to close it, I'm shown "Uncaught TypeError: Cannot read property 'close' of undefined", but the variable is defined.

This is making me go out of my mind, and it's probably something quite simple.
Can anyone help, please?

EDIT: A very basic form of the code is here:

```<code><button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
var myWindow;

function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin() {
    myWindow.close();
}
</script>
</code>```

https://jsfiddle.net/tbd7k511/1/

答:
Just call ```myWindow2.close();``` in your ```closeWin()```

Javascript

```<code><button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
  var myWindow;
  var MyWindow2;

  function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow2 = window.open("", "myWindow2", "width=200,height=200");
  }

  function closeWin() {
    myWindow.close();
    myWindow2.close();
  }

</script>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
</code>```

Body:
I have a small problem.
I am making a website that, when a button is pressed, creates 2 popup windows. One shows one image and the other shows a bunch of controls, including two buttons. I want the buttons to close both popups at the same time.

I've tried to attribute the window to a variable, but then, upon trying to close it, I'm shown "Uncaught TypeError: Cannot read property 'close' of undefined", but the variable is defined.

This is making me go out of my mind, and it's probably something quite simple.
Can anyone help, please?

EDIT: A very basic form of the code is here:

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

https://jsfiddle.net/tbd7k511/1/

Body:
Just call
myWindow2.close();
 in your
closeWin()

Javascript

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>

<script>
  var myWindow;
  var MyWindow2;

  function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow2 = window.open("", "myWindow2", "width=200,height=200");
  }

  function closeWin() {
    myWindow.close();
    myWindow2.close();
  }

</script>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>


问:
Navigating Programmatically in React-Router v4
I couldn't wait and I jumped into using the latest alpha version of react-router v4. The all-new <BrowserRouter/> is great in keeping your UI in sync with the browser history, but how do I  use it to navigate programmatically?

答:
Using withRouter will add router properties to you component, then you can access the history and use push like you did with v3:

import React from 'react';
import { withRouter } from 'react-router-dom';

class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      input: '',
    };

    this._submit = this._submit.bind(this);
  }

  render() {
    return (
      <form onSubmit={this._submit}>
        <input type="text" onChange={(event) => this.setState({input: event.target.value})}/>

        <button type="submit">Submit</button>
      </form>
    );
  }

  _submit(event) {
    event.preventDefault();

    this.props.history.push(`/theUrlYouWantToGoTo`);
  }
}

export default withRouter(Form);
```


问:
Unable to push to github: repository not found
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

```<code>> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found
</code>```

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

```<code>[credential]
    helper = manager
</code>```

I'm running on Windows 10, git version 2.10.2.windows.1.

答:
You need to specify what branch you want to push to.

-git push origin branchName

GitHub Docs: Pushing to a remote

Body:
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

[credential]
    helper = manager

I'm running on Windows 10, git version 2.10.2.windows.1.


问:
Laravel get file content
```<code>Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});
</code>```

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

答:
You can go with the absolute path</p>

```<code>\Illuminate\Support\Facades\File::get(base_path() . '/storage/app/marquee.json');
</code>```

Title: Laravel get file content

Body:
Route::get('marquee', function(){
    echo  File::get('\storage\app\marquee.json');
});

I have a json file place inside storage/app

My question is how can I read this content from controller or route?

Body:
You can go with the absolute path

\Illuminate\Support\Facades\File::get(base_path() . '/storage/app/marquee.json');


问:
Must logins be a https page
Several security experts have said in the past that the login page should be on ssl https. So what if my login is a block that's displayed on all pages. Does that mean that my entire website has to be https?

I read it's possible to put the form on http but post it to https, but I read someone saying that it can be exploited with a man in the middle attack. Can someone confirm this? I have a 100 point bounty for someone who can confirm this (and help me with a practical answer how to securely solve this). My login form is on every page, do I need to make the whole website on https? Please feel free to question anything I said here. They're only things I read but don't have experience with and didn't try it myself.

Edit: to those who asked, when I was posting the question, I tried setting the bounty but the system wouldn't let me. I checked the FAQ and saw that bounty can be posted after 2 days from posting the question. That's why you see no bounty yet. But I will not select an answer until I set a bounty in 2 days. Sorry for any confusion.

答:
I read it's possible to put the form on http but post it to https, but I read someone saying that it can be exploited with a man in the middle attack. Can someone confirm this?

Yes. The form is served up over HTTP, so a man in the middle could inject changes to it (e.g. so it sends credentials to their own server before the form submits).

a practical answer how to securely solve this

If security really matters — use HTTPS for the entire site. Even after the password has been sent, if you go back to HTTP then the cookie can be stolen (see Firesheep)

If security doesn't matter that much, then don't put the login form on every page. Just have a link to a login page instead.

Title: Must logins be a https page


问:
How to access the internal properties of one assembly from another assembly without using InternalVisibleTo?
Without using the signing key (.snk) is there a way to access the internal property of one assembly from another assembly ?

Thanks in advance.
Arun

答:
Reflection when used through strongly typed delegates isn't TOO much slow... (it should be just a little slower than virtual method calls):

Example:

```<code>public class MyClass
{
    internal int MyProperty { get; set; }
}
</code>```

And then:

```<code>public static class MyClassAccessor
{
    public static readonly Func<MyClass, int> GetMyProperty;
    public static readonly Action<MyClass, int> SetMyProperty;

    static MyClassAccessor()
    {
        var prop = typeof(MyClass).GetProperty("MyProperty", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        GetMyProperty = (Func<MyClass, int>)Delegate.CreateDelegate(typeof(Func<MyClass, int>), prop.GetMethod);
        SetMyProperty = (Action<MyClass, int>)Delegate.CreateDelegate(typeof(Action<MyClass, int>), prop.SetMethod);
    }
}
</code>```

And you use like:

```<code>var mc = new MyClass();
MyClassAccessor.SetMyProperty(mc, 5);
Console.WriteLine(MyClassAccessor.GetMyProperty(mc));
</code>```

Body:
Reflection when used through strongly typed delegates isn't TOO much slow... (it should be just a little slower than virtual method calls):

Example:

public class MyClass
{
    internal int MyProperty { get; set; }
}

And then:

public static class MyClassAccessor
{
    public static readonly Func<MyClass, int> GetMyProperty;
    public static readonly Action<MyClass, int> SetMyProperty;

    static MyClassAccessor()
    {
        var prop = typeof(MyClass).GetProperty("MyProperty", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        GetMyProperty = (Func<MyClass, int>)Delegate.CreateDelegate(typeof(Func<MyClass, int>), prop.GetMethod);
        SetMyProperty = (Action<MyClass, int>)Delegate.CreateDelegate(typeof(Action<MyClass, int>), prop.SetMethod);
    }
}

And you use like:

var mc = new MyClass();
MyClassAccessor.SetMyProperty(mc, 5);
Console.WriteLine(MyClassAccessor.GetMyProperty(mc));


问:
C- gethostbyaddr & Valgrind
For some reason valgrind keeps throwing the following error:

```<code>==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)
</code>```

Here is the way I'm doing it. Any reasons why this is happening? Thanks

```<code>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}
</code>```

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10

答:
inet_addr doesn't always return a simple unsigned int.  It returns an in_addr_t (or an in_addr depending on your flavor of C headers, mine's linux 2.6.31 / glib 2.0).  On my system, in_addr_t is actually a 128 bits (16 bytes) because inet_addr can return an IPv6 address.

Likewise, gethostbyaddr takes an in_addr_t, not an unsigned int.  This is almost certainly your problem.  Change the type of ip to inet_addr_t and change the corresponding sizeof, and pay more attention to compiler warnings next time.

```<code>struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
host = gethostbyaddr (&ip, sizeof(ip), AF_INET);
if (host == NULL) return NULL;
return strdup(host->h_name);
</code>```

Title: C- gethostbyaddr & Valgrind

Body:
For some reason valgrind keeps throwing the following error:

==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)

Here is the way I'm doing it. Any reasons why this is happening? Thanks

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10

Body:
inet_addr doesn't always return a simple unsigned int.  It returns an in_addr_t (or an in_addr depending on your flavor of C headers, mine's linux 2.6.31 / glib 2.0).  On my system, in_addr_t is actually a 128 bits (16 bytes) because inet_addr can return an IPv6 address.

Likewise, gethostbyaddr takes an in_addr_t, not an unsigned int.  This is almost certainly your problem.  Change the type of ip to inet_addr_t and change the corresponding sizeof, and pay more attention to compiler warnings next time.

struct hostent *host;
in_addr_t ip = inet_addr(ipaddress);
host = gethostbyaddr (&ip, sizeof(ip), AF_INET);
if (host == NULL) return NULL;
return strdup(host->h_name);


问:
using http post to check session and redirect
I am still new to angularjs and trying to understand the concept. i have a working solution but i just need to make sure this is a secure way of doing it. i have a $rootScope.$on('$stateChangeStart', function(){} which sends a http post to a php file, this checks to see if it has session data and returns "1" being true and "0" being false. if false then i perform a $state.go('login'); which redirects to login page. This works exactly how i wish it to but just would like some further knowledge if this is secure enough.

答:
This works exactly how i wish it to but just would like some further knowledge if this is secure enough.

When working with javascript or angular or any other SPA frameworks, forget about sessions. It's better using token based authentication system that provides you a lot of benefits, more security and more scalability.

There is a very good example here. It covers almost all aspects of token base auth that you need. Although it's for ionic, but doesn't matter. Ionic is built on the top of the angular.


问:
how to convert conotur co-ordinates to complex format(x+y*j0)
contour finding of segmented image of circle results in contour which is not circular along with boundary contour, contour finding is done using this:

contours = skimg.measure.find_contours(edges,0.8)

how to convert these coordinates into complex format.

答:
what I have found about Fourier descriptors :

http://fourier.eng.hmc.edu/e161/lectures/fd/node1.html

skimg.measure.find_contours return a list of array with coordinates [x, y], so you already have your coordinate because you will use it in the complex form as :

x+y*i

After depends how you will use it in your next calculus, but, for example, if you want to read all the y values :

```<code>for i in range(len(contours)):
    for j in range(len(contours[i])):
        print contours[i][j][1]
</code>```

you can also use cmath to handle complex number:

https://docs.python.org/2/library/cmath.html

you can also use complex :

```<code>>>> x=4.90
>>> y=7.890
>>> CoordComplex=complex(x,y)
>>> CoordComplex
(4.9+7.89j)
</code>```

or to creat a list of complex from list of arrays :

```<code>compCoord=[]
for i in range(len(contours)):
    for j in range(len(contours[i])):
        compCoord.append(complex(contours[i][j][0], contours[i][j])[1])
</code>```

Body:
what I have found about Fourier descriptors :

http://fourier.eng.hmc.edu/e161/lectures/fd/node1.html

skimg.measure.find_contours return a list of array with coordinates [x, y], so you already have your coordinate because you will use it in the complex form as :

x+y*i

After depends how you will use it in your next calculus, but, for example, if you want to read all the y values :

for i in range(len(contours)):
    for j in range(len(contours[i])):
        print contours[i][j][1]

you can also use cmath to handle complex number:

https://docs.python.org/2/library/cmath.html

you can also use complex :

>>> x=4.90
>>> y=7.890
>>> CoordComplex=complex(x,y)
>>> CoordComplex
(4.9+7.89j)

or to creat a list of complex from list of arrays :

compCoord=[]
for i in range(len(contours)):
    for j in range(len(contours[i])):
        compCoord.append(complex(contours[i][j][0], contours[i][j])[1])


问:
How to count rows with specific value?
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

```<code>SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId
</code>```

答:
simple if you have value 0 or 1 in Goal

```<code>sum(Goal) AS Goal
</code>```

OR

```<code> COUNT(case when Goal <> 0 then 1 end) AS Goal
</code>```

Title: How to count rows with specific value?

Body:
I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 1?

SELECT
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore,
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM
    Match A
INNER JOIN
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId

Body:
simple if you have value 0 or 1 in Goal

sum(Goal) AS Goal

OR

 COUNT(case when Goal <> 0 then 1 end) AS Goal


问:
How can I use PHP Simple HTML DOM to get img src?
I Would like to scrape images from this page http://www.ikea.com/us/en/catalog/products/S59163189/

The markup for displaying the images are like this:

```<code> <div id="moreImgThumbContainer">
    <div class="imageThumb" id="imageThumb_0">
        <a href="javascript:void(0);" id="imageThumbLink_0" class="active">
            <img src="/PIAimages/0386819_PE559167_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_0" style="opacity: 10;">
        </a>
    </div>

 <div class="imageThumb" id="imageThumb_1">
        <a href="javascript:void(0);" id="imageThumbLink_1">
            <img src="/PIAimages/0449646_PE599007_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_1" style="opacity: 0.8;">
        </a>
    </div>
</div>
</code>```

I tried with the html code, in a single page, it works.

```<code>foreach($html->find('img[id^=imgID]') as $img_link){
         $img_array[] = 'http://www.ikea.com'.$img_link->src;
         $images = implode(';', $img_array);
}
</code>```

How can I get src of each image in PHP html dom parser using this api http://simplehtmldom.sourceforge.net/ ?

Edit: I think that i found the cause of the problem, the images are loading with ajax and takes time to load.

Is there a solution to scrape them?

Any help please!

答:
Try with jquery and Array#map function

var d  = $('.imageThumb').map(function (){
c =  $(this).children('a').children('img').attr('src');
return c;
}).get()

console.log(d.join(';'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moreImgThumbContainer">
    <div class="imageThumb" id="imageThumb_0">

            <img src="/PIAimages/0386819_PE559167_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_0" style="opacity: 10;">

    </div>

    <div class="imageThumb" id="imageThumb_1">

            <img src="/PIAimages/0449646_PE599007_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_1" style="opacity: 0.8;">

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

Body:
I Would like to scrape images from this page http://www.ikea.com/us/en/catalog/products/S59163189/

The markup for displaying the images are like this:

I tried with the html code, in a single page, it works.

foreach($html->find('img[id^=imgID]') as $img_link){
         $img_array[] = 'http://www.ikea.com'.$img_link->src;
         $images = implode(';', $img_array);
}

How can I get src of each image in PHP html dom parser using this api http://simplehtmldom.sourceforge.net/ ?

Edit: I think that i found the cause of the problem, the images are loading with ajax and takes time to load.

Is there a solution to scrape them?

Any help please!

Body:
Try with jquery and Array#map function

var d  = $('.imageThumb').map(function (){
c =  $(this).children('a').children('img').attr('src');
return c;
}).get()

console.log(d.join(';'))

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moreImgThumbContainer">
    <div class="imageThumb" id="imageThumb_0">
        <a href="javascript:void(0);" id="imageThumbLink_0" class="active">
            <img src="/PIAimages/0386819_PE559167_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_0" style="opacity: 10;">
        </a>
    </div>

    <div class="imageThumb" id="imageThumb_1">
        <a href="javascript:void(0);" id="imageThumbLink_1">
            <img src="/PIAimages/0449646_PE599007_S3.JPG" onclick="irwStatThumbImgClickedFromPIP();" onmouseover="addOpacityEffect(this.id);" onmouseout="rmvOpacityEffect(this.id);" id="imgID_1" style="opacity: 0.8;">
        </a>
    </div>
</div>


问:
JavaScript Event Listeners for when the DOM changes
I'm writing a Mozilla Firefox Extension (Javascript without the BS of having to identify if it's IE or Firefox), where I find myself stuck in the following situation. On a page load, I add event listeners like so:
extension.addEventListener("DOMContentLoaded", extension.onPageLoad, true);

That would execute m "onPageLoad()" method as soon as the DOM is loaded, meaning all data is received. And that works, but I need to find a way to add a listener for when the DOM changes. The extension should read all data in the appbrowser-window, even if that's update via AJAX calls (ie: twitter, facebook).

I've looked into the DOMSubtreeModified event, but that doesn't seem to work when content is dynamically added after the initial DOMContentLoaded event has fired.

Has anyone ever overcome this problem?

My alternative is to keep firing the same function with a timeout() of say 2 seconds, to reread the DOM and parse it,  but I prefer to only do that if it actually changed.

答:
For anyone finding this in 2017 or later, these DOM modification events have been deprecated. What you want instead is MutationObserver.

See the MutationObserver docs on MDN, or this SO answer for more details.


问:
How to get application language and device language separately in android?
My device language is in English and my application language is in Italian.So how I  get the  device language and application language programmatically ?</p>

答:
Get system language

```<code>Resources.getSystem().getConfiguration().locale.getLanguage();
</code>```

Get app language

```<code>String currentLang = Locale.getDefault().getLanguage();
</code>```

Body:
Get system language

Resources.getSystem().getConfiguration().locale.getLanguage();

Get app language

String currentLang = Locale.getDefault().getLanguage();


问:
How to publish a CRM application in the CRM App Store?
our company would like to start developing Dynamics CRM Applications and store them in the Microsoft CRM App Store.
I looked around in the Internet but i couldn't find an exhaustive guide or some kind of suggestions to do it.
We are able to develop CRM Applications as we work on it for years, but now we want to publish (register) our apps on the store.
How we can achieve this?

Thank you in advance!!

答:
You need to Create Microsoft dev account & Azure account,
Microsoft Dev account used for registering you or your company.

Azure account has two sites One is Portal (portal.azure.com) on which we upload the solution and get url to set on the second site of Publish(publish.azure.com) .

Publish portal you just configure your uploaded package url and dev account settings.

I have found some information from below link
http://www.axsource.com/guide-for-microsoft-partners-to-publish-app-onto-microsoft-appsource/


问:
Laravel Multiple Optional Parameter Not Working and Two Back Slashes in URL
This is my route:

```<code>Route::get('/edit_atten/{id}/{date}/{c_in?}/{c_out?}', 'AttendanceController@editAttendance');

http://127.0.0.1:8000/edit_atten/31/2017-03-20//12:25:30

 public function editAttendance($id, $date, $c_in=null, $c_out=null)
{
    $this_user = Attendance::find($id);

    $this_user->check_in = $c_in;
    $this_user->check_out = $c_out;

    $this_user->save();

    echo "Success";

}
</code>```

Here, c_in & c_out are optional parameters.If I submit only c_out then URL shows like this: http://127.0.0.1:8000/edit_atten/31/2017-03-20//12:25:30 it creates routes problems. Because two slashes (//) shows in the URL! Though this (c_in) parameter is optional, why showing this?

Any solution for these ?

答:
```<code>Route::get('/edit_atten', 'AttendanceController@editAttendance');
</code>```

http://127.0.0.1:8000/edit_atten?id=31&date2017-03-20&c_out=12:25:30

```<code>public function editAttendance(Request $request)
{
  $id = $request->input('id');
  $date = $request->input('date');
  $c_in = $request->input('c_in');
  $c_out = $request->input('c_out');

  $this_user = Attendance::find($id);
  $this_user->check_in = $c_in;
  $this_user->check_out = $c_out;
  $this_user->save();

  echo "Success";
}
</code>```

Body:
This is my route:

Route::get('/edit_atten/{id}/{date}/{c_in?}/{c_out?}', 'AttendanceController@editAttendance');

http://127.0.0.1:8000/edit_atten/31/2017-03-20//12:25:30

 public function editAttendance($id, $date, $c_in=null, $c_out=null)
{
    $this_user = Attendance::find($id);

    $this_user->check_in = $c_in;
    $this_user->check_out = $c_out;

    $this_user->save();

    echo "Success";

}

Here, c_in & c_out are optional parameters.If I submit only c_out then URL shows like this: http://127.0.0.1:8000/edit_atten/31/2017-03-20//12:25:30 it creates routes problems. Because two slashes (//) shows in the URL! Though this (c_in) parameter is optional, why showing this?

Any solution for these ?

Body:
Route::get('/edit_atten', 'AttendanceController@editAttendance');

http://127.0.0.1:8000/edit_atten?id=31&date2017-03-20&c_out=12:25:30

public function editAttendance(Request $request)
{
  $id = $request->input('id');
  $date = $request->input('date');
  $c_in = $request->input('c_in');
  $c_out = $request->input('c_out');

  $this_user = Attendance::find($id);
  $this_user->check_in = $c_in;
  $this_user->check_out = $c_out;
  $this_user->save();

  echo "Success";
}


问:
Refresh content of a Div
I have read through multiple posts regarding reloading the content of a div through the use of Jquery. I have a Dashboard with multiple floating divs that rotates data calculated in php scripts.

ie. i have a php script that calculates data and i include this in a div which then scrolls through the content (see below code)

The problem i have with the code examples available online is that it doesnt show my php content.

How can i go about reloading the php pages in the div and still keep my slideshow going?

Thanks in advance

```<code><div class="topdiv_1">
    <div id="topdiv_1_slideshow">
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px" style="padding-left: 10px; margin-top: 50px;">
            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat1.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Total</h6>
        </div>
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px"
                 style="padding-left: 10px; margin-top: 50px;">

            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat2.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours System Center</h6>
        </div>
        <div align="center">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px"
                 style="padding-left: 10px; margin-top: 50px;">

            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php include_once('topdiv_1_stat3.php') ?></h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Service Center</h6>
        </div>
    </div>
</div>
</code>```

UPDATE:

I have tried adding this code to the div but now it throws away the formatting of the returned value:

```<code><div id="topdiv_1_slideshow">
        <div align="center" id="1">
            <img src="images/elements/project.png" class="pull-left" alt="" height="100px" style="padding-left: 10px; margin-top: 50px;">
            <h1 style="font-size: 90px; color: #ffffff; font-weight: bold"><?php /*include_once('topdiv_1_stat1.php') */?>
                <script>
                    $(function(){
                    $("#1").load("topdiv_1_stat1.php");
                    });
                </script>

                </h1>
            <h6 style="font-size: 14px; color: #ffffff; font-weight: bold">Project Hours Total</h6>
        </div>
</code>```

答:
You can call a php script with Ajax, get the datas and show all the datas returned by the PHP script in the DOM element you want, that will refresh it with fresh datas.

But you can't refresh only a part of your page without javascript.

Title: Refresh content of a Div

Body:
I have read through multiple posts regarding reloading the content of a div through the use of Jquery. I have a Dashboard with multiple floating divs that rotates data calculated in php scripts.

ie. i have a php script that calculates data and i include this in a div which then scrolls through the content (see below code)

The problem i have with the code examples available online is that it doesnt show my php content.

How can i go about reloading the php pages in the div and still keep my slideshow going?

Thanks in advance

<?php include_once('topdiv_1_stat1.php') ?>

Project Hours Total

<?php include_once('topdiv_1_stat2.php') ?>

Project Hours System Center

<?php include_once('topdiv_1_stat3.php') ?>

Project Hours Service Center

UPDATE:

I have tried adding this code to the div but now it throws away the formatting of the returned value:

<?php /*include_once('topdiv_1_stat1.php') */?>

Project Hours Total


答:
You can include a WHERE condition saying where goal <> 0 or use conditional count() like

```<code>COUNT(case when Goal <> 0 then 1 else 0 end) AS Goal
</code>```

Make your subquery like

```<code> LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
            FROM PlayerMatch
            INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
            WHERE Goal <> 0 ---Here
            GROUP BY MatchId, TeamId) C1
</code>```

Title: How to count rows with specific value?

Body:
You can include a WHERE condition saying where goal <> 0 or use conditional count() like

COUNT(case when Goal <> 0 then 1 else 0 end) AS Goal

Make your subquery like

 LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
            FROM PlayerMatch
            INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
            WHERE Goal <> 0 ---Here
            GROUP BY MatchId, TeamId) C1


问:
Spring boot: thymeleaf is not rendering fragments correctly
I am creating the spring boot web Application. For templating purpose I am using thymeleaf. I am creating separate html page fragment and I am creating two different layout from these fragments. However, When I connecting the content page I am not getting proper output.

Please check the code snippets/

view resolver

```<code>@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public TemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("html5");
    return templateResolver;
}

@Bean
public SpringTemplateEngine setTemplateEngine() {
    SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
    springTemplateEngine.setTemplateResolver(templateResolver());
    return springTemplateEngine;
}

@Bean
public ViewResolver viewResolver(){
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(setTemplateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}
</code>```

Directory structure

```<code>src/
  main/
    webapp/
        WEB-INF/
            views/
                fragments/
                         header.html
                         footer.html
                         navBar.html
                layouts/
                         appLayout.html
                         baseLayout.html
                 welcome.html
</code>```

appLayout.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
</head>
<body>

<div th:replace="/fragments/header :: header"></div>
<div th:replace="/fragments/navbar :: navbar"></div>
<div class="container">
    <div layout:fragment="content">
    <p>Content goes here...</p>
    </div>
    <footer>
    <div th:replace="/fragments/footer :: footer"></div>
    </footer>
</div>
</body>
</html>
</code>```

Footer fragment footer.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <div th:fragment="footer">
    Footer
    </div>
</body>
</html>
</code>```

Different fragments are created using this method.

main method class aka startup

```<code>@ComponentScan(basePackages={"xyz.abc"})
@SpringBootApplication
public class AppApplication {

    public static void main(String[] args) {
        System.out.println("Started");
        SpringApplication.run(AppApplication.class, args);
    }
}
</code>```

welcome.html

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layouts/appLayout}">

<head>
</head>

<body>
<th:block layout:fragment="content">
    <div class="hero-unit">
    <h1>My Content</h1>
    </div>
</th:block>
</body>
</html>
</code>```

Now when I access the server, I am getting only welcome.html and nothing from appLayout and fragments

What am I missing?

One more issue I have gone through many projects and some of them are keeping views under src/main/resource and I am keeping it under src/main/web/WEB-INF what is the difference between these two approaches?

答:
if you are using spring boot you don't need to define view resolver to render html pages.

The @SpringBootApplication annotation is equivalent to using  @Configuration, @EnableAutoConfiguration and @ComponentScan. so you don't probably need to define @ComponentScan.

I also see you don't need to define those beans if you are using spring boot. templates directory under  resources are directly accessible without defining beans. so by using thymeleaf you can return views from controller easily.

views are kept under src/main/web/WEB-INF in spring mvc. but on spring boot views are kept under templates directory which can be returned from controller without doing any view resolver configuration.

for your thymeleaf problem you can see this on github.

https://github.com/sagar1limbu/bookstore

Body:
I am creating the spring boot web Application. For templating purpose I am using thymeleaf. I am creating separate html page fragment and I am creating two different layout from these fragments. However, When I connecting the content page I am not getting proper output.

Please check the code snippets/

view resolver

@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public TemplateResolver templateResolver() {
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
    templateResolver.setPrefix("/WEB-INF/views/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("html5");
    return templateResolver;
}

@Bean
public SpringTemplateEngine setTemplateEngine() {
    SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
    springTemplateEngine.setTemplateResolver(templateResolver());
    return springTemplateEngine;
}

@Bean
public ViewResolver viewResolver(){
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    viewResolver.setTemplateEngine(setTemplateEngine());
    viewResolver.setOrder(1);
    return viewResolver;
}

Directory structure

src/
  main/
    webapp/
        WEB-INF/
            views/
                fragments/
                         header.html
                         footer.html
                         navBar.html
                layouts/
                         appLayout.html
                         baseLayout.html
                 welcome.html

appLayout.html

<!DOCTYPE html>

Content goes here...

Footer fragment footer.html

<!DOCTYPE html>

    Footer

Different fragments are created using this method.

main method class aka startup

@ComponentScan(basePackages={"xyz.abc"})
@SpringBootApplication
public class AppApplication {

    public static void main(String[] args) {
        System.out.println("Started");
        SpringApplication.run(AppApplication.class, args);
    }
}

welcome.html

<!DOCTYPE html>

My Content

Now when I access the server, I am getting only welcome.html and nothing from appLayout and fragments

What am I missing?

One more issue I have gone through many projects and some of them are keeping views under src/main/resource and I am keeping it under src/main/web/WEB-INF what is the difference between these two approaches?


问:
automatically converting xml format from LibGlade to GtkBuilder
I've found 2 ways of converting from an old GTK+ UI xml format (using Libglade) to the new format (using the built-in GtkBuilder). One is using Glade 3 Interface Builder (Save As button), and another is using gtk-builder-convert. They give different outputs, so I would like to know which one to trust more.</p>

答: It seems that gtk-builder-convert is less buggy than the two. Glade 3 screws up the xml output even when making a small edit without even doing a convert (Saving to old glade format).


问:
Java Verify xml digital signature using public key
I have a signed xml document which has been signed by private_key.pfx.

Now I have a public_key.cert file which start from :

```<code>====== BEGIN OF =======
jksbfjkbckcnJKNBCKSJJksncs==

====== END OF==========
</code>```

Now, I want to verify signed xml document using my public_key.cer

How can I do this ?

Please Help

答:
You need to look for the <Signature> element in your signed document.  There are methods in the Java XML Digital Signature API you can use to verify the signature such as XMLSignature.validate().

If you check out this article: Programming With the Java XML Digital Signature API.

key steps in validating an XML signature.

```<code>// Find Signature element.
NodeList nl =
    doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
    throw new Exception("Cannot find Signature element");
}

// Create a DOMValidateContext and specify a KeySelector
// and document context.
DOMValidateContext valContext = new DOMValidateContext
    (new X509KeySelector(), nl.item(0));

// Unmarshal the XMLSignature.
XMLSignature signature = fac.unmarshalXMLSignature(valContext);

// Validate the XMLSignature.
boolean coreValidity = signature.validate(valContext);
</code>```

First, you must find the location of the Signature element that you
  wish to validate. One way to do this is to use the DOM
  getElementsByTagNameNS method as shown in Code Sample 5. The second
  block of code creates a DOMValidateContext object containing a
  KeySelector object and a reference to the Signature element. The
  purpose of the KeySelector object is to obtain the public key using
  the information in the KeyInfo element and hand it back to be used as
  the validation key. The next section will discuss KeySelectors in more
  detail. The last two lines of code unmarshal and validate the
  signature. The validate method returns true if the signature is valid
  and false if it is invalid.

Body:
I have a signed xml document which has been signed by private_key.pfx.

Now I have a public_key.cert file which start from :

====== BEGIN OF =======
jksbfjkbckcnJKNBCKSJJksncs==

====== END OF==========

Now, I want to verify signed xml document using my public_key.cer

How can I do this ?

Please Help

Body:
You need to look for the <Signature> element in your signed document.  There are methods in the Java XML Digital Signature API you can use to verify the signature such as XMLSignature.validate().

If you check out this article: Programming With the Java XML Digital Signature API.

key steps in validating an XML signature.

// Find Signature element.
NodeList nl =
    doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
    throw new Exception("Cannot find Signature element");
}

// Create a DOMValidateContext and specify a KeySelector
// and document context.
DOMValidateContext valContext = new DOMValidateContext
    (new X509KeySelector(), nl.item(0));

// Unmarshal the XMLSignature.
XMLSignature signature = fac.unmarshalXMLSignature(valContext);

// Validate the XMLSignature.
boolean coreValidity = signature.validate(valContext);

First, you must find the location of the Signature element that you
  wish to validate. One way to do this is to use the DOM
  getElementsByTagNameNS method as shown in Code Sample 5. The second
  block of code creates a DOMValidateContext object containing a
  KeySelector object and a reference to the Signature element. The
  purpose of the KeySelector object is to obtain the public key using
  the information in the KeyInfo element and hand it back to be used as
  the validation key. The next section will discuss KeySelectors in more
  detail. The last two lines of code unmarshal and validate the
  signature. The validate method returns true if the signature is valid
  and false if it is invalid.


问:
IIDentity does not contain a definition for 'GetUserId'
I'm trying to use the VS2015 MVC controller and specifically GetUserID on User.Identity

i have seen a number of similar questions relating to this which state to add reference to Microsoft.AspNet.Identity, however as you can see that is referenced.

i assume i'm missing a package or something i just cannot figure it out

```<code>using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Web_Test.Models;

namespace Web_Test.Controllers
{
    public class TestController : Controller
    {
    public TestController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }

    public IActionResult Index()
    {
        //GetUserId() underlined in Red in VS2015
        //IIDentity does not contain a definition for 'GetUserId'
        string currentUserId = User.Identity.GetUserId();
        return View();
    }
}
}
</code>```

答:
Adding the following worked for me. I also needed to add the NuGet Package Microsoft ASP.NET Identity Core mentioned by @Badri.</p>

```<code>using Microsoft.AspNet.Identity; // NuGet: Microsoft ASP.NET Identity Core.
</code>```

Body:
I'm trying to use the VS2015 MVC controller and specifically GetUserID on User.Identity

i have seen a number of similar questions relating to this which state to add reference to Microsoft.AspNet.Identity, however as you can see that is referenced.

i assume i'm missing a package or something i just cannot figure it out

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Web_Test.Models;

namespace Web_Test.Controllers
{
    public class TestController : Controller
    {
    public TestController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }

    public IActionResult Index()
    {
        //GetUserId() underlined in Red in VS2015
        //IIDentity does not contain a definition for 'GetUserId'
        string currentUserId = User.Identity.GetUserId();
        return View();
    }
}
}

Body:
Adding the following worked for me. I also needed to add the NuGet Package Microsoft ASP.NET Identity Core mentioned by @Badri.

using Microsoft.AspNet.Identity; // NuGet: Microsoft ASP.NET Identity Core.