问:
Regex to match punctuation followed by space with some exceptions
I am trying to come up with a regex which matches punctuation (!, ?, and .) followed by a space. I want to NOT match periods which are preceded by salutations like "Mr.", "Mrs.", etc...

Doing the first part is simple enough:
r"[\?|!|\.] "

But I am struggling with the second part. Here is what I have so far:
r"(?<=[^(Mr|Ms)])\. "

The second one does NOT match something like "radar. " or "cups. " or "loom. " which is bad. I am also having trouble combining both those regexes into a single one.

Thanks.

答:
Here is a working one: https://regex101.com/r/iRNTMY/2

```<code>(?<!(Mr|Ms))(?<!(Mrs))[.?!]
</code>```

It uses negative look-behind twice for the two different length possibilities.

Body:
Here is a working one: https://regex101.com/r/iRNTMY/2

(?<!(Mr|Ms))(?<!(Mrs))[.?!]

It uses negative look-behind twice for the two different length possibilities.


来源: stackexchange

问:
Constructing images in C# WPF/MVVM (drawing lines, arcs, text)
In a WPF standalone-application I need to draw an image based on a series of 'commands' such as "text a at position x,y" and "draw line from x1,y1 to x2,y2".

My problems and considerations are outlined below - any help and comments are most appreciated!

The image is of a water pump constructed by our company.

The commands are generated by a proprietory system within our company.

There are no problems interpreting the commands.

My issue is with

a) what WPF control should I choose to draw it 'on' ?

b) how can I move the major part of the code to unit-testable classes?

a1) I have tried with PathGeometry, which is excellent for drawing geometric shapes but can't draw text.

a2) I have tried with Shape, which supports drawing text, but is less advanced with respect to geometry.

a3) Could I use the strength in each of the two, and 'apply' a PathGeometry to a Shape?

a4) I need to handle MouseOver after the drawing to highlight based on the mouse position. It can be done through computing 'behind the scenes' the object nearest mouse position (though possible, it's heavy!) but can the choice of rendering Control help me out?

b1) I do not expect the end drawing to be subjectable to test?

b2) How 'deep' should I reference controls belonging in the GUI? Gut feeling says no deeper than ViewModel (not business level), but the higher I keep it, the more code remains in places where they can't be unit tested.

答:
Here are answers specific to WPF:

You can draw on a Canvas, wich lets you set element's position (Canvas.SetLeft, Canvas.SetTop, ...)

And you can perfectly use PathGeometry, Shape, etc... you should also have a loop at GeometryGroup which allows to group all geometry as one.

For the text, if you want text as a Geometry, you can use FormattedText with the BuildGeometry method..

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Xamarin - how to open a new ContentPage in a ListView?
I have a list that comes from my web service and i display it like so:

```<code><StackLayout HorizontalOptions="FillAndExpand">
    <ListView x:Name="curso" ItemSelected="CursoView_ItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Horizontal">
                            <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">
                                <Label StyleClass="Header" Text="{Binding name}" />
                            </StackLayout>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>
</code>```

And now i want to be able to click on an item and open a new ContentPage

答:
```<code>public void CursoView_ItemSelected(object sender, ItemSelectedEventArgs e)
{
  // this assumes your current page is already contained in a NavigationPage
  Navigation.PushAsync(new MyNextPage());
}
</code>```

Body:
I have a list that comes from my web service and i display it like so:

<StackLayout HorizontalOptions="FillAndExpand">
    <ListView x:Name="curso" ItemSelected="CursoView_ItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Horizontal">
                            <StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand">

                            </StackLayout>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

And now i want to be able to click on an item and open a new ContentPage


问:
Custom cron job is not scheduling Magento2
I am trying to add cronjob through crontab.xml in my custom module, but they are not appearing in cron_schedule table after running php bin/magento cron:run many times.
If i enter time as <schedule>* * * * *</schedule> it works and job get schedule in cron_schedule table. But i have to set time to run cronjob at 1:00 am. here is my crontab.xml

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="abc_import" instance="Abc\Xyz\Model\Api" method="importProducts">
            <schedule>0 1 * * *</schedule>
        </job>
    </group>
</config>
</code>```

答:
Have you tried flushing cache.

```<code>php bin/magento cache:flush
</code>```

What about running cron like this?

```<code>php bin/magento cron:run
</code>```

Body:
I am trying to add cronjob through crontab.xml in my custom module, but they are not appearing in cron_schedule table after running php bin/magento cron:run many times.
If i enter time as <schedule>* * * * *</schedule> it works and job get schedule in cron_schedule table. But i have to set time to run cronjob at 1:00 am. here is my crontab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="abc_import" instance="Abc\Xyz\Model\Api" method="importProducts">
            <schedule>0 1 * * *</schedule>
        </job>
    </group>
</config>

Body:
Have you tried flushing cache.

php bin/magento cache:flush

What about running cron like this?

php bin/magento cron:run


问:
How to use params/properties flag values when executing hive job on google dataproc
I am trying to execute a hive job in google dataproc using following gcloud command:

gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --properties=[bucket1=abcd]

gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --params=[bucket1=abcd]

But none of the 2 above commands is able to set 'bucket1' variable to 'x' variable .

The hive script is as follows:

```<code>set x=${bucket1};
set x;
drop table T1;
create external table T1( column1 bigint, column2 float, column3 int) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE LOCATION 'gs://${hiveconf:x}/output/prod';
</code>```

But the variable 'x' is unable to take 'bucket1' variable which i passed in the gcloud command.

How do i do it? Please suggest

答:
Both examples should work with minor tweaks.

In cloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --properties bucket1=abcd, you can access variable as ${bucket1}

In gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --params bucket1=abcd, you can access variable as ${hivevar:bucket1}

Easy way to test this, is to submit a script like this to dump all variables:

gcloud dataproc jobs submit hive --cluster msm-test-cluster -e "set;" --properties foo=bar --params bar=baz

The output should contain:

```<code>| foo=bar
| hivevar:bar=baz
</code>```

Related question:
How to set variables in HIVE scripts

Body:
I am trying to execute a hive job in google dataproc using following gcloud command:

gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --properties=[bucket1=abcd]

gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --params=[bucket1=abcd]

But none of the 2 above commands is able to set 'bucket1' variable to 'x' variable .

The hive script is as follows:

set x=${bucket1};
set x;
drop table T1;
create external table T1( column1 bigint, column2 float, column3 int) ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' STORED AS TEXTFILE LOCATION 'gs://${hiveconf:x}/output/prod';

But the variable 'x' is unable to take 'bucket1' variable which i passed in the gcloud command.

How do i do it? Please suggest

Body:
Both examples should work with minor tweaks.

In cloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --properties bucket1=abcd, you can access variable as ${bucket1}

In gcloud dataproc jobs submit hive --cluster=msm-test-cluster --file hive.sql --params bucket1=abcd, you can access variable as ${hivevar:bucket1}

Easy way to test this, is to submit a script like this to dump all variables:

gcloud dataproc jobs submit hive --cluster msm-test-cluster -e "set;" --properties foo=bar --params bar=baz

The output should contain:

| foo=bar
| hivevar:bar=baz

Related question:
How to set variables in HIVE scripts


问:
Php script, query ran from value thats passed in
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

```<code>   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");
</code>```

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

```<code>mssql_query($_REQUEST['sqlscript']);
</code>```

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.

答:
Tell your script to output the contents of $_REQUEST['sqlscript']

echo $REQUEST['sqlscript'];

Check that the output is correct.  You might well find that there are some parsing errors, or just that your script is incomplete.  Check for quotes (") and make sure the query is valid.

Also, you should never run a script from a request.  Imagine if someone browsed to your site and typed

youtsite.com?sqlscript='drop * from tables';

Your entire database would be wiped.

Body:
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

mssql_query($_REQUEST['sqlscript']);

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.


问:
Wordpress Site Images not displaying in IE11 & Firefox Browser
I have an interesting problem with this website.  When the site is viewed through Chrome or Safari, all images are displayed & the site appears as intended.

When the site is viewed in Firefox (V54) & reportedly in IE11, neither the logo, nor any other images are visible on the page.

When I inspect the code in Firefox, I can see the images in the code, so there isn't an inherent issue with the client device accessing the image:

Any thoughts as to what would be causing this?

答:
Thanks for your answers guys.  Managed to fix this (which is probably why user3080315 you saw everything working OK.

The issue was with the CSS.  A friend spotted the problem:

```<code>img {
    height: auto;
    max-width: 100%;
    vertical-align: middle;
    -webkit-filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.25));
    filter: url(#drop-shadow);
    -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
    filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}
</code>```

Should become:

```<code>img {
    height: auto;
    max-width: 100%;
    vertical-align: middle;
    -webkit-filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.25));
    -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
    filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}
</code>```

filter: url(#drop-shadow); being the line causing issue.

Body:
Thanks for your answers guys.  Managed to fix this (which is probably why user3080315 you saw everything working OK.

The issue was with the CSS.  A friend spotted the problem:

img {
    height: auto;
    max-width: 100%;
    vertical-align: middle;
    -webkit-filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.25));
    filter: url(#drop-shadow);
    -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
    filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}

Should become:

img {
    height: auto;
    max-width: 100%;
    vertical-align: middle;
    -webkit-filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.25));
    -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
    filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}

filter: url(#drop-shadow); being the line causing issue.


问:
R Repeat function from first subvector of vector until total vector length reached
I have a vector epsilon of length N. I am applying the function bw.CDF.pi(x, pilot="UCV") from the sROC package to compute bandwidths for cdf Kernel estimation.

My goal is to repeat this bandwidth function for every subvector from epsilon from the beginning value on. Stated otherwise, I would like to apply this function for the first value in epsilon, then for the first two values in epsilon, then for the first three values in epsilon, continiuing until the function is applied fot the total vector epsilon. Finally i want to have then N values for the bandwidth.

How can I accomplish this?

答:
Apparently you need a vector of 2 elements for the function bw.CDF.pi to run. If you want to run it for the first 2 elemts of a vector, then the first 3, etc, you can do the following. Note that the data example is the one in the help page for the function.

```<code>library(sROC)

set.seed(100)
n <- 200
x <- c(rnorm(n/2, mean=-2, sd=1), rnorm(n/2, mean=3, sd=0.8))

lapply(seq_along(x)[-1], function(m) bw.CDF.pi(x[seq_len(m)], pilot="UCV"))
</code>```

Body:
Apparently you need a vector of 2 elements for the function bw.CDF.pi to run. If you want to run it for the first 2 elemts of a vector, then the first 3, etc, you can do the following. Note that the data example is the one in the help page for the function.

library(sROC)

set.seed(100)
n <- 200
x <- c(rnorm(n/2, mean=-2, sd=1), rnorm(n/2, mean=3, sd=0.8))

lapply(seq_along(x)[-1], function(m) bw.CDF.pi(x[seq_len(m)], pilot="UCV"))


问:
<fo:external-graphic src=... > throws error
I use fop 2.1 and I need to load an external graphic with an absolute path. I tried this:

```<code>    <fo:root xsl:use-attribute-sets="text-attributes">
        <fo:layout-master-set>
         ...

        <fo:page-sequence master-reference="master">
            <xsl:call-template name="pageHeader"/>
            <xsl:call-template name="pageFooter"/>

            <fo:flow flow-name="xsl-region-body">
                ...
            </fo:flow>
        </fo:page-sequence>

   ...

<xsl:template name="pageHeader">
    <fo:static-content flow-name="region-before-first">
        <fo:block>
           <fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>
        </fo:block>
    </fo:static-content>
</xsl:template>
</code>```

$logo-image contains the absolute path like C:/users/.../application/logo.gif

I get the following error:

```<code>PM org.apache.fop.events.LoggingEventListener processEvent
SEVERE: Invalid property value encountered in src="url(file:/C:/users/.../application/logo.gif)"  .... Invalid URI specified
</code>```

Any idea?

I tried also to put ' around like "url('file:/C:/users/.../application/logo.gif')" and else at divers place. No success... :-(

As in some other stylesheets I do have external graphic that functions I tried also take the header into the normal flow ( => not static ). Not really the way to do for a header, but a try... :

```<code>    <fo:root xsl:use-attribute-sets="text-attributes">
        <fo:layout-master-set>
         ...

        <fo:page-sequence master-reference="master">
            <!--<xsl:call-template name="pageHeader"/>-->
            <xsl:call-template name="pageFooter"/>

            <fo:flow flow-name="xsl-region-body">
                <xsl:call-template name="pageHeader"/>
                ...
            </fo:flow>
        </fo:page-sequence>

   ...

<xsl:template name="pageHeader">
    <fo:block-container position="absolute" top="10mm" left="10mm">
        <fo:block>
           <fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>
        </fo:block>
    </fo:block-container>
</xsl:template>
</code>```

But: Independantly if I put

```<code><fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>
</code>```

or

```<code><fo:external-graphic src="url({concat('file:///',$logo-image)})" height="15mm" content-height="15mm"/>
</code>```

I get same stupid error:

```<code>.... Invalid URI specified
</code>```

答:
First, simplify matters by getting it to work as a static FO file, independent of XSLT.  You can double-back to the XSLT once you have a static target FO file working.

Realize that as @rene commented, you have to use full URI syntax, which may actually require yet another / for local access.  (Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row):

```<code>file:///c:/users
</code>```

If you still have trouble with this, do a browser walk up the directory tree to make sure that the files and its ancestor directories all exist.

Finally, note that ... isn't valid, in case that's a typo for .. and not a meta-notation about elided path components.

Body:
I use fop 2.1 and I need to load an external graphic with an absolute path. I tried this:

    <fo:root xsl:use-attribute-sets="text-attributes">
        <fo:layout-master-set>
         ...

        <fo:page-sequence master-reference="master">
            <xsl:call-template name="pageHeader"/>
            <xsl:call-template name="pageFooter"/>

            <fo:flow flow-name="xsl-region-body">
                ...
            </fo:flow>
        </fo:page-sequence>

   ...

<xsl:template name="pageHeader">
    <fo:static-content flow-name="region-before-first">
        <fo:block>
           <fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>
        </fo:block>
    </fo:static-content>
</xsl:template>

$logo-image contains the absolute path like C:/users/.../application/logo.gif

I get the following error:

PM org.apache.fop.events.LoggingEventListener processEvent
SEVERE: Invalid property value encountered in src="url(file:/C:/users/.../application/logo.gif)"  .... Invalid URI specified

Any idea?

I tried also to put ' around like "url('file:/C:/users/.../application/logo.gif')" and else at divers place. No success... :-(

As in some other stylesheets I do have external graphic that functions I tried also take the header into the normal flow ( => not static ). Not really the way to do for a header, but a try... :

    <fo:root xsl:use-attribute-sets="text-attributes">
        <fo:layout-master-set>
         ...

        <fo:page-sequence master-reference="master">

            <xsl:call-template name="pageFooter"/>

            <fo:flow flow-name="xsl-region-body">
                <xsl:call-template name="pageHeader"/>
                ...
            </fo:flow>
        </fo:page-sequence>

   ...

<xsl:template name="pageHeader">
    <fo:block-container position="absolute" top="10mm" left="10mm">
        <fo:block>
           <fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>
        </fo:block>
    </fo:block-container>
</xsl:template>

But: Independantly if I put

<fo:external-graphic src="url({concat('file:/',$logo-image)})" height="15mm" content-height="15mm"/>

or

<fo:external-graphic src="url({concat('file:///',$logo-image)})" height="15mm" content-height="15mm"/>

I get same stupid error:

.... Invalid URI specified

Body:
First, simplify matters by getting it to work as a static FO file, independent of XSLT.  You can double-back to the XSLT once you have a static target FO file working.

Realize that as @rene commented, you have to use full URI syntax, which may actually require yet another / for local access.  (Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row):

file:///c:/users

If you still have trouble with this, do a browser walk up the directory tree to make sure that the files and its ancestor directories all exist.

Finally, note that ... isn't valid, in case that's a typo for .. and not a meta-notation about elided path components.


问:
Downloading Angular or ReactJS web pages
I need to write a parser which will collect data from a website which was developed using ReactJS. The problem is when open source code (Ctrl+U) I don't see anything in the code but if I inspect an element a can see full webpage in for instance google inspector (Ctrl+Shift+I)

Do you how can can download html code from the inspector?

答: I can not speak for React, but with angular if you locally host the site (ng serve) you will not be able to ctrl+u. However, if it's hosted somewhere you can ie: https://angular.io/</p>


问:
Methods .text() and .html() in jQuery strip trailing whitespace in IE7?
I'm using jQuery to insert text inside a HTML tag. The HTML code looks like this:

```<code><h5>Do you want to send a message to <span id='firstName'></span> right now?</h5>
</code>```

The jQuery code for inserting the text inside the span tag looks like this:

```<code>var myFirstName = "Thomas";
$("h5 span.firstName").html(myFirstName);
</code>```

When I run this code in Firefox, Chrome, Safari or IE8 the result is this:

```<code><h5>Do you want to send a message to <span id='firstName'>Thomas</span> right now?</h5>
</code>```

But in Internet Explorer 7, the result is this:

```<code><h5>Do you want to send a message to <span id='firstName'>Thomas</span>right now?</h5>
</code>```

The trailing white space after the span tag is stripped resulting in a text on-screen that reads: "Do you want to send a message to Thomasright now?".

I've tried using both .html() and .text() but there is no difference in the result.

Is there a way to fix this bug? Is it a known bug in jQuery/IE7?

Thanks in advance!

/Thomas Kahn

答:
That is strange but you can do this:</p>

```<code>var myFirstName = "Thomas ";
$("h5 span.firstName").html(myFirstName);
</code>```

Body:
I'm using jQuery to insert text inside a HTML tag. The HTML code looks like this:

Do you want to send a message to  right now?

The jQuery code for inserting the text inside the span tag looks like this:

var myFirstName = "Thomas";
$("h5 span.firstName").html(myFirstName);

When I run this code in Firefox, Chrome, Safari or IE8 the result is this:

Do you want to send a message to Thomas right now?

But in Internet Explorer 7, the result is this:

Do you want to send a message to Thomasright now?

The trailing white space after the span tag is stripped resulting in a text on-screen that reads: "Do you want to send a message to Thomasright now?".

I've tried using both .html() and .text() but there is no difference in the result.

Is there a way to fix this bug? Is it a known bug in jQuery/IE7?

Thanks in advance!

/Thomas Kahn

Body:
That is strange but you can do this:

var myFirstName = "Thomas&nbsp;";
$("h5 span.firstName").html(myFirstName);


问:
every time I submit with a State, but there is an error, it doesn't save the state selected what Am I missing on the php script?
Im hoping someone can help me, there is probably a simple solution
I am writing a php form with twitter bootstrap as a framework and have created a dropdown. once the state is selected and the submit button clicked, but  "I am human" checkbox  is missing the error messages comes up and the state selected is not saved. how Do i get the state to save as well..</p>

```<code><?php

 if ($_POST['submit']) {
 }
  if (!$_POST['state']) {
       $error="<br/>-- Please enter a State";
 }

  if (!$_POST['check']) {
       $error.="<br/>-- Please confirm your human";
  }
 if ($error) {
    $result="Whoops, there is an error. please correct the following:
    $error";
    }
 }
?>
!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,
 shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet"
 href="css/bootstrap.min.css">
<link rel="stylesheet"href="css/contact_form.css">
</head>
<body>
 <form method="post" action="#" role="form">
 <div class="col-md-3 offset-md-3">
      <div class="form-group">
       <select class="form-control" id="state" name="state"
      placeholder="state" value="<?php echo $_POST['state']; ?>">
        <option value="">State</option>
        <option value="AK">Alaska</option>
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="AZ">Arizona</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DC">District of Columbia</option>
        <option value="DE">Delaware</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="IA">Iowa</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="MA">Massachusetts</option>
        <option value="MD">Maryland</option>
        <option value="ME">Maine</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MO">Missouri</option>
        <option value="MS">Mississippi</option>
        <option value="MT">Montana</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="NE">Nebraska</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NV">Nevada</option>
        <option value="NY">New York</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="PR">Puerto Rico</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VA">Virginia</option>
        <option value="VT">Vermont</option>
        <option value="WA">Washington</option>
        <option value="WI">Wisconsin</option>
        <option value="WV">West Virginia</option>
        <option value="WY">Wyoming</option>
        </select>
     </div>
    </div>
   <div class="checkbox" id="options">
            <label>
              <input type="checkbox" name="check"> I am human
            </label>
             </div>
    <div align="center">
      <input type="submit" name="submit" class="btn btn-primary"
 value="send message"/>
 </div>
 </form>

 <script src="js/jquery.slim.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
</code>```

答:
You can not set value for select this way

```<code><select class="form-control" id="state" name="state"
  placeholder="state" value="<?php echo $_POST['state']; ?>">
</code>```

You should check every opion is select to set value

```<code><option value="AK" <?php if ($_POST['state'] == "AK") {echo "selected";}?> >Alaska</option>
</code>```

Body:
Im hoping someone can help me, there is probably a simple solution
I am writing a php form with twitter bootstrap as a framework and have created a dropdown. once the state is selected and the submit button clicked, but  "I am human" checkbox  is missing the error messages comes up and the state selected is not saved. how Do i get the state to save as well..

<?php

 if ($_POST['submit']) {
 }
  if (!$_POST['state']) {
       $error="
-- Please enter a State";
 }

  if (!$_POST['check']) {
       $error.="
-- Please confirm your human";
  }
 if ($error) {
    $result="Whoops, there is an error. please correct the following:
    $error";
    }
 }
?>
!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,
 shrink-to-fit=no">

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

 <form method="post" action="#" role="form">

       <select class="form-control" id="state" name="state"
      placeholder="state" value="<?php echo $_POST['state']; ?>">
        <option value="">State</option>
        <option value="AK">Alaska</option>
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="AZ">Arizona</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DC">District of Columbia</option>
        <option value="DE">Delaware</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="IA">Iowa</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="MA">Massachusetts</option>
        <option value="MD">Maryland</option>
        <option value="ME">Maine</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MO">Missouri</option>
        <option value="MS">Mississippi</option>
        <option value="MT">Montana</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="NE">Nebraska</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NV">Nevada</option>
        <option value="NY">New York</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="PR">Puerto Rico</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VA">Virginia</option>
        <option value="VT">Vermont</option>
        <option value="WA">Washington</option>
        <option value="WI">Wisconsin</option>
        <option value="WV">West Virginia</option>
        <option value="WY">Wyoming</option>
        </select>

              <input type="checkbox" name="check"> I am human

      <input type="submit" name="submit" class="btn btn-primary"
 value="send message"/>

 </form>

Body:
You can not set value for select this way

<select class="form-control" id="state" name="state"
  placeholder="state" value="<?php echo $_POST['state']; ?>">

You should check every opion is select to set value

<option value="AK" <?php if ($_POST['state'] == "AK") {echo "selected";}?> >Alaska</option>


问:
local variable 'data' referenced before assignment
UnboundLocalError at /post/
local variable 'data' referenced before assignment
Request Method:
POST
Request URL:
http://127.0.0.1:8000/post/
Django Version:
1.11.3
Exception Type:
UnboundLocalError
Exception Value:
local variable 'data' referenced before assignment
Exception Location:
D:\website\formapp\views.py in index, line 56

```<code>def index(request):
if request.method == 'POST':
    form = Postform(request.POST,request.FILES)
    if form.is_valid():
        f=form.save(commit=False)
        f.user=request.user
        f.save()
        return HttpResponseRedirect('/post/')
else:
    form = Postform()
    data=Post.objects.order_by('-date_created')
return render(request,'home2.html',{'form':form,'data':data})
</code>```

```<code>class Postform(forms.ModelForm):
pic=models.FileField()
vid=models.FileField()
class Meta:
    model=Post
    #fields=['title','content','pic']
    fields='__all__'
</code>```

```<code><form action=' ' method = 'POST' enctype="multipart/form-data">
{% csrf_token %}
<h3>Title:</h3> {{form.title}}<br><br>
<h3>Content:</h3> {{form.content}}<br><br>
<h3>Pic: </h3>{{form.pic}}<br>
<button type= 'submit' class='btn btn-primary btn-md'>Save</button>
<br><br>
</form>
</code>```

答:
If form.is_valid() returns False, you have to assign a value to data.

```<code>def index(request):

    if request.method == 'POST':
        form = Postform(request.POST,request.FILES)
        if form.is_valid():
            f=form.save(commit=False)
            f.user=request.user
            f.save()
            return HttpResponseRedirect('/post/')
    else:
        form = Postform()

    data=Post.objects.order_by('-date_created') # take this out of the `else` block.
    return render(request,'home2.html',{'form':form,'data':data})
</code>```

Body:
UnboundLocalError at /post/
local variable 'data' referenced before assignment
Request Method:
POST
Request URL:
http://127.0.0.1:8000/post/
Django Version:
1.11.3
Exception Type:
UnboundLocalError
Exception Value:
local variable 'data' referenced before assignment
Exception Location:
D:\website\formapp\views.py in index, line 56

def index(request):
if request.method == 'POST':
    form = Postform(request.POST,request.FILES)
    if form.is_valid():
        f=form.save(commit=False)
        f.user=request.user
        f.save()
        return HttpResponseRedirect('/post/')
else:
    form = Postform()
    data=Post.objects.order_by('-date_created')
return render(request,'home2.html',{'form':form,'data':data})

class Postform(forms.ModelForm):
pic=models.FileField()
vid=models.FileField()
class Meta:
    model=Post
    #fields=['title','content','pic']
    fields='__all__'

<form action=' ' method = 'POST' enctype="multipart/form-data">
{% csrf_token %}

Title:
 {{form.title}}

Content:
 {{form.content}}

Pic:
{{form.pic}}

<button type= 'submit' class='btn btn-primary btn-md'>Save</button>

</form>

Body:
If form.is_valid() returns False, you have to assign a value to data.

def index(request):

    if request.method == 'POST':
        form = Postform(request.POST,request.FILES)
        if form.is_valid():
            f=form.save(commit=False)
            f.user=request.user
            f.save()
            return HttpResponseRedirect('/post/')
    else:
        form = Postform()

    data=Post.objects.order_by('-date_created') # take this out of the `else` block.
    return render(request,'home2.html',{'form':form,'data':data})


问:
Getting exception at at com.install4j.runtime.launcher.WinLauncher.main(WinLauncher.java:26)
I have created installers using Install4j. I am able to install the tool with these installers on both windows and linux.

but in windows, I am getting below exception

```<code>StartupHandler.initializeActionManager() ... ERROR: occurred while reading action shcema.
ERROR: SAX2 driver class org.apache.xerces.parsers.SAXParser does not implement XMLReader
org.xml.sax.SAXException: SAX2 driver class org.apache.xerces.parsers.SAXParser does not implement XMLReader
java.lang.ClassCastException: org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration
    at org.xml.sax.helpers.XMLReaderFactory.loadClass(Unknown Source)
    at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
    at com.appperfect.common.UtilityFunctions.parseXML(UtilityFunctions.java:1981)
    at com.appperfect.installer.common.ActionSchemaReader.loadActionConfigFile(ActionSchemaReader.java:74)
    at com.appperfect.installer.common.ActionSchemaReader.<init>(ActionSchemaReader.java:65)
    at com.appperfect.installer.common.ActionManager.loadActionSchema(ActionManager.java:157)
    at com.appperfect.installer.i4j.handlers.StartupHandler.initializeActionManager(StartupHandler.java:308)
    at com.appperfect.installer.i4j.handlers.StartupHandler.prepareInstaller(StartupHandler.java:86)
    at com.appperfect.installer.i4j.actions.AppStartupAction.install(AppStartupAction.java:43)
    at com.install4j.runtime.installer.ContextImpl$7.executeAction(ContextImpl.java:1668)
    at com.install4j.runtime.installer.ContextImpl$7.fetchValue(ContextImpl.java:1659)
    at com.install4j.runtime.installer.ContextImpl$7.fetchValue(ContextImpl.java:1656)
    at com.install4j.runtime.installer.helper.comm.actions.FetchObjectAction.execute(FetchObjectAction.java:14)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionDirect(HelperCommunication.java:274)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionInt(HelperCommunication.java:249)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionChecked(HelperCommunication.java:187)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.fetchObjectChecked(HelperCommunication.java:170)
    at com.install4j.runtime.installer.ContextImpl.performActionIntStatic(ContextImpl.java:1656)
    at com.install4j.runtime.installer.InstallerContextImpl.performActionInt(InstallerContextImpl.java:151)
    at com.install4j.runtime.installer.ContextImpl.performAction(ContextImpl.java:1103)
    at com.install4j.runtime.installer.controller.Controller.executeAction(Controller.java:368)
    at com.install4j.runtime.installer.controller.Controller.executeActions(Controller.java:334)
    at com.install4j.runtime.installer.controller.Controller.handleCommand(Controller.java:195)
    at com.install4j.runtime.installer.controller.Controller.handleStartup(Controller.java:116)
    at com.install4j.runtime.installer.controller.Controller.start(Controller.java:73)
    at com.install4j.runtime.installer.Installer.runInProcess(Installer.java:59)
    at com.install4j.runtime.installer.Installer.main(Installer.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:65)
    at com.exe4j.runtime.WinLauncher.main(WinLauncher.java:101)
    at com.install4j.runtime.launcher.WinLauncher.main(WinLauncher.java:26)
</code>```

I have googled and found that it may be due to incompatible versions of xercesImpl.jar, downloaded latest jars and tried but no help.

removed xercseImpl.jar and xml-apis.jar, added xerces.jar. But the issue persists.

答: This problem is fixed in install4j 6.1.6.</p>

Body:
I have created installers using Install4j. I am able to install the tool with these installers on both windows and linux.

but in windows, I am getting below exception

StartupHandler.initializeActionManager() ... ERROR: occurred while reading action shcema.
ERROR: SAX2 driver class org.apache.xerces.parsers.SAXParser does not implement XMLReader
org.xml.sax.SAXException: SAX2 driver class org.apache.xerces.parsers.SAXParser does not implement XMLReader
java.lang.ClassCastException: org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration
    at org.xml.sax.helpers.XMLReaderFactory.loadClass(Unknown Source)
    at org.xml.sax.helpers.XMLReaderFactory.createXMLReader(Unknown Source)
    at com.appperfect.common.UtilityFunctions.parseXML(UtilityFunctions.java:1981)
    at com.appperfect.installer.common.ActionSchemaReader.loadActionConfigFile(ActionSchemaReader.java:74)
    at com.appperfect.installer.common.ActionSchemaReader.<init>(ActionSchemaReader.java:65)
    at com.appperfect.installer.common.ActionManager.loadActionSchema(ActionManager.java:157)
    at com.appperfect.installer.i4j.handlers.StartupHandler.initializeActionManager(StartupHandler.java:308)
    at com.appperfect.installer.i4j.handlers.StartupHandler.prepareInstaller(StartupHandler.java:86)
    at com.appperfect.installer.i4j.actions.AppStartupAction.install(AppStartupAction.java:43)
    at com.install4j.runtime.installer.ContextImpl$7.executeAction(ContextImpl.java:1668)
    at com.install4j.runtime.installer.ContextImpl$7.fetchValue(ContextImpl.java:1659)
    at com.install4j.runtime.installer.ContextImpl$7.fetchValue(ContextImpl.java:1656)
    at com.install4j.runtime.installer.helper.comm.actions.FetchObjectAction.execute(FetchObjectAction.java:14)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionDirect(HelperCommunication.java:274)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionInt(HelperCommunication.java:249)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.executeActionChecked(HelperCommunication.java:187)
    at com.install4j.runtime.installer.helper.comm.HelperCommunication.fetchObjectChecked(HelperCommunication.java:170)
    at com.install4j.runtime.installer.ContextImpl.performActionIntStatic(ContextImpl.java:1656)
    at com.install4j.runtime.installer.InstallerContextImpl.performActionInt(InstallerContextImpl.java:151)
    at com.install4j.runtime.installer.ContextImpl.performAction(ContextImpl.java:1103)
    at com.install4j.runtime.installer.controller.Controller.executeAction(Controller.java:368)
    at com.install4j.runtime.installer.controller.Controller.executeActions(Controller.java:334)
    at com.install4j.runtime.installer.controller.Controller.handleCommand(Controller.java:195)
    at com.install4j.runtime.installer.controller.Controller.handleStartup(Controller.java:116)
    at com.install4j.runtime.installer.controller.Controller.start(Controller.java:73)
    at com.install4j.runtime.installer.Installer.runInProcess(Installer.java:59)
    at com.install4j.runtime.installer.Installer.main(Installer.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:65)
    at com.exe4j.runtime.WinLauncher.main(WinLauncher.java:101)
    at com.install4j.runtime.launcher.WinLauncher.main(WinLauncher.java:26)

I have googled and found that it may be due to incompatible versions of xercesImpl.jar, downloaded latest jars and tried but no help.

removed xercseImpl.jar and xml-apis.jar, added xerces.jar. But the issue persists.


问:
how to redirect a page in nodejs
Currently this doesnt work. I'm new to nodejs so maybe the format is completely wrong

```<code>function blueScreen(showit) {
   console.log(showit);
   if (showit) {
      function getFormattedUrl(req) {
         return url.format({
           protocol: req.protocol,
           host: req.get('localhost:3000/blue.html')
         });
      }
   }
   return res.redirect(getFormattedUrl(req));;
}
</code>```

I do know this goes into this function but the screen wont change when showIt is true
UPDATE: the res.redirect i believe is wrong because i never defined rec anyway. However I will say that this is not in the same file the app is due to the way my files interact it cant be in that file. Is there a way I can redirect my screen in a file without req and res function?

答:
I assume you use expressjs. Basically you have a middleware function where you can access to the request response object

```<code>app.get('/blue', function (req, res) {
   res.redirect('/green');
});
</code>```

Title: how to redirect a page in nodejs

Body:
Currently this doesnt work. I'm new to nodejs so maybe the format is completely wrong

function blueScreen(showit) {
   console.log(showit);
   if (showit) {
      function getFormattedUrl(req) {
         return url.format({
           protocol: req.protocol,
           host: req.get('localhost:3000/blue.html')
         });
      }
   }
   return res.redirect(getFormattedUrl(req));;
}

I do know this goes into this function but the screen wont change when showIt is true
UPDATE: the res.redirect i believe is wrong because i never defined rec anyway. However I will say that this is not in the same file the app is due to the way my files interact it cant be in that file. Is there a way I can redirect my screen in a file without req and res function?

Body:
I assume you use expressjs. Basically you have a middleware function where you can access to the request response object

app.get('/blue', function (req, res) {
   res.redirect('/green');
});


问:
Calculate total CPU usage
What is best algorithm for calculating total CPU usage at a particular time during execution of a process.

I am working windows platform in C++.

答:
Don't use WMI
Simply Use win32 NAPI</p>

Title: Calculate total CPU usage

LastEditorDisplayName: Martin

Body:
Don't use WMI
Simply Use win32 NAPI

OwnerDisplayName: red


问:
linkedin : Invalid redirect_uri. This value must match a URL registered with the API Key
I am using 'omniauth-linkedin-oauth2'.

When I am login with linkedin then I am getting this error

Invalid redirect_uri. This value must match a URL registered with the API Key.

This is my settings:

答:
I had this when trying to authorise from a zurb Reveal modal popup.  In my case, the issue was the URL for the page that was being displayed in the popup was not in my OAuth2 Redirect URLs list on the LinkedIn developer site.

That was easy to miss because the page URL from the page in the modal is not the URL that was currently showing in the browser's address bar.  Once I added the URL for the page being shown in the pop up it worked.


问:
Java - Dice roll combinations that amount to the same target value
The problem I'm having is with calculating from a set number of dice, and a set target value, what the best possible combination of dice is so that the most target value can be reached as many times as possible, without re-using a single dice.

To clarify, here is an example:
6 dice are used, holding the values: 1, 1, 1, 2, 4, 4 and the target that I want to reach is 5.

To get 5, I can combine the dice in different ways, for example 1+1+1+2 is five, as well as 4+1. But what I want is to be able to uniquely combine as many of the dice as possible to reach my target value as many times as I can. The combination I would have to go for in that case is: 4+1 and another 4+1, reaching my target value twice.

Doing this programmatically proved difficult though, any suggestions are greatly appreciated.

答:
The basic algorithm is to consider any dice present or non present. If the summation is less than a target continue. other wise return no result. If you hit the target return the seq.
You can do this recursively the for each combination toggle a consideration for a dice and continue until you reach/ pass the target value. The order would be 2^n.</p>


问:
Proper way to return private object in Python
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

```<code># My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()
</code>```

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

```<code>@property
def capabilities(self):
    return self._capabilities
</code>```

Or should I do this and return a copy to protect myself?

```<code>@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)
</code>```

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.

答:
Yes, attributes starting with one underscore are considered private. You can access or modify them but you shouldn't.

However when you create a public attribute you essentially give the user the permission that it's okay to modify what it returns. Python always returns references, the question is just if the reference is mutable or immutable, dictionaries and lists are mutable so they could change the contents, while other types like numbers and strings are immutable so they are "safe to return".

Instead of thinking about how to return a copy you should think about which "properties" and "methods" of _capabilities are of interest for a user. For example if you just want a "has_capability" and "value_of_capability" you could simply create functions for that:

```<code>class Channel(object):
    def __init__(self):
        self._capabilities = dict()

    def has_capability(self, capability):
        return capability in self._capabilities

    def value_of_capability(self, capability):
        return self._capabilities[capability]
</code>```

and likewise for other operations that should be supported. It doesn't make sense to hide an attribute and then to "expose" it (no matter if as reference or as copy). The problem with a copy is that it is slow and it's likely to lead to surprises because you can modify it but the changes don't propagate back. That's not really intuitive.

Body:
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

# My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

@property
def capabilities(self):
    return self._capabilities

Or should I do this and return a copy to protect myself?

@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.

Body:
Yes, attributes starting with one underscore are considered private. You can access or modify them but you shouldn't.

However when you create a public attribute you essentially give the user the permission that it's okay to modify what it returns. Python always returns references, the question is just if the reference is mutable or immutable, dictionaries and lists are mutable so they could change the contents, while other types like numbers and strings are immutable so they are "safe to return".

Instead of thinking about how to return a copy you should think about which "properties" and "methods" of _capabilities are of interest for a user. For example if you just want a "has_capability" and "value_of_capability" you could simply create functions for that:

class Channel(object):
    def __init__(self):
        self._capabilities = dict()

    def has_capability(self, capability):
        return capability in self._capabilities

    def value_of_capability(self, capability):
        return self._capabilities[capability]

and likewise for other operations that should be supported. It doesn't make sense to hide an attribute and then to "expose" it (no matter if as reference or as copy). The problem with a copy is that it is slow and it's likely to lead to surprises because you can modify it but the changes don't propagate back. That's not really intuitive.


问:
Python Decorators & Nested Functions return statement. Proper usage with parenthesis?
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')
</code>```

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

```<code>def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")
</code>```

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

答:
The difference is that with the parenthesis, you are not returning the decorator function. Rather, you are returning the return value of the function, which means you prematurely call the decorated function. If you didn't have parenthesis, your code would work correctly, and the function object inner would be returned.

In short, don't call the function. You need to return the actual function itself for your decorator to work correctly:

```<code>>>> def stars(func):
        def inner():
            print("*" * 50)
            func()
            print("*" * 50)
        return inner # Don't call inner, return it.

>>> @stars
def func():
    print('Decorate this message.')

>>> func()
**************************************************
Decorate this message.
**************************************************
>>>
</code>```

If you called inner anyway, Your message would've been printed when func() was defined instead of func() being called.

Body:
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

Body:
The difference is that with the parenthesis, you are not returning the decorator function. Rather, you are returning the return value of the function, which means you prematurely call the decorated function. If you didn't have parenthesis, your code would work correctly, and the function object inner would be returned.

In short, don't call the function. You need to return the actual function itself for your decorator to work correctly:

>>> def stars(func):
        def inner():
            print("*" * 50)
            func()
            print("*" * 50)
        return inner # Don't call inner, return it.

>>> @stars
def func():
    print('Decorate this message.')

>>> func()
**************************************************
Decorate this message.
**************************************************
>>>

If you called inner anyway, Your message would've been printed when func() was defined instead of func() being called.


问:
Facebook Graph Java HttpsURLConnection returns error 400
I'm trying to download some data from Facebook Graph via the web api and everything worked fine until now, somehow, this code is giving me a 400 error instead of the json response

```<code>URL url = new URL(link);
URLConnection urlConn = url.openConnection();

urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");

InputStreamReader in = new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in);
</code>```

When it reaches this line:

```<code>InputStreamReader in = new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8);
</code>```

It throws an IOException error with this message:

Server returned HTTP response code: 400 for URL: https://graph.facebook.com/v2.9/sear...

Opening that url in chrome returns the page just fine without errors.

-- EDIT --

If it helps, checking the header fields this is what it shows:

{Transfer-Encoding=[chunked], x-fb-trace-id=[G1Wlv7GX9w8],
  null=[HTTP/1.1 400 Bad Request], Access-Control-Allow-Origin=[*],
  WWW-Authenticate=[OAuth "Facebook Platform" "invalid_request" "(#613)
  Calls to this api have exceeded the rate limit."],
  Connection=[keep-alive], x-fb-rev=[3122154], Pragma=[no-cache],
  Date=[Wed, 28 Jun 2017 15:26:45 GMT], Cache-Control=[no-store],
  Vary=[Accept-Encoding], Expires=[Sat, 01 Jan 2000 00:00:00 GMT],
  X-FB-Debug=[REMOVED],
  facebook-api-version=[v2.9], Content-Type=[application/json;
  charset=UTF-8]}

I would understand the

Calls to this api have exceeded the rate limit

If it wasn't working in the browser either

答:
I tried your code and it works perfectly as long as the URL is correct.

For example when I removed the access_token from the URL query parameters it gave me the error HTTP 400.

Server returned HTTP response code: 400 for URL: https://graph.facebook.com/v2.9/me?&debug=all&fields=id,name&format=json&method=get&pretty=0

If I add the &access_token= back, it works like a charm for me.

Hoping you can see if anything like this happening on your side.

IF you could share the absolute URL obscuring your access token, I can debug further.

--EDIT--

Please use this code adjustment to print the reason of the HTTP 400 so you might figure out the root cause.

```<code>URL url = new URL(link);
    HttpURLConnection  urlConn = (HttpURLConnection) url.openConnection();

    urlConn.setRequestProperty("Content-Type", "application/json");
    urlConn.setRequestProperty("Accept-Charset", "UTF-8");
    urlConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");

    //InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
    InputStreamReader in = null;
    if (urlConn.getResponseCode() < urlConn.HTTP_BAD_REQUEST) {
        in = new InputStreamReader(urlConn.getInputStream());
    } else {
         /* error from server */
        in = new InputStreamReader(urlConn.getErrorStream());
    }

    BufferedReader reader = new BufferedReader(in);
    System.out.println(reader.readLine());
</code>```

Thanks!

Body:
I'm trying to download some data from Facebook Graph via the web api and everything worked fine until now, somehow, this code is giving me a 400 error instead of the json response

URL url = new URL(link);
URLConnection urlConn = url.openConnection();

urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
urlConn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");

InputStreamReader in = new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(in);

When it reaches this line:

InputStreamReader in = new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8);

It throws an IOException error with this message:

Server returned HTTP response code: 400 for URL: https://graph.facebook.com/v2.9/sear...

Opening that url in chrome returns the page just fine without errors.

-- EDIT --

If it helps, checking the header fields this is what it shows:

{Transfer-Encoding=[chunked], x-fb-trace-id=[G1Wlv7GX9w8],
  null=[HTTP/1.1 400 Bad Request], Access-Control-Allow-Origin=[*],
  WWW-Authenticate=[OAuth "Facebook Platform" "invalid_request" "(#613)
  Calls to this api have exceeded the rate limit."],
  Connection=[keep-alive], x-fb-rev=[3122154], Pragma=[no-cache],
  Date=[Wed, 28 Jun 2017 15:26:45 GMT], Cache-Control=[no-store],
  Vary=[Accept-Encoding], Expires=[Sat, 01 Jan 2000 00:00:00 GMT],
  X-FB-Debug=[REMOVED],
  facebook-api-version=[v2.9], Content-Type=[application/json;
  charset=UTF-8]}

I would understand the

Calls to this api have exceeded the rate limit

If it wasn't working in the browser either

Body:
I tried your code and it works perfectly as long as the URL is correct.

For example when I removed the access_token from the URL query parameters it gave me the error HTTP 400.

Server returned HTTP response code: 400 for URL: https://graph.facebook.com/v2.9/me?&debug=all&fields=id,name&format=json&method=get&pretty=0

If I add the &access_token= back, it works like a charm for me.

Hoping you can see if anything like this happening on your side.

IF you could share the absolute URL obscuring your access token, I can debug further.

--EDIT--

Please use this code adjustment to print the reason of the HTTP 400 so you might figure out the root cause.

URL url = new URL(link);
    HttpURLConnection  urlConn = (HttpURLConnection) url.openConnection();

    urlConn.setRequestProperty("Content-Type", "application/json");
    urlConn.setRequestProperty("Accept-Charset", "UTF-8");
    urlConn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0");

    //InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
    InputStreamReader in = null;
    if (urlConn.getResponseCode() < urlConn.HTTP_BAD_REQUEST) {
        in = new InputStreamReader(urlConn.getInputStream());
    } else {
         /* error from server */
        in = new InputStreamReader(urlConn.getErrorStream());
    }

    BufferedReader reader = new BufferedReader(in);
    System.out.println(reader.readLine());

Thanks!


问:
What's the relationship between sed, grep, find, awk, gawk, which one is preferred?
I'm new to Linux/Unix. I find some task can be accomplished by many ways using these commands. Is there some relationship between them? Or which one is preferred? Which one is outdated?

Thanks.

答:
See SO 366980 for discussion about the differences between Perl, Python, Awk and Sed.

There are four distinct commands in the list of five; awk and gawk are closely related, with GNU Awk being the GNU implementation of Awk.

find is for locating files in a set of directories based on file characteristics such as name or modification time.  GNU Find has many more capabilities than the traditional or POSIX versions of Find.

grep is for locating content within files using regular expressions to control what is selected.  GNU Grep has many more capabilities than the traditional or POSIX versions of Grep.

sed is for modifying the contents of files using editing commands, including regular expressions.  The GNU Sed has many more capabilities than the traditional or POSIX versions of Sed.

awk is a pattern matching and formatting language.  It is a programming language in a way that the other tools you mention are not.  When needed, it is very useful.  However, Perl and Python also have the capabilities of Awk and many extras, so many people use them instead of Awk.  GNU Awk has some more capabilities than the traditional or POSIX versions of Awk.

So, the tools you list do different jobs, but can work together in many ways.  One other tool you should be aware of is xargs, which takes lists of files and runs a specified command on each of the files in turn.


问:
ordering y axis with facet
I have this data frame

```<code>library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat %>% arrange(parent,-count )

 parent group value count
1      F  D(5)     4     5
2      F  A(4)     3     4
3      J  A(4)     1     4
4      J  C(3)     2     3
</code>```

You can see above that the data is ordered by parent and then count descending. I would like the chart to keep this ordering BUT when I plot it in the "J" chart C(3) comes on top of A(4) and that should be revered. How can that be done?

```<code>ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")
</code>```

答:
You can set your factor on the group column using the currently ordered values as the levels (reversed to get the ordering you want). This will lock in the ordering.</p>

```<code>library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat <- dat %>% arrange(parent,-count )

dat$group <- factor(dat$group, levels = rev(unique(dat$group)))

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")
</code>```

Title: ordering y axis with facet

Body:
I have this data frame

library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat %>% arrange(parent,-count )

 parent group value count
1      F  D(5)     4     5
2      F  A(4)     3     4
3      J  A(4)     1     4
4      J  C(3)     2     3

You can see above that the data is ordered by parent and then count descending. I would like the chart to keep this ordering BUT when I plot it in the "J" chart C(3) comes on top of A(4) and that should be revered. How can that be done?

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")

Body:
You can set your factor on the group column using the currently ordered values as the levels (reversed to get the ordering you want). This will lock in the ordering.

library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
                count = c(4,3,4,5))
dat <- dat %>% arrange(parent,-count )

dat$group <- factor(dat$group, levels = rev(unique(dat$group)))

ggplot(dat, aes(x = group, y= value))+
  geom_bar(stat ="identity",position = "dodge")+
  coord_flip()+
  facet_wrap(~parent, scale = "free_y")


问:
Android How to renewal ssl certificate without app updating in play store
I have used two types of Authorized certificates(commercial ca) used in my Android Studio mobile application inside raw folder.
first: .crt (for request encryption )
second: .bks ( request to server with SSL Pinning )

my .crt file expiry is 2 year only. I want to renewal my certificate without
updating my app to playstore. I have refereed many links. they are saying ,generate new certificate and use it in updated app and update the app in playstore option only.

Note: Please suggest, If any other way, without updating app in play store, i want to renewal my ca in mobile application run-timely.

Thanks Advance

I have refereed below links regarding my ssl certificate renewal

```<code>https://stackoverflow.com/questions/15788714/when-an-ssl-cert-is-renewed-does-an-android-bks-also-need-to-be-updated

https://stackoverflow.com/questions/24197201/how-do-i-update-the-ssl-cert-in-my-android-apps

https://stackoverflow.com/questions/33706984/android-how-to-store-certificate-in-keystore-programmatically

http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/

http://helpdesk.objects.com.au/java/how-do-i-programatically-extract-a-certificate-from-a-site-and-add-it-to-my-keystore

https://stackoverflow.com/questions/2012497/accepting-a-certificate-for-https-on-android

https://stackoverflow.com/questions/40935588/android-update-ssl-certificate
</code>```

答:
No, I'm afraid there's not.

When generating new certificates, the files are refreshed, so the app has to be done.

This has to make you rethink why your "architecture" is working that way, since certificates should be stored in servers, with their own backup and renewal programmed every certain amount of time.

Body:
I have used two types of Authorized certificates(commercial ca) used in my Android Studio mobile application inside raw folder.
first: .crt (for request encryption )
second: .bks ( request to server with SSL Pinning )

my .crt file expiry is 2 year only. I want to renewal my certificate without
updating my app to playstore. I have refereed many links. they are saying ,generate new certificate and use it in updated app and update the app in playstore option only.

Note: Please suggest, If any other way, without updating app in play store, i want to renewal my ca in mobile application run-timely.

Thanks Advance

I have refereed below links regarding my ssl certificate renewal

https://stackoverflow.com/questions/15788714/when-an-ssl-cert-is-renewed-does-an-android-bks-also-need-to-be-updated

https://stackoverflow.com/questions/24197201/how-do-i-update-the-ssl-cert-in-my-android-apps

https://stackoverflow.com/questions/33706984/android-how-to-store-certificate-in-keystore-programmatically

http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/

http://helpdesk.objects.com.au/java/how-do-i-programatically-extract-a-certificate-from-a-site-and-add-it-to-my-keystore

https://stackoverflow.com/questions/2012497/accepting-a-certificate-for-https-on-android

https://stackoverflow.com/questions/40935588/android-update-ssl-certificate


问:
Creating asynchronous WCF clients without using Service References
Currently I do not use Service References as I feel the code it autogenerates is more weight than I need. Instead I generate a proxy class by doing:

```<code>public class MyClient : ClientBase<IMyService>, IMyService
</code>```

This has worked great for me, no proxy classes are generated so I reuse the same datatypes. But this only lets me create synchronous client methods.

What would it take to generate async versions? I have taken a look at the autogenerated code that adding a Service Reference would do and it seems like soo much boilerplate. A ton of begin/end/onbegin/oncomplete associated event arg datatypes etc etc.

Is there a simpler way with less scaffolding needed to create async client methods?
My ultimate end goal is to be able to use the new c# 5 async/await keywords on webservice clients

答:
The CTP for async/await is just a preview of the support for these features. They plan to fully integrate them into WCF.

http://blogs.msdn.com/b/endpoint/archive/2010/11/13/simplified-asynchronous-programming-model-in-wcf-with-async-await.aspx

Body:
Currently I do not use Service References as I feel the code it autogenerates is more weight than I need. Instead I generate a proxy class by doing:

public class MyClient : ClientBase<IMyService>, IMyService

This has worked great for me, no proxy classes are generated so I reuse the same datatypes. But this only lets me create synchronous client methods.

What would it take to generate async versions? I have taken a look at the autogenerated code that adding a Service Reference would do and it seems like soo much boilerplate. A ton of begin/end/onbegin/oncomplete associated event arg datatypes etc etc.

Is there a simpler way with less scaffolding needed to create async client methods?
My ultimate end goal is to be able to use the new c# 5 async/await keywords on webservice clients


问:
Java 8 lambda predicate chaining?
I can't get it to compile, is it even possible to chain predicate lambdas?

```<code>Arrays.asList("1","2","3").stream().filter( (e -> e=="1" ).or(e-> e=="2") ).count();
</code>```

Or only way is to explicitly create a predicate and then combine like so:

```<code>Predicate<String> isOne= e -> e=="1";
Arrays.asList("1","2","3").stream().filter( isOne.or(e -> e=="2") ).count();
</code>```

Or is there more "functionally elegant" way to achieve same thing?

答:
Arrays.asList("1","2","3").stream().filter( Arrays.asList("1", "2")::contains).count();
```

<p>and yes method "either" is good idea</p>

<pre class="lang-java prettyprint-override"><code>    public static void main(String[] args) {
        long count = Arrays.asList("1","2","3").stream().filter(either("1"::equals).or("2"::equals)).count();
        System.out.println(count);
    }

    private static <T> Predicate<T> either(Predicate<T> predicate) {
        return predicate;
    }
</code>```

or you can use import static java.util.function.Predicate.isEqual;
and write isEqual("1").or(isEqual("2"))

Title: Java 8 lambda predicate chaining?

Body:
I can't get it to compile, is it even possible to chain predicate lambdas?

Arrays.asList("1","2","3").stream().filter( (e -> e=="1" ).or(e-> e=="2") ).count();

Or only way is to explicitly create a predicate and then combine like so:

Predicate<String> isOne= e -> e=="1";
Arrays.asList("1","2","3").stream().filter( isOne.or(e -> e=="2") ).count();

Or is there more "functionally elegant" way to achieve same thing?

Body:
Arrays.asList("1","2","3").stream().filter( Arrays.asList("1", "2")::contains).count();

and yes method "either" is good idea

    public static void main(String[] args) {
        long count = Arrays.asList("1","2","3").stream().filter(either("1"::equals).or("2"::equals)).count();
        System.out.println(count);
    }

    private static <T> Predicate<T> either(Predicate<T> predicate) {
        return predicate;
    }

or you can use import static java.util.function.Predicate.isEqual;
and write isEqual("1").or(isEqual("2"))


问:
Creating Nested Class
I am trying to create a nested class in VBA.

So far I have successfully created the following:

```<code>OurCompany.Department.Employee("John")
</code>```

How can I create a few groups of Department so I can store the data seperately.
Something like this

```<code>OurCompany.Department("Finance").Employee("John") = "Employee Number 100"
OurCompany.Department("Finance").Employee("Kim") = "Employee Number 101"
OurCompany.Department("Engineering").Employee("Sam") = "Employee Number 124"
</code>```

cDeparment Class

```<code>Private pDepartmentEmployee As Collection
Public Property Get Department(RefString As String) As cEmployee

    Set Department = pDepartment.Item(RefString)

End Property

Public Property Set Department(RefString As String, ByVal objDepartEmployee As cEmployee)

    pDepartmentEmployee.Add objDepartEmployee, RefString

End Property
</code>```

cEmployee Class

```<code>Private pEmployee As Collection
Public Property Get Employee(RefKey As String) As String

    Employee = pEmployee.Item(RefKey)

End Property

Public Property Let Employee(RefKey As String, RefItem As String)

    pEmployee.Add Item:=RefItem, Key:=RefKey

End Property
</code>```

答:
Here you could create object model with classes like this:

```<code>Company -> has Departments -> Department -> has Employees -> Employee
</code>```

To create wrapper classes like Departments and Employees may seen to be purposeless but consider the fact that the VBA.Collection can hold anything not just only instances of Department or Employee so this way the collection wrapper ensures, that the collection holds only objects of certain type.

```<code>Dim col As VBA.Collection
Set col = New VBA.Collection

col.Add 123, CStr(123)
col.Add Range("A1:C3"), "Range(""A1:C3"")"
col.Add "banana", "banana"

Dim wing As Employee
Set wing = New Employee
wing.Id = 200
wing.Name = "Wing"

col.Add wing, CStr(wing.Id)

Debug.Print col.Count ' Prints 4
</code>```

Simple example, HTH.

Company

```<code>Private m_departmets As Departmets

Public Property Get Departmets() As Departmets
    Set Departmets = m_departmets
End Property

Private Sub Class_Initialize()
    Set m_departmets = New Departmets
End Sub
</code>```

Departments

```<code>Private m_items As VBA.Collection

Private Sub Class_Initialize()
    Set m_items = New VBA.Collection
End Sub

Public Sub AddItem(newItem As Department)
    m_items.Add newItem, newItem.Name
End Sub

Public Function GetItem(Name As String) As Department
    Set GetItem = m_items(Name)
End Function
</code>```

Department

```<code>Private m_name As String
Private m_employees As Employees

Public Property Get Name() As String
    Name = m_name
End Property

Public Property Let Name(ByVal vNewValue As String)
    m_name = vNewValue
End Property

Public Property Get Employees() As Employees
    Set Employees = m_employees
End Property

Private Sub Class_Initialize()
    Set m_employees = New Employees
End Sub
</code>```

Employees

```<code>Private m_items As VBA.Collection

Private Sub Class_Initialize()
    Set m_items = New VBA.Collection
End Sub

Public Sub AddItem(newItem As Employee)
    m_items.Add newItem, VBA.CStr(newItem.Id)
End Sub

Public Function GetItem(Id As Long) As Employee
    Set GetItem = m_items(VBA.CStr(Id))
End Function
</code>```

Employee

```<code>Private m_name As String
Private m_id As Long

Public Property Get Name() As String
    Name = m_name
End Property

Public Property Let Name(ByVal vNewValue As String)
    m_name = vNewValue
End Property

Public Property Get Id() As Long
    Id = m_id
End Property

Public Property Let Id(ByVal vNewValue As Long)
    m_id = vNewValue
End Property
</code>```

Test

```<code>Sub Test()
    Dim john As Employee
    Dim kim As Employee
    Dim sam As Employee
    Dim financeDepartment As Department
    Dim engineeringDepartment As Department
    Dim ourCompany As Company

    Set john = New Employee
    Set kim = New Employee
    Set sam = New Employee

    john.Name = "John"
    john.Id = 100
    kim.Name = "Kim"
    kim.Id = 101
    sam.Name = "Sam"
    sam.Id = 124

    Set financeDepartment = New Department
    Set engineeringDepartment = New Department

    financeDepartment.Name = "Finance"
    engineeringDepartment.Name = "Engineering"

    financeDepartment.Employees.AddItem john
    financeDepartment.Employees.AddItem kim
    engineeringDepartment.Employees.AddItem sam

    Set ourCompany = New Company
    ourCompany.Departmets.AddItem financeDepartment
    ourCompany.Departmets.AddItem engineeringDepartment

    Debug.Print ourCompany.Departmets.GetItem("Finance").Employees.GetItem(100).Name
    Debug.Print ourCompany.Departmets.GetItem("Finance").Employees.GetItem(101).Name
    Debug.Print ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name

    ' Change name of Sam to Samuel
    ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name = "Samuel"
    Debug.Print ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name
End Sub
</code>```

Output

```<code>John
Kim
Sam
Samuel
</code>```

ContentLicense: CC BY-SA 4.0

Title: Creating Nested Class

Body:
I am trying to create a nested class in VBA.

So far I have successfully created the following:

OurCompany.Department.Employee("John")

How can I create a few groups of Department so I can store the data seperately.
Something like this

OurCompany.Department("Finance").Employee("John") = "Employee Number 100"
OurCompany.Department("Finance").Employee("Kim") = "Employee Number 101"
OurCompany.Department("Engineering").Employee("Sam") = "Employee Number 124"

cDeparment Class

Private pDepartmentEmployee As Collection
Public Property Get Department(RefString As String) As cEmployee

    Set Department = pDepartment.Item(RefString)

End Property

Public Property Set Department(RefString As String, ByVal objDepartEmployee As cEmployee)

    pDepartmentEmployee.Add objDepartEmployee, RefString

End Property

cEmployee Class

Private pEmployee As Collection
Public Property Get Employee(RefKey As String) As String

    Employee = pEmployee.Item(RefKey)

End Property

Public Property Let Employee(RefKey As String, RefItem As String)

    pEmployee.Add Item:=RefItem, Key:=RefKey

End Property

Body:
Here you could create object model with classes like this:

Company -> has Departments -> Department -> has Employees -> Employee

To create wrapper classes like Departments and Employees may seen to be purposeless but consider the fact that the VBA.Collection can hold anything not just only instances of Department or Employee so this way the collection wrapper ensures, that the collection holds only objects of certain type.

Dim col As VBA.Collection
Set col = New VBA.Collection

col.Add 123, CStr(123)
col.Add Range("A1:C3"), "Range(""A1:C3"")"
col.Add "banana", "banana"

Dim wing As Employee
Set wing = New Employee
wing.Id = 200
wing.Name = "Wing"

col.Add wing, CStr(wing.Id)

Debug.Print col.Count ' Prints 4

Simple example, HTH.

Company

Private m_departmets As Departmets

Public Property Get Departmets() As Departmets
    Set Departmets = m_departmets
End Property

Private Sub Class_Initialize()
    Set m_departmets = New Departmets
End Sub

Departments

Private m_items As VBA.Collection

Private Sub Class_Initialize()
    Set m_items = New VBA.Collection
End Sub

Public Sub AddItem(newItem As Department)
    m_items.Add newItem, newItem.Name
End Sub

Public Function GetItem(Name As String) As Department
    Set GetItem = m_items(Name)
End Function

Department

Private m_name As String
Private m_employees As Employees

Public Property Get Name() As String
    Name = m_name
End Property

Public Property Let Name(ByVal vNewValue As String)
    m_name = vNewValue
End Property

Public Property Get Employees() As Employees
    Set Employees = m_employees
End Property

Private Sub Class_Initialize()
    Set m_employees = New Employees
End Sub

Employees

Private m_items As VBA.Collection

Private Sub Class_Initialize()
    Set m_items = New VBA.Collection
End Sub

Public Sub AddItem(newItem As Employee)
    m_items.Add newItem, VBA.CStr(newItem.Id)
End Sub

Public Function GetItem(Id As Long) As Employee
    Set GetItem = m_items(VBA.CStr(Id))
End Function

Employee

Private m_name As String
Private m_id As Long

Public Property Get Name() As String
    Name = m_name
End Property

Public Property Let Name(ByVal vNewValue As String)
    m_name = vNewValue
End Property

Public Property Get Id() As Long
    Id = m_id
End Property

Public Property Let Id(ByVal vNewValue As Long)
    m_id = vNewValue
End Property

Test

Sub Test()
    Dim john As Employee
    Dim kim As Employee
    Dim sam As Employee
    Dim financeDepartment As Department
    Dim engineeringDepartment As Department
    Dim ourCompany As Company

    Set john = New Employee
    Set kim = New Employee
    Set sam = New Employee

    john.Name = "John"
    john.Id = 100
    kim.Name = "Kim"
    kim.Id = 101
    sam.Name = "Sam"
    sam.Id = 124

    Set financeDepartment = New Department
    Set engineeringDepartment = New Department

    financeDepartment.Name = "Finance"
    engineeringDepartment.Name = "Engineering"

    financeDepartment.Employees.AddItem john
    financeDepartment.Employees.AddItem kim
    engineeringDepartment.Employees.AddItem sam

    Set ourCompany = New Company
    ourCompany.Departmets.AddItem financeDepartment
    ourCompany.Departmets.AddItem engineeringDepartment

    Debug.Print ourCompany.Departmets.GetItem("Finance").Employees.GetItem(100).Name
    Debug.Print ourCompany.Departmets.GetItem("Finance").Employees.GetItem(101).Name
    Debug.Print ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name

    ' Change name of Sam to Samuel
    ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name = "Samuel"
    Debug.Print ourCompany.Departmets.GetItem("Engineering").Employees.GetItem(124).Name
End Sub

Output

John
Kim
Sam
Samuel


问:
Facebook webhook for leadgen - Can't retrieve Facebook Lead Ads
I follow this Facebook's guide:
https://www.facebook.com/marketingdevelopers/videos/883648801749520/

I set up successfully all these steps:

In the "developers.facebook.com/apps/APP-ID", I add "webhooks" product and create subscription to page and subscribe to leadgen, In addition, I verified my callback_url successfully

I create a new page that used Facebook Javascript SDK and I send a post request using FB.api with the user page access token to the page subscribed_apps and the API returns me "{success:true}", I double checked if that worked with the Facebook graph by sending the same request just with GET method and it return me and object that looks like that:
{ "data": [ { "link": "https://www.my-url.com/", "name": "my app name", "id": "my app id" } ] }

Now, all I had to do is to send a test to my lead ad and get an update notification to my callback_url which is

```<code>https://www.my-domain.com/admin/webhook
</code>```

I tried 2 different ways, the first is from my app subscription, I don't get any error but nothing happened

the second way was with "Lead ads testing tool"

https://developers.facebook.com/tools/lead-ads-testing

and I'm receiving an error with error code 301 that says "rejected"

答:
Finally, after hours of searching I found this answer:
Facebook Messenger webhook setup, but not triggered

and I send curl to my server and also got 301,
so I realized that the issue was with my htaccess file, I could not fix it so I move the webhook.php to my main domain and now it works!

Body:
I follow this Facebook's guide:
https://www.facebook.com/marketingdevelopers/videos/883648801749520/

I set up successfully all these steps:

In the "developers.facebook.com/apps/APP-ID", I add "webhooks" product and create subscription to page and subscribe to leadgen, In addition, I verified my callback_url successfully

I create a new page that used Facebook Javascript SDK and I send a post request using FB.api with the user page access token to the page subscribed_apps and the API returns me "{success:true}", I double checked if that worked with the Facebook graph by sending the same request just with GET method and it return me and object that looks like that:
{ "data": [ { "link": "https://www.my-url.com/", "name": "my app name", "id": "my app id" } ] }

Now, all I had to do is to send a test to my lead ad and get an update notification to my callback_url which is

https://www.my-domain.com/admin/webhook

I tried 2 different ways, the first is from my app subscription, I don't get any error but nothing happened

the second way was with "Lead ads testing tool"

https://developers.facebook.com/tools/lead-ads-testing

and I'm receiving an error with error code 301 that says "rejected"


问:
Add user to a Json list #PHP #JS
We are trying to add some new user to a Json file from a frontend form.

We pass the code taken from the form via Js, after that we are trying (Via PHP) to pass the value inserted by the user in a json file.

Extract from HTML

```<code>  <div class="log">
                    <p>Username Nuovo Utente</p>
                    <input class="nome" id="nuovoUtente" placeholder="inserisci il nome"><br>
                    <p>Password Password Nuovo Utente</p>
                    <input type="password" id="nuovaPsw" class="psw"> <br>
                    <button type="submit" class="lo" id="aggiunto">Aggiungi Nuovo Utente</button>
                </div>
</code>```

Extract from the js file

```<code> let newNom = document.getElementById('nuovoUtente');
   let newPass = document.getElementById('nuovaPsw');

   aggiunto.onclick=function(){
       $.get("utenti.php", { nome: newNom.value , pw: newPass.value });
   }
</code>```

Php file

```<code>  <?php
    $data[] = $_GET['data'];
    console.log($data[]);
    $inp = file_get_contents('pindex.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('pindex.json', $jsonData);
    ?>
</code>```

答:
Maybe your "pindex.json" JSON file is badly formatted and the json_encode function is returning null.

Since you did not tell me how json is, I did this example.
Called users.json

```<code>{
  "users" : [
    {"nome" : "GeekSilva", "pw" : "123"}
  ]
}
</code>```

The PHP code would look like this.

```<code>$nome = $_GET['nome'];
$pw = $_GET['pw'];

$data = ['nome' => $nome, 'pw' => $pw];

$inp = file_get_contents('users.json');

//Passing the second parameter to true will be returned as an array
$tempArray = json_decode($inp, true);

// push to $tempArray
$tempArray['users'][] = $data;

$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
</code>```

With the second parameter of the json_decode function we get an array and from there we can add an element with the parameters passed via AJAX.

Title: Add user to a Json list #PHP #JS

Body:
We are trying to add some new user to a Json file from a frontend form.

We pass the code taken from the form via Js, after that we are trying (Via PHP) to pass the value inserted by the user in a json file.

Extract from HTML

Username Nuovo Utente

                    <input class="nome" id="nuovoUtente" placeholder="inserisci il nome">

Password Password Nuovo Utente

                    <input type="password" id="nuovaPsw" class="psw">

                    <button type="submit" class="lo" id="aggiunto">Aggiungi Nuovo Utente</button>

Extract from the js file

 let newNom = document.getElementById('nuovoUtente');
   let newPass = document.getElementById('nuovaPsw');

   aggiunto.onclick=function(){
       $.get("utenti.php", { nome: newNom.value , pw: newPass.value });
   }

Php file

  <?php
    $data[] = $_GET['data'];
    console.log($data[]);
    $inp = file_get_contents('pindex.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('pindex.json', $jsonData);
    ?>

Body:
Maybe your "pindex.json" JSON file is badly formatted and the json_encode function is returning null.

Since you did not tell me how json is, I did this example.
Called users.json

{
  "users" : [
    {"nome" : "GeekSilva", "pw" : "123"}
  ]
}

The PHP code would look like this.

$nome = $_GET['nome'];
$pw = $_GET['pw'];

$data = ['nome' => $nome, 'pw' => $pw];

$inp = file_get_contents('users.json');

//Passing the second parameter to true will be returned as an array
$tempArray = json_decode($inp, true);

// push to $tempArray
$tempArray['users'][] = $data;

$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);

With the second parameter of the json_decode function we get an array and from there we can add an element with the parameters passed via AJAX.


问:
How to secure passwords in the Software Development?
how do you secure your passwords in propertie Files?
Encryption / Encoding?

Or do you use a different approach to handle Database User / Passwords for connection Strings?

Thanks for you help!

Update: Thanks for your responses! In this special case we talk about two tier architecture. We have many clients with direct connections to the databases. Propertie Files are on a network share.

答: For connection strings to database I use mostly jndi connections. And there I can encrypt the passwords: http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html#Digested_Passwords</p>


问:
Selecting another HTML element from an ng-click attribute
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>
</code>```

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

```<code><input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>
</code>```

答:
My solution was to use Angular's element selector to point to the input element holding the file, and then pass the result of that as the parameter into the function, like so:

```<code><input type="file" id="scvFileUploadId" />

<button id="uploadFilesubmit" onclick="angular.element(this).controller().uploadFile(angular.element(document.querySelector('#csvFileUploadID'))[0].files[0])">Upload</button>
</code>```

I'm not sure if this solution is the most 'Angular' way of doing it, but there were existing workarounds for some lack of support with Angular input file uploading being done on this part of the application that forced me to interact with DOM, so this does suffice in my scenario.

Body:
I am attempting to pass a file into a function, where the file is originated from an input type of file.  My code looks something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile()">Upload</button>

In short, I would like to take the file that has been added to the input and pass it into the parameter of the function of the ng-click attribute that is fired when the button is clicked.  I think this may be simple, but I cannot wrap my head around it at the moment.

I'm trying to do something like this.

<input type="file" id="scvFileUploadId"/>

<button id="uploadFilesubmit" ng-click"ctrl.uploadFile(#scvFileUploadId.file)">Upload</button>

Body:
My solution was to use Angular's element selector to point to the input element holding the file, and then pass the result of that as the parameter into the function, like so:

<input type="file" id="scvFileUploadId" />

<button id="uploadFilesubmit" onclick="angular.element(this).controller().uploadFile(angular.element(document.querySelector('#csvFileUploadID'))[0].files[0])">Upload</button>

I'm not sure if this solution is the most 'Angular' way of doing it, but there were existing workarounds for some lack of support with Angular input file uploading being done on this part of the application that forced me to interact with DOM, so this does suffice in my scenario.


问:
JUnit @BeforeClass annotation compiles fine in IDE but fails Maven build
When I write a simple method as follows:

```<code> @BeforeClass
 public void setUp(){}
</code>```

it compiles properly both in IntellijIDEA and Eclipse (using built in IDE Build).
However the same fragment of code fails a Maven run:

```<code>Tests in error:
  initializationError(TestClass): Method setUp() should be static
</code>```

Should have not this error been caught during compilation?

答: The retention type of @BeforeClass annotation is RUNTIME, thus it will be reported when you execute it.

Body:
When I write a simple method as follows:

 @BeforeClass
 public void setUp(){}

it compiles properly both in IntellijIDEA and Eclipse (using built in IDE Build).
However the same fragment of code fails a Maven run:

Tests in error:
  initializationError(TestClass): Method setUp() should be static

Should have not this error been caught during compilation?