问:
Calling event click with JavaScript
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

```<code>protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }
</code>```

答:
Assign an onClick listener to your button.</p>

```<code>document.getElementById("your-id").click = function () {
    newButton_Click();
}
</code>```

Title: Calling event click with JavaScript

Body:
It is possible to call a event click with JavaScript? how?

I'm trying to call this event when a button get clicked.

I'm creating Buttons dynamically so the id's change constantly

Here is how i make the buttons dynamically and assign the event click

protected void Page_Init(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            List<Button> Botones = new List<Button>();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += new System.EventHandler(newButton_Click);

                Botones.Add(newButton);

                GoodPanel.Controls.Add(newButton);
                newButton.CssClass = "btn-primary outline separate";
            }
        }

protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);

            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }

Body:
Assign an onClick listener to your button.

document.getElementById("your-id").click = function () {
    newButton_Click();
}


来源: stackexchange

问:
My PHP code is not picking up the variables when using the mail function
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

```<code>    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>
</code>```

The html code is provided below, not sure why $_POST is not pulling through.

```<code><!DOCTYPE html>
<html>
<head>
    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            <label for ="name">Name:</label>
            <input type="text" id="name" name="name">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email">
            <label for="pickup"> Pick Up Location</label>
            <input type="text" id="pickup" name="pickup">
            <label>Time:</label>
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            <label>:</label>
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
            <label for="destination"> Destination Postal Code</label>
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

</body>
</html>
</code>```

答:
post always in upper case.$_POST['variable name'] then try it.

try this after $_POST implementation not working:

```<code>$message = <<<EOD
    Hi,
    Please pick up {$name}from {pickup} and drop to {$destination}
    EOD;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My PHP code is not picking up the variables in $message, when $message is sent to an email address using the mail function the variables are missing. Not sure what I am doing wrong.

    <?php

    $to = 'test@email.com';
    $subject = 'Booking';

    $name = $_post['name'];
    $email = $_post['email'];
    $pickup = $_post['pickup'];
    $destination = $_post['destination'];

    $message = <<<Email
    Hi,
    Please pick up $name from $pickup and drop to $destination
    Email;

    $header = $email;

    mail($to, $subject, $message, $header);

    echo "Message Sent";

    ?>

The html code is provided below, not sure why $_POST is not pulling through.

<!DOCTYPE html>

    <title>Sign Up</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

    <form action="form.php" method="POST">
        <fieldset>
            <legend>Book your Journey</legend>
            Name:
            <input type="text" id="name" name="name">
            Email:
            <input type="email" id="email" name="email">
             Pick Up Location
            <input type="text" id="pickup" name="pickup">
            Time:
            <select>
                <option>--HR--</option>
                <option value="1">01</option>
                <option value="2">02</option>
                <option value="3">03</option>
                <option value="4">04</option>
                <option value="5">05</option>
                <option value="6">06</option>
                <option value="7">07</option>
                <option value="8">08</option>
                <option value="9">09</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
            </select>
            :
            <select>
                <option>--MIN--</option>
                <option value="00">00</option>
                <option value="15">15</option>
                <option value="30">30</option>
                <option value="45">45</option>
            </select>
            <select>
                <option value="am">am</option>
                <option value="pm">pm</option>
            </select>
            </fieldset>
            <fieldset>
             Destination Postal Code
            <input type="text" id="destination" name="destination">
        </fieldset>
        <button>Submit</button>
    </form>

Body:
post always in upper case.$_POST['variable name'] then try it.

try this after $_POST implementation not working:

$message = <<<EOD
    Hi,
    Please pick up {$name}from {pickup} and drop to {$destination}
    EOD;


问:
Dynamic bean selection
I have a service I write with Spring Boot. There are three beans in the service. I can statically run the bean that I want in the test phase with the qualifier annotation, but I want the user to be able to dynamically select the bean that he wants. How do I run the selected Bean?</p>

答: You can have a common interface for all the three beans and have this interface in your service with @autowired. From your test program you can inject whatever bean you want in to this service.</p>

Title: Dynamic bean selection


问:
Decode base64 data on iOS
I have a base64 string that I can decode on macOS by breaking the string into 16 bytes (characters) per line then using OpenSSL to decode:

Sample data.enc:

```<code>RwSBFR7iQ5vQYLqZ
E60hJEyOaU4VVGcq
tvnB2A1zQEylNdN9
tTZIOfwGMwDbMZln
nvT7lm80L1MkvDNH
qivdRAV4Ymtizw3F
d3GWBZ+xFVIAk0H3
lQWzAr43G7TRCYfc
r5Ijuj0qGIEF1FLp
Y6tlYNMI0C3J6UXH
qnd3vu4XuwIHi1gV
ciOxuP+iqgjvjM3O
qy8sU0YITC3ywxPA
Sh14azvcPu9F1/KY
S1J1JzN3XsTzscHf
kdry0hbz5H0l+6Um
Uz9Sb9HTGxxx9mwF
B821I8DfZc2RGx8W
mFuaNzgLFhS6CdwF
G9yALPk4wBUqIxEA
y4w/oLPosQqZ7Z9L
JnQ4SA==
</code>```

Decode command:

openssl enc -d -base64 -in data.enc -out data.bin

Here is the RAW base64 encoded string:

```<code>R3LSQUyakgQKXoxCqw/v/o2LwPPthWSOgoyCKV/p60WE7tIVLTIf0mGiSGhXwK91cXYygsCoXyTEdMY4bquMhhV09R2DXVVD79IXBp+7mGSdTcYh4FUvZCMUmWCqjje2PiZUXIzfDgwrJcxKplNrX6T/oc70quz/X4rZv1Qu6BMDBzF/otsC0Q1qx3QzUobxsRaUaCltb1CSdExTZ3zWR8anuz5eaBct3ymM8XNA8zYv6CB44/P+yS6CqGOza/a5R5x04A06Un0hu+d+hsSxW2F9zdeODz3t7cPVZYiW9nyC9XzIXH01Oi25uHuC0otxLlfXU4adMHB4Lj6YrA3Uxg==
</code>```

The data in data.bin is PKI encrypted and I can decrypt it on iOS just fine. If I cat data.bin I see (only showing the first few characters) of the encrypted data:

Gr?AL??
^?B????????d????)_??E???-2?a?HhW??uqv2???

However, on iOS if I try:

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"enc"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData *data = [[NSData alloc] initWithBase64EncodedString:text options:0];
</code>```

Then data is always nil.

答:
Note: The Base64 decoded output is not a string, it is binary data. You are getting nil returned because it is not a UTF-8 string and arbitrary data is generally not valid UTF-8.

```<code>NSString *base64 = @"RwSBFR7iQ5vQYLqZE60hJEyOaU4VVGcqtvnB2A1zQEylNdN9tTZIOfwGMwDbMZlnnvT7lm80L1MkvDNHqivdRAV4Ymtizw3Fd3GWBZ+xFVIAk0H3lQWzAr43G7TRCYfcr5Ijuj0qGIEF1FLpY6tlYNMI0C3J6UXHqnd3vu4XuwIHi1gVciOxuP+iqgjvjM3Oqy8sU0YITC3ywxPASh14azvcPu9F1/KYS1J1JzN3XsTzscHfkdry0hbz5H0l+6UmUz9Sb9HTGxxx9mwFB821I8DfZc2RGx8WmFuaNzgLFhS6CdwFG9yALPk4wBUqIxEAy4w/oLPosQqZ7Z9LJnQ4SA==";
NSLog(@"base64: %@", base64);
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64 options:nil];
NSLog(@"data: %@", data);
</code>```

Output:

```<code>base64: RwSBFR7iQ5vQYLqZE60hJEyOaU4VVGcqtvnB2A1zQEylNdN9tTZIOfwGMwDbMZlnnvT7lm80L1MkvDNHqivdRAV4Ymtizw3Fd3GWBZ+xFVIAk0H3lQWzAr43G7TRCYfcr5Ijuj0qGIEF1FLpY6tlYNMI0C3J6UXHqnd3vu4XuwIHi1gVciOxuP+iqgjvjM3Oqy8sU0YITC3ywxPASh14azvcPu9F1/KYS1J1JzN3XsTzscHfkdry0hbz5H0l+6UmUz9Sb9HTGxxx9mwFB821I8DfZc2RGx8WmFuaNzgLFhS6CdwFG9yALPk4wBUqIxEAy4w/oLPosQqZ7Z9LJnQ4SA==

data: <47048115 1ee2439b d060ba99 13ad2124 4c8e694e 1554672a b6f9c1d8 0d73404c a535d37d b5364839 fc063300 db319967 9ef4fb96 6f342f53 24bc3347 aa2bdd44 0578626b 62cf0dc5 77719605 9fb11552 009341f7 9505b302 be371bb4 d10987dc af9223ba 3d2a1881 05d452e9 63ab6560 d308d02d c9e945c7 aa7777be ee17bb02 078b5815 7223b1b8 ffa2aa08 ef8ccdce ab2f2c53 46084c2d f2c313c0 4a1d786b 3bdc3eef 45d7f298 4b527527 33775ec4 f3b1c1df 91daf2d2 16f3e47d 25fba526 533f526f d1d31b1c 71f66c05 07cdb523 c0df65cd 911b1f16 985b9a37 380b1614 ba09dc05 1bdc802c f938c015 2a231100 cb8c3fa0 b3e8b10a 99ed9f4b 26743848>
</code>```

Title: Decode base64 data on iOS

Body:
I have a base64 string that I can decode on macOS by breaking the string into 16 bytes (characters) per line then using OpenSSL to decode:

Sample data.enc:

RwSBFR7iQ5vQYLqZ
E60hJEyOaU4VVGcq
tvnB2A1zQEylNdN9
tTZIOfwGMwDbMZln
nvT7lm80L1MkvDNH
qivdRAV4Ymtizw3F
d3GWBZ+xFVIAk0H3
lQWzAr43G7TRCYfc
r5Ijuj0qGIEF1FLp
Y6tlYNMI0C3J6UXH
qnd3vu4XuwIHi1gV
ciOxuP+iqgjvjM3O
qy8sU0YITC3ywxPA
Sh14azvcPu9F1/KY
S1J1JzN3XsTzscHf
kdry0hbz5H0l+6Um
Uz9Sb9HTGxxx9mwF
B821I8DfZc2RGx8W
mFuaNzgLFhS6CdwF
G9yALPk4wBUqIxEA
y4w/oLPosQqZ7Z9L
JnQ4SA==

Decode command:

openssl enc -d -base64 -in data.enc -out data.bin

Here is the RAW base64 encoded string:

R3LSQUyakgQKXoxCqw/v/o2LwPPthWSOgoyCKV/p60WE7tIVLTIf0mGiSGhXwK91cXYygsCoXyTEdMY4bquMhhV09R2DXVVD79IXBp+7mGSdTcYh4FUvZCMUmWCqjje2PiZUXIzfDgwrJcxKplNrX6T/oc70quz/X4rZv1Qu6BMDBzF/otsC0Q1qx3QzUobxsRaUaCltb1CSdExTZ3zWR8anuz5eaBct3ymM8XNA8zYv6CB44/P+yS6CqGOza/a5R5x04A06Un0hu+d+hsSxW2F9zdeODz3t7cPVZYiW9nyC9XzIXH01Oi25uHuC0otxLlfXU4adMHB4Lj6YrA3Uxg==

The data in data.bin is PKI encrypted and I can decrypt it on iOS just fine. If I cat data.bin I see (only showing the first few characters) of the encrypted data:

Gr?AL??
^?B????????d????)_??E???-2?a?HhW??uqv2???

However, on iOS if I try:

NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"enc"];
NSString *text = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData *data = [[NSData alloc] initWithBase64EncodedString:text options:0];

Then data is always nil.

Body:
Note: The Base64 decoded output is not a string, it is binary data. You are getting nil returned because it is not a UTF-8 string and arbitrary data is generally not valid UTF-8.

NSString *base64 = @"RwSBFR7iQ5vQYLqZE60hJEyOaU4VVGcqtvnB2A1zQEylNdN9tTZIOfwGMwDbMZlnnvT7lm80L1MkvDNHqivdRAV4Ymtizw3Fd3GWBZ+xFVIAk0H3lQWzAr43G7TRCYfcr5Ijuj0qGIEF1FLpY6tlYNMI0C3J6UXHqnd3vu4XuwIHi1gVciOxuP+iqgjvjM3Oqy8sU0YITC3ywxPASh14azvcPu9F1/KYS1J1JzN3XsTzscHfkdry0hbz5H0l+6UmUz9Sb9HTGxxx9mwFB821I8DfZc2RGx8WmFuaNzgLFhS6CdwFG9yALPk4wBUqIxEAy4w/oLPosQqZ7Z9LJnQ4SA==";
NSLog(@"base64: %@", base64);
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64 options:nil];
NSLog(@"data: %@", data);

Output:

base64: RwSBFR7iQ5vQYLqZE60hJEyOaU4VVGcqtvnB2A1zQEylNdN9tTZIOfwGMwDbMZlnnvT7lm80L1MkvDNHqivdRAV4Ymtizw3Fd3GWBZ+xFVIAk0H3lQWzAr43G7TRCYfcr5Ijuj0qGIEF1FLpY6tlYNMI0C3J6UXHqnd3vu4XuwIHi1gVciOxuP+iqgjvjM3Oqy8sU0YITC3ywxPASh14azvcPu9F1/KYS1J1JzN3XsTzscHfkdry0hbz5H0l+6UmUz9Sb9HTGxxx9mwFB821I8DfZc2RGx8WmFuaNzgLFhS6CdwFG9yALPk4wBUqIxEAy4w/oLPosQqZ7Z9LJnQ4SA==

data: <47048115 1ee2439b d060ba99 13ad2124 4c8e694e 1554672a b6f9c1d8 0d73404c a535d37d b5364839 fc063300 db319967 9ef4fb96 6f342f53 24bc3347 aa2bdd44 0578626b 62cf0dc5 77719605 9fb11552 009341f7 9505b302 be371bb4 d10987dc af9223ba 3d2a1881 05d452e9 63ab6560 d308d02d c9e945c7 aa7777be ee17bb02 078b5815 7223b1b8 ffa2aa08 ef8ccdce ab2f2c53 46084c2d f2c313c0 4a1d786b 3bdc3eef 45d7f298 4b527527 33775ec4 f3b1c1df 91daf2d2 16f3e47d 25fba526 533f526f d1d31b1c 71f66c05 07cdb523 c0df65cd 911b1f16 985b9a37 380b1614 ba09dc05 1bdc802c f938c015 2a231100 cb8c3fa0 b3e8b10a 99ed9f4b 26743848>


问:
Running SPSS session action from an external Python script
I have a Python 2.7 script that among others contains the following piece of code:

```<code>import spss

columns = []

spss.StartDataStep()
dataset = spss.Dataset()
for column in dataset.varlist:
    columns.append(column.name)
spss.EndDataStep()

print columns
</code>```

When running this code inside a SPSS syntax (so between BEGIN PROGRAM. and END PROGRAM), it runs as expected and I end up with the variables in the active dataset.

However, when running the same code as part of a script (so from Utilities > Run script...) will return me no results.

It looks as if the SPSS session context is not taken into consideration when running a script.

Is there a way around this problem, or am I doing something wrong?
I don't want to run my code as part of Syntax file, I just want to use vanilla Python scripts.

答:
This is, unfortunately, a complicated issue.  I don't think Statistics is working as documented.  I will take this up with Development.

It appears that in V24, when you run a Python script via Utilities > Run Script (which is the same as issuing the SCRIPT command), your script is connected to the Statistics Viewer process but not to the Statistics backend (the spssengine process), which is where the data live.  There are typically three processes running - the stats.exe process, the spssengine process, and, for Python code, the startx process.  Your script can issue commands via the spss.Submit api and can use other spss apis, but they go against a new copy of the backend, so the expected backend context is not present.

To get around this, you can run a trivial program like

```<code>begin program.
import ascript
end program.
</code>```

where ascript.py is a Python module on the Python search path.  (You could put these lines in an sps file and use INSERT to execute it, too.)

Another way to approach this would be to run Statistics in external mode.  In that mode, you run a Python program that uses SPSS apis but the Python program is on top, and no Statistics user interface appears.  You can read about this in the Python scripting help.

An advantage of external mode is that you can use your favorite Python IDE to build and debug your code.  That's a big advantage if you are basically a Python person.  I use Wing IDE, but any Python IDE should work.  You can also set up an alternative IDE as your default by editing the clientscriptingcfg.ini file in the Statistics installation directory.  See the scripting help for details.  With a tool like Wing, this lets you debug your scripts or other Python code even if run within Statistics.

Body:
I have a Python 2.7 script that among others contains the following piece of code:

import spss

columns = []

spss.StartDataStep()
dataset = spss.Dataset()
for column in dataset.varlist:
    columns.append(column.name)
spss.EndDataStep()

print columns

When running this code inside a SPSS syntax (so between BEGIN PROGRAM. and END PROGRAM), it runs as expected and I end up with the variables in the active dataset.

However, when running the same code as part of a script (so from Utilities > Run script...) will return me no results.

It looks as if the SPSS session context is not taken into consideration when running a script.

Is there a way around this problem, or am I doing something wrong?
I don't want to run my code as part of Syntax file, I just want to use vanilla Python scripts.

Body:
This is, unfortunately, a complicated issue.  I don't think Statistics is working as documented.  I will take this up with Development.

It appears that in V24, when you run a Python script via Utilities > Run Script (which is the same as issuing the SCRIPT command), your script is connected to the Statistics Viewer process but not to the Statistics backend (the spssengine process), which is where the data live.  There are typically three processes running - the stats.exe process, the spssengine process, and, for Python code, the startx process.  Your script can issue commands via the spss.Submit api and can use other spss apis, but they go against a new copy of the backend, so the expected backend context is not present.

To get around this, you can run a trivial program like

begin program.
import ascript
end program.

where ascript.py is a Python module on the Python search path.  (You could put these lines in an sps file and use INSERT to execute it, too.)

Another way to approach this would be to run Statistics in external mode.  In that mode, you run a Python program that uses SPSS apis but the Python program is on top, and no Statistics user interface appears.  You can read about this in the Python scripting help.

An advantage of external mode is that you can use your favorite Python IDE to build and debug your code.  That's a big advantage if you are basically a Python person.  I use Wing IDE, but any Python IDE should work.  You can also set up an alternative IDE as your default by editing the clientscriptingcfg.ini file in the Statistics installation directory.  See the scripting help for details.  With a tool like Wing, this lets you debug your scripts or other Python code even if run within Statistics.


问:
Call to undefined function get_header()

Error: Fatal error: Call to undefined function get_header() in C:\Xampp\xampp\htdocs\index.php on line 1

Index Code:

```<code><?php get_header(); ?>
<?php get_sidebar()?>
    <div id="left">

    <?php_while(have_posts()):?>

        <h2><?php the_title()?></h2>
        <?php the_content();?>

    <?php_endwhile();?>

    </div>

<?php get_footer()?>`
</code>```

答:
the function get_header() is a wordpress theme function, you are calling it from:

C:\Xampp\xampp\htdocs\index.php

put this same code inside a wordpress theme and it will work.

Title: Call to undefined function get_header()

Body:
Error: Fatal error: Call to undefined function get_header() in C:\Xampp\xampp\htdocs\index.php on line 1

Index Code:

<?php get_header(); ?>
<?php get_sidebar()?>

    <?php_while(have_posts()):?>

<?php the_title()?>

        <?php the_content();?>

    <?php_endwhile();?>

<?php get_footer()?>`

ContentLicense: CC BY-SA 4.0


问:
API architecture
I am in the process of designing an API. I would like to know if what I have come up with is a good solution:

I have a respository type of data layer that talks to a database by converting business classes into entities(generated from LLBL GEN, I didn't want to use the entities directly as my business objects because I wanted to keep them simple and allow me to swap out to Entity Framework or some other mapper is I needed to)

I have a WCF service layer that I'm using as a type of facade. It calls the respository layer and converts the business objects to DTOs and passes them through the API service call via a message to the client. The client can be an ASPX website, Silverlight app, WPF app, or even a WP7 app. The problem I keep runnnig into is when I want to run business logic I have to send the DTO back to the WCF service and then back to the client. This doesn't seem "right" to me. I can't put business logic in the DTO because that defeats the purpose. But if I want business type code to run on the client I have a lot of duplication of code throughout my different clients.

My business layer does not know of the data layer, my data layer knows of the business layer and my facade layer knows of the data layer and the business layer and the DTOs. Is this a bad design for an API? And can anyone offer me any suggestions? I have only learned of enterprise level apps through reading different articles online.

Thanks!

答:
My business layer does not know of the data layer, my data layer knows of the business layer and my facade layer knows of the data layer and the business layer and the DTOs. Is this a bad design for an API?

No layer should know about the layer above.

I have a WCF service layer that I'm using as a type of facade. It calls the respository layer and converts the business objects to DTOs and passes them through the API service call via a message to the client. The client can be an ASPX website, Silverlight app, WPF app, or even a WP7 app

Theres a design principle called You Aint Gonno Need It which is the almost the same thing as Keep It Simple (and) Stupid.

They both is all about NOT adding features that you might need. If you start with only having a website that uses the service layer, then simply use it directly without a WCF service.

If you need a WCF service later on, then add it later.

If you are defining the services using interfaces it's quite to swap a implementation that you are using directly to a WCF service implementation. (if you are using a IoC container)

Concretes vs interfaces

You should always put the interfaces and business objects in a separate assembly from implementations (classes) to make it easier to swap implementations of each layer. It's a design pattern called Separated interace which you can read about here: http://martinfowler.com/eaaCatalog/separatedInterface.html

ContentLicense: CC BY-SA 2.5

Title: API architecture


问:
Loading pretrained model with Python tensorflow v.0.9.0 in Java tensorflow v.1.2.0
When both Java and Python tensorflow versions are 1.2.0, it seems we can use SavedModelBundle (Java) and Saved Model API (Python) in order to save a trained model in Python tensorflow and load the model in Java tensorflow (Not with Maven).

However, I could not find a way to properly load a model in Java when the version of Python is below 1.0.

I trained a model and saved it as .pb, .sd, and .txt files in Python tensorflow (0.9.0) and followed the example instruction in the tensorflow website to load the model. However, I got the following error:

```<code>Exception in thread "main" java.lang.IllegalStateException: Attempting
to use uninitialized value policy/mean_network/hidden_1/b
            [[Node: _retval_policy/mean_network/hidden_1/b_0_0 =
_Retval[T=DT_FLOAT, index=0,
_device="/job:localhost/replica:0/task:0/cpu:0"]
(policy/mean_network/hidden_1/b)]]
            at org.tensorflow.Session.run(Native Method)
            at org.tensorflow.Session.access$100(Session.java:48)
            at org.tensorflow.Session$Runner.runHelper(Session.java:285)
            at org.tensorflow.Session$Runner.run(Session.java:235)
            at Carpole.executeGraph(Carpole.java:42)
            at Carpole.main(Carpole.java:30)
</code>```

Does anyone know how to properly load a pretrained model in Java in the most recent version (since I cannot find previous version API anymore) without using Saved Model API?

Thanks in advance!

Here is my Python code for saving:

```<code>with tf.Session() as sess:
    self.saver = tf.train.Saver(tf.all_variables())
    sess.run(tf.initialize_all_variables())
    …..
    saver_def = self.saver.as_saver_def()
    print(saver_def.filename_tensor_name)
    print(saver_def.restore_op_name)

    self.saver.save(sess, 'trained_model'+str(itr)+'.sd')
    tf.train.write_graph(sess.graph_def, '.', 'trained_model'+str(itr)+'.pb', as_text=False)
    tf.train.write_graph(sess.graph_def, '.', 'trained_model'+str(itr)+'.txt', as_text=True)
</code>```

And here is my Java code

```<code>public static void main(String[] args) throws Exception {
    String dataDirPath = args[0];
    byte[] graphDef = readAllBytesOrExit(Paths.get(dataDirPath, "trained_model10.pb"));
    List<String> labels = readAllLinesOrExit(Paths.get(dataDirPath, "trained_model10.txt"));
    float[] vector = new float[4];
    vector[0] = (float) -0.09341373;
    vector[1] = (float) -0.07540844;
    vector[2] = (float)  0.00930138;
    vector[3] = (float) -0.14317159;
    Tensor input = Tensor.create(vector);

    float[] labelProbabilities = executeGraph(graphDef, input);
    int bestLabelIdx = maxIndex(labelProbabilities);
    System.out.println(String.format("BEST MATCH: %s (%.2f%% likely)",labels.get(bestLabelIdx), labelProbabilities[bestLabelIdx] * 100f));
}

private static float[] executeGraph(byte[] graphDef, Tensor input_tensor) {
    try (Graph g = new Graph()) {
        g.importGraphDef(graphDef);
        System.out.println(g);
        try (Session s = new Session(g); Tensor result = s.runner().feed("policy/mean_network/input/input",input_tensor).fetch("policy/mean_network/hidden_1/b").run().get(0)) {
        final long[] rshape = result.shape();
        }
        int nlabels = (int) rshape[1];
        return result.copyTo(new float[1][nlabels])[0];
    }
}
</code>```

答:
In general, TensorFlow versions prior to 1.0 are not guaranteed to work with TensorFlow versions >= 1.0 (as per the TensorFlow Version Semantics and use of semantic versioning).

That said, looking at the code snippets you provided, you're loading the computational graph in Java, but are not loading the saved variables and hence you get an exception complaining that the variables have not been initialized.

Encapsulating the graph and saved variables into a single bundle is what the SavedModel format is intended for. However, if you can't use that, and if you need the graph only for inference in Java, then you might want to consider "freezing" the graph and then loading that in Java. The frozen graph will contain all the variable values in a single file.

You could try to use the freeze_graph libraries (from the 0.9 release branch) to save such a graph.

Working with pre-1.0 releases of TensorFlow might be a challenge. If possible, I'd strongly suggest you move your model to a TensorFlow version >= 1.0 and then can avail for the API stability guarantees.

Hope that helps.

Body:
When both Java and Python tensorflow versions are 1.2.0, it seems we can use SavedModelBundle (Java) and Saved Model API (Python) in order to save a trained model in Python tensorflow and load the model in Java tensorflow (Not with Maven).

However, I could not find a way to properly load a model in Java when the version of Python is below 1.0.

I trained a model and saved it as .pb, .sd, and .txt files in Python tensorflow (0.9.0) and followed the example instruction in the tensorflow website to load the model. However, I got the following error:

Exception in thread "main" java.lang.IllegalStateException: Attempting
to use uninitialized value policy/mean_network/hidden_1/b
            [[Node: _retval_policy/mean_network/hidden_1/b_0_0 =
_Retval[T=DT_FLOAT, index=0,
_device="/job:localhost/replica:0/task:0/cpu:0"]
(policy/mean_network/hidden_1/b)]]
            at org.tensorflow.Session.run(Native Method)
            at org.tensorflow.Session.access$100(Session.java:48)
            at org.tensorflow.Session$Runner.runHelper(Session.java:285)
            at org.tensorflow.Session$Runner.run(Session.java:235)
            at Carpole.executeGraph(Carpole.java:42)
            at Carpole.main(Carpole.java:30)

Does anyone know how to properly load a pretrained model in Java in the most recent version (since I cannot find previous version API anymore) without using Saved Model API?

Thanks in advance!

Here is my Python code for saving:

with tf.Session() as sess:
    self.saver = tf.train.Saver(tf.all_variables())
    sess.run(tf.initialize_all_variables())
    …..
    saver_def = self.saver.as_saver_def()
    print(saver_def.filename_tensor_name)
    print(saver_def.restore_op_name)

    self.saver.save(sess, 'trained_model'+str(itr)+'.sd')
    tf.train.write_graph(sess.graph_def, '.', 'trained_model'+str(itr)+'.pb', as_text=False)
    tf.train.write_graph(sess.graph_def, '.', 'trained_model'+str(itr)+'.txt', as_text=True)

And here is my Java code

public static void main(String[] args) throws Exception {
    String dataDirPath = args[0];
    byte[] graphDef = readAllBytesOrExit(Paths.get(dataDirPath, "trained_model10.pb"));
    List<String> labels = readAllLinesOrExit(Paths.get(dataDirPath, "trained_model10.txt"));
    float[] vector = new float[4];
    vector[0] = (float) -0.09341373;
    vector[1] = (float) -0.07540844;
    vector[2] = (float)  0.00930138;
    vector[3] = (float) -0.14317159;
    Tensor input = Tensor.create(vector);

    float[] labelProbabilities = executeGraph(graphDef, input);
    int bestLabelIdx = maxIndex(labelProbabilities);
    System.out.println(String.format("BEST MATCH: %s (%.2f%% likely)",labels.get(bestLabelIdx), labelProbabilities[bestLabelIdx] * 100f));
}

private static float[] executeGraph(byte[] graphDef, Tensor input_tensor) {
    try (Graph g = new Graph()) {
        g.importGraphDef(graphDef);
        System.out.println(g);
        try (Session s = new Session(g); Tensor result = s.runner().feed("policy/mean_network/input/input",input_tensor).fetch("policy/mean_network/hidden_1/b").run().get(0)) {
        final long[] rshape = result.shape();
        }
        int nlabels = (int) rshape[1];
        return result.copyTo(new float[1][nlabels])[0];
    }
}


问:
Display tags from list of separated comma words
I have a list of tags stores in a table, when I call this list by {{article.tags}} 	 flask code, the display is basic as follows (tag1, tag2, tag3 ..), I want to display them as:
enter image description here
thank you

答:
You can use a Jinja2 for loop:</p>

```<code>{% for tag in article.tags.split(',') %}
    <td>{{ tag }}</td>
{% endfor %}
</code>```

Body:
You can use a Jinja2 for loop:

{% for tag in article.tags.split(',') %}
    <td>{{ tag }}</td>
{% endfor %}


问:
Replaced .css() with .animate() and it's not working
I'm trying to create a parallax-ish effect when you move your cursor over the header by shifting an image. I got it working with .css() — I included that in the line that's commented out in the code below — but I replaced it with .animate() because I want easing, and the animation isn't working.

```<code>var width = 50 / $(window).width();
$('header').mousemove(function(e) {
    var pageX = e.pageX - ($(window).width() / 2);
    var newvalueX = width * pageX * -1 - 25;
    //$('#headerImg img').css('transform', 'translateX(calc(-50% - ' + newvalueX + 'px))');
    $('#headerImg img').animate({
        'transform': 'translateX(calc(-50% - ' + newvalueX + 'px))'
    }, 'slow', function() {
        console.log('check');
    });
});
</code>```

The console.log DOES work, and there are no errors, but the .animate() itself does nothing. I'm thining it must be something really dumb on my part!

答:
You can use easing with css:

```<code>#headerImg img{
  transition-timing-function: ease-in;
  transition: 0.2s;
}
</code>```

For more information:
https://www.w3schools.com/cssref/css3_pr_transition-timing-function.asp

Body:
I'm trying to create a parallax-ish effect when you move your cursor over the header by shifting an image. I got it working with .css() — I included that in the line that's commented out in the code below — but I replaced it with .animate() because I want easing, and the animation isn't working.

var width = 50 / $(window).width();
$('header').mousemove(function(e) {
    var pageX = e.pageX - ($(window).width() / 2);
    var newvalueX = width * pageX * -1 - 25;
    //$('#headerImg img').css('transform', 'translateX(calc(-50% - ' + newvalueX + 'px))');
    $('#headerImg img').animate({
        'transform': 'translateX(calc(-50% - ' + newvalueX + 'px))'
    }, 'slow', function() {
        console.log('check');
    });
});

The console.log DOES work, and there are no errors, but the .animate() itself does nothing. I'm thining it must be something really dumb on my part!

Body:
You can use easing with css:

#headerImg img{
  transition-timing-function: ease-in;
  transition: 0.2s;
}

For more information:
https://www.w3schools.com/cssref/css3_pr_transition-timing-function.asp


问:
Conditional statements using vue.js with html element
Im new to vue.js, and Im trying to do a simple if with a date field within my ASP.NET MVC project.
I've seen examples on vue tutorials where the condition is done in the js file, but Im not convinced that this would help me.
I currently have a date field in my ViewModel that has two drop downs. This is for an application form that asks a person how long have they lived at their address. They can select up to 11 months and 6+ years. I have a button that allows them to add another address. When you click this button, the viewModel for the date fields are repeated so they can add another one (stored in a List).
 However I want to wrap this around a condition that says only if the date entered is less than 6 years then the button would appear. Like I said, at the min it is there always.

my code for the address and its button is:

```<code>    <fieldset>
    <legend>Please provide all your addresses in the last 6 years</legend>
    @Html.EditorFor(m => m.PreviousAddresses)
</fieldset>

    <button class="button">Add another previous address</button>
</code>```

What im trying to do is something like v-if="PreviousAddress < 6" but I dont think thats right. Can someone help with the syntax?

EDIT: The validation works on the back end. Just need the client side to work with it:

```<code> [Minimum(72, ErrorMessage = "Please enter 6 years address history")]
    public int TotalAddressHistoryInMonths
    {
        get
        {
            int totalMonths = CurrentAddress?.Duration?.TotalPeriodInMonths ?? 0;

            if (PreviousAddresses != null)
            {
                foreach (ResidencyInputViewModel residency in PreviousAddresses)
                {
                    totalMonths += residency?.Duration?.TotalPeriodInMonths ?? 0;
                }
            }

            return totalMonths;
        }
    }
</code>```

答: The solution you have appears to be correct, but can you post the rest of your code. Seeing the data object should help.</p>

Body:
Im new to vue.js, and Im trying to do a simple if with a date field within my ASP.NET MVC project.
I've seen examples on vue tutorials where the condition is done in the js file, but Im not convinced that this would help me.
I currently have a date field in my ViewModel that has two drop downs. This is for an application form that asks a person how long have they lived at their address. They can select up to 11 months and 6+ years. I have a button that allows them to add another address. When you click this button, the viewModel for the date fields are repeated so they can add another one (stored in a List).
 However I want to wrap this around a condition that says only if the date entered is less than 6 years then the button would appear. Like I said, at the min it is there always.

my code for the address and its button is:

    <fieldset>
    <legend>Please provide all your addresses in the last 6 years</legend>
    @Html.EditorFor(m => m.PreviousAddresses)
</fieldset>

    <button class="button">Add another previous address</button>

What im trying to do is something like v-if="PreviousAddress < 6" but I dont think thats right. Can someone help with the syntax?

EDIT: The validation works on the back end. Just need the client side to work with it:

 [Minimum(72, ErrorMessage = "Please enter 6 years address history")]
    public int TotalAddressHistoryInMonths
    {
        get
        {
            int totalMonths = CurrentAddress?.Duration?.TotalPeriodInMonths ?? 0;

            if (PreviousAddresses != null)
            {
                foreach (ResidencyInputViewModel residency in PreviousAddresses)
                {
                    totalMonths += residency?.Duration?.TotalPeriodInMonths ?? 0;
                }
            }

            return totalMonths;
        }
    }


问:
Is there a typeclass in haskell for boolean values?
I am trying to learn some Haskell by looking at a superb short and educational article on comonad application from 2006 link and it contains an expression like rule (U (a:_) b (c:_)) = not (a && b && not c || (a==b)) whre U is a zipper comonad. That is stated in data U x = [x] x [x] and accompanying implementations of the comonad operations.

Trying to learn more, I am attempting to annotate the type of the expression manually. A wise choice seems to be rule :: U Bool -> Bool, but that seems a bit... restrictive. I could imagine other types that would be able to have truthyness values, such as Ints (0 corresponds to false, all other values could be True) and other.

If there was a type class for truthyness called truthy, I guess I could write rule :: (Truthy t) => U t -> Bool. Since I want to iterate over rule, the first type annotation (rule :: U Bool -> Bool) is good enough, but still the question tickles my brain.

Is there such a typeclass? If there is, what is it called? If not, why is there no need for it?

答:
Digression: Generally we don't use type classes to do what you might call mere overloading, of the sort you find in dynamic languages (e.g. making + mean "concatenate lists" or "add ints", or overloading boolean operations to work on "truthy" values as in your question). The difference is I guess that we say good abstractions are made with type classes that have a set of laws that hold them together, so that you can write polymorphic code that is useful. It might be that we can make a "truthy" class that's good by this standard but I'm not sure.

But to get to your question, there are certainly classes that abstract boolean logic to some degree (the field of study here being maybe Boolean algebra), the most relevant here probably being the Bits class from Data.Bits.

So you'd get:

```<code>-- note, the polymorphic `t` has cooties, and we'd need to be able to
-- make the caller polymorphic in a sensible way too for this to make sense
rule :: (Bits t) => U t -> t
rule (U (a:_) b (c:_)) = complement (a .&. b .&. complement c .|. complement (a `xor` b))
</code>```

The only tricky bit above is a == b becomes the wordy more general form complement (a ``xor`` b). Actually if we restrict ourselves to the fundamental operations (AND/OR/NOT), then the more general form of == is quite complicated:

```<code>a .==. b = complement ((a .|. b) .&. complement (a .&. b))
</code>```

It would be interesting to see whether or in what way this operation makes sense with this more general type (I don't know what it's meant to do), e.g. does it do something sensible for Int. Then compare that with Int had we used your "truthy" class. Is one more useful than the other? Does the Bits version give you any new insight into the algorithm or is it just an arbitrary overloading?

Edit: here's something interesting about working in this more abstract domain: we can use the laws of boolean algebra to reduce and understand our expression better. For instance by handing it off to Wolfram Alpha we can observe that the normalized forms of our expression don't contain c at all (you should double-check I haven't made a mistake somewhere), so we might as well have written:

```<code>rule (U (a:_) b _) = (a && not b) || (not a && b)
</code>```

This might be interesting insight (is that c even necessary in our data structure?) or might indicate a bug in our logic.

Body:
Digression: Generally we don't use type classes to do what you might call mere overloading, of the sort you find in dynamic languages (e.g. making + mean "concatenate lists" or "add ints", or overloading boolean operations to work on "truthy" values as in your question). The difference is I guess that we say good abstractions are made with type classes that have a set of laws that hold them together, so that you can write polymorphic code that is useful. It might be that we can make a "truthy" class that's good by this standard but I'm not sure.

But to get to your question, there are certainly classes that abstract boolean logic to some degree (the field of study here being maybe Boolean algebra), the most relevant here probably being the Bits class from Data.Bits.

So you'd get:

-- note, the polymorphic `t` has cooties, and we'd need to be able to
-- make the caller polymorphic in a sensible way too for this to make sense
rule :: (Bits t) => U t -> t
rule (U (a:_) b (c:_)) = complement (a .&. b .&. complement c .|. complement (a `xor` b))

The only tricky bit above is a == b becomes the wordy more general form complement (a ``xor`` b). Actually if we restrict ourselves to the fundamental operations (AND/OR/NOT), then the more general form of == is quite complicated:

a .==. b = complement ((a .|. b) .&. complement (a .&. b))

It would be interesting to see whether or in what way this operation makes sense with this more general type (I don't know what it's meant to do), e.g. does it do something sensible for Int. Then compare that with Int had we used your "truthy" class. Is one more useful than the other? Does the Bits version give you any new insight into the algorithm or is it just an arbitrary overloading?

Edit: here's something interesting about working in this more abstract domain: we can use the laws of boolean algebra to reduce and understand our expression better. For instance by handing it off to Wolfram Alpha we can observe that the normalized forms of our expression don't contain c at all (you should double-check I haven't made a mistake somewhere), so we might as well have written:

rule (U (a:_) b _) = (a && not b) || (not a && b)

This might be interesting insight (is that c even necessary in our data structure?) or might indicate a bug in our logic.


问:
R installed.packages() randomly stopped working on windows 7
installed.packages() command in R lists your installed packages.  Mine was working for almost a year and then this command randomly started throwing an error.  As this is a built-in command, I am not even sure how to "reinstall" it or address this.  Any ideas how to fix the error and get the command working again?

```<code>> installed.packages()
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file `'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'`
</code>```

One suggestion on here involved this in combination:

.libPaths()

installed.packages(lib.loc = 'my path')

The results of this produced yet another error as shown here.  Looks like an issue with the installed file still but how to address is the question:

```<code>> installed.packages(lib.loc = 'C:/ProgramFilesCoders/R/R-3.3.2/library')
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file 'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'
>
</code>```

答:
Sometimes the most simple obvious solution is what works:

I closed my RStudio environment saving it to .RData

I re-opened RStudio and tried the command again

it worked

For the future, some good ideas got posted on here before I thought to try the above.  Here are the suggestions that others included in case the above does not work if this problem is encountered by anyone in the future:

Use .libPaths() to find out proper path where this is installed, and then re-run the command with the path included in it like so: installed.packages(lib.loc = 'your path')

Try debugging it with: debug(installed.packages); Expectation is that we will likely find something wrong with .readPkgDesc(lib, fields) while stepping through debug.  This was not tried yet so you may encounter things not written up here when you do try it.

Try Updating R in case it is out of date with these commands: library(installr) and updateR().

Body:
installed.packages() command in R lists your installed packages.  Mine was working for almost a year and then this command randomly started throwing an error.  As this is a built-in command, I am not even sure how to "reinstall" it or address this.  Any ideas how to fix the error and get the command working again?

> installed.packages()
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file `'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'`

One suggestion on here involved this in combination:

.libPaths()

installed.packages(lib.loc = 'my path')

The results of this produced yet another error as shown here.  Looks like an issue with the installed file still but how to address is the question:

> installed.packages(lib.loc = 'C:/ProgramFilesCoders/R/R-3.3.2/library')
Error in gzfile(file, mode) : cannot open the connection
In addition: Warning message:
In gzfile(file, mode) :
  cannot open compressed file 'C:\Users\Mitch\AppData\Local\Temp\Rtmp6Dawpa/libloc_190_4464fd2b.rds', probable reason 'No such file or directory'
>


问:
Issue with specialization and higher kinds in scala
I have these lines (scala 2.11.11):

```<code>trait TypeClass[T]
class DoubleIsTypeClass extends TypeClass[Double]
implicit val forDouble = new DoubleIsTypeClass
</code>```

Know lets add the following line :

```<code>case class User[V[_], @specialized T : TypeClass](a: V[T])
</code>```

Now it does not compile.
Removing @specialized fixes it.
Is it a bug ?
I don't really need higher kinds here except their help with type inference but that is a big deal.

EDIT
Just for those who may have stumbled upon a similar problem

Typeclasses are not the issue here, case classes are:

```<code>case class User[V[_], @specialized T](a: V[T])
</code>```

The line above does not compile on its own.

答:
This looks like SI-9227. It seems to be a bug.

In general, these are some quirks around specialization which are worth reading about.

Body:
I have these lines (scala 2.11.11):

trait TypeClass[T]
class DoubleIsTypeClass extends TypeClass[Double]
implicit val forDouble = new DoubleIsTypeClass

Know lets add the following line :

case class User[V[_], @specialized T : TypeClass](a: V[T])

Now it does not compile.
Removing @specialized fixes it.
Is it a bug ?
I don't really need higher kinds here except their help with type inference but that is a big deal.

EDIT
Just for those who may have stumbled upon a similar problem

Typeclasses are not the issue here, case classes are:

case class User[V[_], @specialized T](a: V[T])

The line above does not compile on its own.


问:
Piecewise functions in the Octave symbolic package?
Unlike Matlab, Octave Symbolic has no piecewise function.  Is there a work around? I would like to do something like this:

```
syms x
y = piecewise(x0, 1)
```

Relatedly, how does one get pieces of a piecewise function?  I ran the following:

```
>> int (exp(-a*x), x, 0, t)
```

And got the following correct answer displayed and stored in a variable:

```
      t      for a = 0

       -a*t
  1   e
  - - -----  otherwise
  a     a

```

But now I would like to access the "otherwise" part of the answer so I can factor it. How do I do that?

(Yes, I can factor it in my head, but I am practicing for when more complicated expressions come along.  I am also only really looking for an approach using symbolic expressions -- even though in any single case numerics may work fine, I want to understand the symbolic approach.)

Thanks!

答:
Matlab's piecewise function seems to be fairly new (introduced in 2016b), but it basically just looks like a glorified ternary operator. Unfortunately I don't have 2016 to check if it performs any checks on the inputs or not, but in general you can recreate a 'ternary' operator in octave by indexing into a cell using logical indexing. E.g.

{@() return_A(), @() return_B(), @() return_default()}([test1, test2, true]){1}()
```

<p><strong>Explanation:</strong></p>

<ul>
<li>Step 1: You put all the values of interest in a cell array. Wrap them in function handles if you want to prevent them being evaluated at the time of parsing (e.g. if you wanted the output of the ternary operator to be to produce an error)</li>
<li>Step 2: Index this cell array using logical indexing, where at each index you perform a logical test </li>
<li>Step 3: If you need a 'default' case, use a 'true' test for the last element.</li>
<li>Step 4: From the cell (sub)array that results from above, select the first element and 'run' the resulting function handle. Selecting the first element has the effect that if more than one tests succeed, you only pick the first result; given the 'default' test will always succeed, this also makes sure that this is not picked unless it's the first and only test that succeeds (which it does so by default).</li>
</ul>

<p>Here are the above steps implemented into a function (appropriate sanity checks omitted here for brevity), following the same syntax as matlab's <code>piecewise</code>:</p>

<pre class="lang-matlab prettyprint-override"><code>function Out = piecewise (varargin)
  Conditions = varargin(1:2:end);    % Select all 'odd' inputs
  Values     = varargin(2:2:end);    % Select all 'even' inputs
  N          = length (Conditions);
  if length (Values) ~= N            % 'default' case has been provided
    Values{end+1} = Conditions{end}; % move default return-value to 'Values'
    Conditions{end} = true;          % replace final (ie. default) test with true
  end

  % Wrap return-values into function-handles
  ValFuncs = cell (1, N);
  for n = 1 : N; ValFuncs{n} = @() Values{n}; end

  % Grab funhandle for first successful test and call it to return its value
  Out = ValFuncs([Conditions{:}]){1}();
end
</code>```

Example use:

>> syms x t;
>> F = @(a) piecewise(a == 0, t, (1/a)*exp(-a*t)/a);

>> F(0)
ans = (sym) t

>> F(3)
ans = (sym)

   -3⋅t
  ℯ
  ─────
    9
```

Body:
Unlike Matlab, Octave Symbolic has no piecewise function.  Is there a work around? I would like to do something like this:

syms x
y = piecewise(x0, 1)

Relatedly, how does one get pieces of a piecewise function?  I ran the following:

>> int (exp(-a*x), x, 0, t)

And got the following correct answer displayed and stored in a variable:

      t      for a = 0

       -a*t
  1   e
  - - -----  otherwise
  a     a

But now I would like to access the "otherwise" part of the answer so I can factor it. How do I do that?

(Yes, I can factor it in my head, but I am practicing for when more complicated expressions come along.  I am also only really looking for an approach using symbolic expressions -- even though in any single case numerics may work fine, I want to understand the symbolic approach.)

Thanks!

Body:
Matlab's piecewise function seems to be fairly new (introduced in 2016b), but it basically just looks like a glorified ternary operator. Unfortunately I don't have 2016 to check if it performs any checks on the inputs or not, but in general you can recreate a 'ternary' operator in octave by indexing into a cell using logical indexing. E.g.

{@() return_A(), @() return_B(), @() return_default()}([test1, test2, true]){1}()

Explanation:

Step 1: You put all the values of interest in a cell array. Wrap them in function handles if you want to prevent them being evaluated at the time of parsing (e.g. if you wanted the output of the ternary operator to be to produce an error)

Step 2: Index this cell array using logical indexing, where at each index you perform a logical test

Step 3: If you need a 'default' case, use a 'true' test for the last element.

Step 4: From the cell (sub)array that results from above, select the first element and 'run' the resulting function handle. Selecting the first element has the effect that if more than one tests succeed, you only pick the first result; given the 'default' test will always succeed, this also makes sure that this is not picked unless it's the first and only test that succeeds (which it does so by default).

Here are the above steps implemented into a function (appropriate sanity checks omitted here for brevity), following the same syntax as matlab's piecewise:

function Out = piecewise (varargin)
  Conditions = varargin(1:2:end);    % Select all 'odd' inputs
  Values     = varargin(2:2:end);    % Select all 'even' inputs
  N          = length (Conditions);
  if length (Values) ~= N            % 'default' case has been provided
    Values{end+1} = Conditions{end}; % move default return-value to 'Values'
    Conditions{end} = true;          % replace final (ie. default) test with true
  end

  % Wrap return-values into function-handles
  ValFuncs = cell (1, N);
  for n = 1 : N; ValFuncs{n} = @() Values{n}; end

  % Grab funhandle for first successful test and call it to return its value
  Out = ValFuncs([Conditions{:}]){1}();
end

Example use:

>> syms x t;
>> F = @(a) piecewise(a == 0, t, (1/a)*exp(-a*t)/a);

>> F(0)
ans = (sym) t

>> F(3)
ans = (sym)

   -3⋅t
  ℯ
  ─────
    9


问:
underscore.js: _.throttle(function, wait)
According the underscore documentation:

throttle_.throttle(function, wait)

  Creates and returns a new,
  throttled version of the passed function, that, when invoked
  repeatedly, will only actually call the original function at most once
  per every wait milliseconds. Useful for rate-limiting events that
  occur faster than you can keep up with.

What does it means Useful for rate-limiting events that occur faster than you can keep up with.

This function is equivalent to setTimeout with a function that calls itself?

Can someone provide me some example on jsfiddle?

答:
The difference between throttle and debounce is described here:
https://css-tricks.com/the-difference-between-throttling-and-debouncing/</p>

```<code>/*
"Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
"Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer."
*/
_.debounce = (fn, delay) => {
  let timer
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(null, args)
    }, delay)
  }
}
/*
"Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
 */
_.throttle = (fn, delay) => {
  let canCall = true
  return (...args) => {
    if (canCall) {
      fn.apply(null, args)
      canCall = false
      setTimeout(() => {
        canCall = true
      }, delay)
    }
  }
}
</code>```

Body:
The difference between throttle and debounce is described here:
https://css-tricks.com/the-difference-between-throttling-and-debouncing/

/*
"Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
"Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer."
*/
_.debounce = (fn, delay) => {
  let timer
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(null, args)
    }, delay)
  }
}
/*
"Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
 */
_.throttle = (fn, delay) => {
  let canCall = true
  return (...args) => {
    if (canCall) {
      fn.apply(null, args)
      canCall = false
      setTimeout(() => {
        canCall = true
      }, delay)
    }
  }
}


问:
UIToolBar bar button items NOT showing with Swift
I am making an app without using Interface Builder, so I'm creating everything by code.

I have a view controller that is embedded in a navigation controller. I know navigation controllers have a toolbar property, and all I need to do is set the boolean to false to unhide it. My code looks like this (it is a function called in viewDidLoad):

```<code>func setUpToolBar(){
    navigationController?.toolbarHidden = false
    navigationController?.toolbar.barTintColor = UIColor.blackColor()
    navigationController?.toolbar.tintColor = UIColor.whiteColor()

    toolItems.append(addImageButton)
    toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
    toolItems.append(exportImageButton)
    toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
    toolItems.append(deleteImageButton)

    navigationController?.toolbar.setItems(toolItems, animated: false)

}
</code>```

Here is where and how I am declaring these properties for my view controller:

```<code>private var addImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "plus button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.addImage))
    return button
}()
private var exportImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "export button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.exportImagePressed))
    return button
}()
private var deleteImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "trash button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.deleteImagePressed))
    return button
}()

private var toolItems : [UIBarButtonItem] = []
</code>```

Here is the function for my UIFactory class which simply handles the hassle of creating these UI items outside of the view controller

```<code>class func createBarButtonItem(title: String?, imageNamed : String?, style : UIBarButtonItemStyle?, target : AnyObject?, selector : Selector?) -> UIBarButtonItem{
    let button = UIBarButtonItem()
    if let theTitle = title {
        button.title = theTitle
    }
    if let theImageName = imageNamed {
        button.image = UIImage(named: theImageName)
    }
    if let theStyle = style{
        button.style = theStyle
    }
    if let theTarget = target {
        button.target = theTarget
    }
    if let theSelector = selector {
        button.action = theSelector
    }
    return button
}
</code>```

And, after running this code in the simulator, this is what I see (no toolbar items! Also, notice I have a bar button item in that navigation bar, which I added in code just fine)

Please, someone help me. I am stuck on such a nonsensical step and I can't proceed with my app without this.

答:
I changed

navigationController!.toolbar.setItems(toolItems, animated: true)

to

toolbarItems = toolItems

and worked for me.

Body:
I am making an app without using Interface Builder, so I'm creating everything by code.

I have a view controller that is embedded in a navigation controller. I know navigation controllers have a toolbar property, and all I need to do is set the boolean to false to unhide it. My code looks like this (it is a function called in viewDidLoad):

func setUpToolBar(){
    navigationController?.toolbarHidden = false
    navigationController?.toolbar.barTintColor = UIColor.blackColor()
    navigationController?.toolbar.tintColor = UIColor.whiteColor()

    toolItems.append(addImageButton)
    toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
    toolItems.append(exportImageButton)
    toolItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil))
    toolItems.append(deleteImageButton)

    navigationController?.toolbar.setItems(toolItems, animated: false)

}

Here is where and how I am declaring these properties for my view controller:

private var addImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "plus button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.addImage))
    return button
}()
private var exportImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "export button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.exportImagePressed))
    return button
}()
private var deleteImageButton : UIBarButtonItem = {
    let button = UIFactory.createBarButtonItem(nil, imageNamed: "trash button", style: .Plain, target: ImagesCollectionViewController.self, selector: #selector(ImagesCollectionViewController.deleteImagePressed))
    return button
}()

private var toolItems : [UIBarButtonItem] = []

Here is the function for my UIFactory class which simply handles the hassle of creating these UI items outside of the view controller

class func createBarButtonItem(title: String?, imageNamed : String?, style : UIBarButtonItemStyle?, target : AnyObject?, selector : Selector?) -> UIBarButtonItem{
    let button = UIBarButtonItem()
    if let theTitle = title {
        button.title = theTitle
    }
    if let theImageName = imageNamed {
        button.image = UIImage(named: theImageName)
    }
    if let theStyle = style{
        button.style = theStyle
    }
    if let theTarget = target {
        button.target = theTarget
    }
    if let theSelector = selector {
        button.action = theSelector
    }
    return button
}

And, after running this code in the simulator, this is what I see (no toolbar items! Also, notice I have a bar button item in that navigation bar, which I added in code just fine)

Please, someone help me. I am stuck on such a nonsensical step and I can't proceed with my app without this.


问:
Django file upload not displaying
I have written the code for file upload but it is not displaying on my destination page.
Please help me edit my code or suggest how to fix this issue.
The rest of the fields are displaying but not the file field

My models.py

```<code>class Help(models.Model):
  researcher  = models.CharField(max_length=100)
  study = models.CharField(max_length=500)
  date = models.DateTimeField(auto_now_add=True)
  document = models.FileField(upload_to='documents/', null=True, blank=True)
</code>```

forms.py

```<code>from django import forms
from .models import Help
from django.forms import ModelForm

class AboutHelp(forms.ModelForm):

    class Meta:
        model = Help
        fields = '__all__'
</code>```

source page

```<code><form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form">
  {% csrf_token %}
      <label>Researcher Name(s):
        <input type="text" name="researcher"><br>
      <lable>Study Summary
        <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>
      <br>
      <label>Upload your IRB approval letter:
        <input type ="file" id="irb-file" class="file_input" name="document"></label>
      <br>
      <input type = "submit" value="Submit" class="btn btn-primary" />
  </form>
</code>```

views.py

```<code>def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
    return render(request, 'about_experiment.html', context)

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        posts = Help.objects.filter().order_by('-date')[0]
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            researcher = form.cleaned_data['researcher']
            study = form.cleaned_data['study']
            document = form.cleaned_data['document']

  else:
      form = AboutHelp()
      posts = Help.objects.filter().order_by('-date')[0]
      return render(request, 'about_experiment.html', {'posts': posts})
  return render(request, 'about_experiment.html', {'posts': posts})
</code>```

destination page

```<code>  <h4><b>{{ posts.researcher }}</b></h4>
          <p>{{ posts.study }}</p>
          <p>Uploaded file is : {{ posts.document }}</p>
</code>```

答: Have you checked your file is been saved? And I think you have not understood the use of Django forms yet.Here's how to .You're creating the form but you're displaying fields manually and in view, you getting the data by forms.cleaned_data. Also, to save files you need to define <form enctype="multipart/form-data" > Here's why

Title: Django file upload not displaying

Body:
I have written the code for file upload but it is not displaying on my destination page.
Please help me edit my code or suggest how to fix this issue.
The rest of the fields are displaying but not the file field

My models.py

class Help(models.Model):
  researcher  = models.CharField(max_length=100)
  study = models.CharField(max_length=500)
  date = models.DateTimeField(auto_now_add=True)
  document = models.FileField(upload_to='documents/', null=True, blank=True)

forms.py

from django import forms
from .models import Help
from django.forms import ModelForm

class AboutHelp(forms.ModelForm):

    class Meta:
        model = Help
        fields = '__all__'

source page

<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form">
  {% csrf_token %}
      Researcher Name(s):
        <input type="text" name="researcher">

      <lable>Study Summary
        <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea>

      Upload your IRB approval letter:
        <input type ="file" id="irb-file" class="file_input" name="document">

      <input type = "submit" value="Submit" class="btn btn-primary" />
  </form>

views.py

def about_experiment(request, ex_link_name):
  researcher = None
  study = None
  posts = None
  exp = get_object_or_404(Experiment,link_name = ex_link_name)
  high_scores = ScoreItem.objects.filter(experiment=exp,active=True)
  context = {
    'request': request,
    'exp':exp,
    'high_scores': high_scores,
    'awards':AwardItem.objects.filter(experiment=exp,visible=True),
  }

  if exp.about_file:
    context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path()
    return render(request, 'about_experiment.html', context)

  if request.method == 'POST':
        form = AboutHelp(request.POST, request.FILES)
        posts = Help.objects.filter().order_by('-date')[0]
        if form.is_valid():
            obj = form.save(commit = False)
            obj.save()
            researcher = form.cleaned_data['researcher']
            study = form.cleaned_data['study']
            document = form.cleaned_data['document']

  else:
      form = AboutHelp()
      posts = Help.objects.filter().order_by('-date')[0]
      return render(request, 'about_experiment.html', {'posts': posts})
  return render(request, 'about_experiment.html', {'posts': posts})

destination page

{{ posts.researcher }}

{{ posts.study }}

Uploaded file is : {{ posts.document }}


问:
Datatable error on initialising via node require
the code am using to require the datatables plugins is

```<code>window.$ = window.jQuery = require('jquery');

dt = require('datatables.net')(window, $);
dt_bs = require('datatables.net-bs')(window, $);
buttons = require('datatables.net-buttons')(window, $);
buttons_bs = require('datatables.net-buttons-bs')(window, $);
responsive = require('datatables.net-responsive')(window, $);
responsive_bs = require('datatables.net-responsive-bs')(window, $);
colreorder = require('datatables.net-colreorder')(window, $);
fixedheader = require('datatables.net-fixedheader')(window, $);
scroller = require('datatables.net-scroller')(window, $);
</code>```

but when I compile the assets and run the error am getting is

```<code>TypeError: this is undefined
</code>```

I don't know what am doing wrong and yes I have tested the error comes from this section because if I comment out the section there is no error so any help would be highly appreciated, it's already driving me nuts. Thanks in advance.

P.S. This is my reference

答:
I had to change my code to this and the error disappeared</p>

```<code>window.$ = window.jQuery = require('jquery');

dt = require('datatables.net');
dt_bs = require('datatables.net-bs');
buttons = require('datatables.net-buttons');
buttons_bs = require('datatables.net-buttons-bs');
responsive = require('datatables.net-responsive');
responsive_bs = require('datatables.net-responsive-bs');
colreorder = require('datatables.net-colreorder');
fixedheader = require('datatables.net-fixedheader');
scroller = require('datatables.net-scroller');
</code>```

Body:
the code am using to require the datatables plugins is

window.$ = window.jQuery = require('jquery');

dt = require('datatables.net')(window, $);
dt_bs = require('datatables.net-bs')(window, $);
buttons = require('datatables.net-buttons')(window, $);
buttons_bs = require('datatables.net-buttons-bs')(window, $);
responsive = require('datatables.net-responsive')(window, $);
responsive_bs = require('datatables.net-responsive-bs')(window, $);
colreorder = require('datatables.net-colreorder')(window, $);
fixedheader = require('datatables.net-fixedheader')(window, $);
scroller = require('datatables.net-scroller')(window, $);

but when I compile the assets and run the error am getting is

TypeError: this is undefined

I don't know what am doing wrong and yes I have tested the error comes from this section because if I comment out the section there is no error so any help would be highly appreciated, it's already driving me nuts. Thanks in advance.

P.S. This is my reference

Body:
I had to change my code to this and the error disappeared

window.$ = window.jQuery = require('jquery');

dt = require('datatables.net');
dt_bs = require('datatables.net-bs');
buttons = require('datatables.net-buttons');
buttons_bs = require('datatables.net-buttons-bs');
responsive = require('datatables.net-responsive');
responsive_bs = require('datatables.net-responsive-bs');
colreorder = require('datatables.net-colreorder');
fixedheader = require('datatables.net-fixedheader');
scroller = require('datatables.net-scroller');


问:
Javascript array items to numbers
I've made a program that sorts numbers user inputs. The problem is that when I insert an empty space, it is stored in array as a number 0. I tried to set up several conditions to prevent this but nothing seems to work out. Any solution?
here's a little snippet of my code where I believe the mistake occurs and where some kind of condition should be set:
stringArray = userInput.value.split(' ');
  numArray = stringArray.map(Number);

答:
```<code>var numArray= stringArray.map(n=>parseInt(n,10));
</code>```

Simply use parseInt which is more strict ( and returns NaN in this case).So you could Filter:

```<code>numArray=numArray.filter(e=>!isNaN(e));
</code>```

Title: Javascript array items to numbers

Body:
var numArray= stringArray.map(n=>parseInt(n,10));

Simply use parseInt which is more strict ( and returns NaN in this case).So you could Filter:

numArray=numArray.filter(e=>!isNaN(e));


问:
Super complicated SQL statement...maybe impossible
I've done some programming and some SQL but is no developer except for my own little projects.
I now have a problem I would love to solve in pure SQL but can't really figure out how.
I have 2 simple tables that i need to draw a monthly report from, but i need to do some counting and that's the tricky part.
Here are the structure...

```<code>table
  km_locations
columns
  location_id INT
  location_name TXT

table
  km_trips
colums
  trip_id INT
  trip_date DATE
  start_location_id INT
  end_location_id INT
  km_start INT
  km_end INT
</code>```

And here are the rules that make it too complicated for me to figure out...

Create a report within a specific date range eg. between
2016-02-15 and 2016-03-15.

Replace start_location_id and end_location_id with corresponding
location_name in km_locations.

Count how many similar trips i made within the last 12 months and
show the incremental value in a separate column.

Only count trips too or from Home, and only count if no other trips with same start and end destination combo have been made on the date.

The sample below without total_trips I can get with this statement.

```<code>SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC
</code>```

wanted sample date output

```<code>id     date     trip_start      trip_end        km_start    km_end  total_trips
1   2016-02-15  Home            Grocery Store   10675       10681   8
2   2016-02-15  Grocery Store   Gas Station     10681       10684
3   2016-02-15  Gas Station     Home            10684       10689   5
4   2016-02-16  Home            Grocery Store   10689       10695   9
5   2016-02-16  Grocery Store   Home            10695       10701
6   2016-02-17  Home            School          10701       10723   12
7   2016-02-17  School          Grocery Store   10723       10739
8   2016-02-17  Grocery Store   Friends House   10739       10755
9   2016-02-17  Friends House   Home            10755       10767   7
10  2016-02-18  Home            Friends House   10767       10783   8
11  2016-02-18  Friends House   Home            10755       10767
12  2016-02-19  Home            Friends House   10767       10783   9
13  2016-02-19  Friends House   Grocery Store   10783       10792
14  2016-02-19  Grocery Store   Home            10792       10798   10
</code>```

It might be too much for a SQL statement but I'm thinking that it might be possible with views, unions and som mad skills.
It is a new project I am moving from Excel, so I'm open to any suggestions to table structures that can make this work.
Right now I'm trying to make this work with SQLite but will go with another databse if that is my only option.

Thanks.

答:
Try correlated subquery kind of</p>

```<code>SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end,
(SELECT count(DISTINCT t2.trip_date) cnt
 FROM km_trips t2
 WHERE t2.trip_date < t.trip_date
    AND  t2.start_location_id = t.start_location_id
    AND  t2.end_location_id = t.end_location_id
    AND (SELECT location_id FROM km_locations WHERE location_name = 'home')
         IN (t2.start_location_id, t2.end_location_id)
 ) count
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC
</code>```

Body:
I've done some programming and some SQL but is no developer except for my own little projects.
I now have a problem I would love to solve in pure SQL but can't really figure out how.
I have 2 simple tables that i need to draw a monthly report from, but i need to do some counting and that's the tricky part.
Here are the structure...

table
  km_locations
columns
  location_id INT
  location_name TXT

table
  km_trips
colums
  trip_id INT
  trip_date DATE
  start_location_id INT
  end_location_id INT
  km_start INT
  km_end INT

And here are the rules that make it too complicated for me to figure out...

Create a report within a specific date range eg. between
2016-02-15 and 2016-03-15.

Replace start_location_id and end_location_id with corresponding
location_name in km_locations.

Count how many similar trips i made within the last 12 months and
show the incremental value in a separate column.

Only count trips too or from Home, and only count if no other trips with same start and end destination combo have been made on the date.

The sample below without total_trips I can get with this statement.

SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC

wanted sample date output

id     date     trip_start      trip_end        km_start    km_end  total_trips
1   2016-02-15  Home            Grocery Store   10675       10681   8
2   2016-02-15  Grocery Store   Gas Station     10681       10684
3   2016-02-15  Gas Station     Home            10684       10689   5
4   2016-02-16  Home            Grocery Store   10689       10695   9
5   2016-02-16  Grocery Store   Home            10695       10701
6   2016-02-17  Home            School          10701       10723   12
7   2016-02-17  School          Grocery Store   10723       10739
8   2016-02-17  Grocery Store   Friends House   10739       10755
9   2016-02-17  Friends House   Home            10755       10767   7
10  2016-02-18  Home            Friends House   10767       10783   8
11  2016-02-18  Friends House   Home            10755       10767
12  2016-02-19  Home            Friends House   10767       10783   9
13  2016-02-19  Friends House   Grocery Store   10783       10792
14  2016-02-19  Grocery Store   Home            10792       10798   10

It might be too much for a SQL statement but I'm thinking that it might be possible with views, unions and som mad skills.
It is a new project I am moving from Excel, so I'm open to any suggestions to table structures that can make this work.
Right now I'm trying to make this work with SQLite but will go with another databse if that is my only option.

Thanks.

Body:
Try correlated subquery kind of

SELECT
t.trip_date,
c1.location_name AS 'trip_start',
c2.location_name AS 'trip_end',
t.km_start,
t.km_end,
(SELECT count(DISTINCT t2.trip_date) cnt
 FROM km_trips t2
 WHERE t2.trip_date < t.trip_date
    AND  t2.start_location_id = t.start_location_id
    AND  t2.end_location_id = t.end_location_id
    AND (SELECT location_id FROM km_locations WHERE location_name = 'home')
         IN (t2.start_location_id, t2.end_location_id)
 ) count
FROM km_trips t
LEFT JOIN km_locations c1 ON c1.location_id = t.start_location_id
LEFT JOIN km_locations c2 ON c2.location_id = t.end_location_id
WHERE t.trip_date BETWEEN '2016-02-06' AND '2016-03-10'
ORDER BY t.trip_date ASC, t.km_start ASC


问:
How to get the records from database from a particular date..through procedure. date passes as parameter
This is my procedure i am unable to get the records for the particular date..

i have the data on particular date but output is zero..
            but when i use >= it gives me data..

using = @Date as parameter gives zero output..

using >= @Date as parameter gives output

my procedure where do i need to modify to get the data according to dates supplied.

```<code>Declare @ids varchar(max);
set @ids = (select ids from USers where UserId = 10)
  select F.Date as DateOfuser,F.ID , (B.FirstName + ',' + B.LastName) as Name,
A.Group ,E.companyname,E.company ,D.receivedDate
from Details as A
inner join Usersnew as B
on A.newId = B.newId
inner join Files as D
on D.DocId = B.Docid
Inner join PDetails as C
on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) = @Date  ))  -- @parameter @date // no output
and D.GId in(select ID from fnSplitter(@ids))
inner join PDetails as E
on E.PId = C.Id
inner join Information as F
on F.PId = E.PId
</code>```

how do i get the records on particular day passed as a parameter..

I have the data but its not returning how do i modify my procedure to get
the data

i need to get output based on dates..i have data received through dates so date passed as parameter..

please help?

any idea to get records on a particular date passed as parameter?

why

= is not returning  >= is returning

can u please explain?

cant we pass = operand in procedure that equals the date passed?

答:
As @Simon said. There is probably problem with comparing date to datetime. When you compare date to datetime, date is casted to datetime, e.g. "2017-07-04" is casted to "2017-07-04 00:00:00.000".
Change line:

```<code>    on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) = @Date  ))
</code>```

to:

```<code>on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) >= @Date) AND (convert(datetime,D.ReceivedDate, 20) < DATEADD(dd,1,@Date)))
</code>```

You can also change it to this:

```<code>on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(cast(D.ReceivedDate as date) = @Date  ))
</code>```

Body:
This is my procedure i am unable to get the records for the particular date..

i have the data on particular date but output is zero..
            but when i use >= it gives me data..

using = @Date as parameter gives zero output..

using >= @Date as parameter gives output

my procedure where do i need to modify to get the data according to dates supplied.

Declare @ids varchar(max);
set @ids = (select ids from USers where UserId = 10)
  select F.Date as DateOfuser,F.ID , (B.FirstName + ',' + B.LastName) as Name,
A.Group ,E.companyname,E.company ,D.receivedDate
from Details as A
inner join Usersnew as B
on A.newId = B.newId
inner join Files as D
on D.DocId = B.Docid
Inner join PDetails as C
on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) = @Date  ))  -- @parameter @date // no output
and D.GId in(select ID from fnSplitter(@ids))
inner join PDetails as E
on E.PId = C.Id
inner join Information as F
on F.PId = E.PId

how do i get the records on particular day passed as a parameter..

I have the data but its not returning how do i modify my procedure to get
the data

i need to get output based on dates..i have data received through dates so date passed as parameter..

please help?

any idea to get records on a particular date passed as parameter?

why

= is not returning  >= is returning

can u please explain?

cant we pass = operand in procedure that equals the date passed?

Body:
As @Simon said. There is probably problem with comparing date to datetime. When you compare date to datetime, date is casted to datetime, e.g. "2017-07-04" is casted to "2017-07-04 00:00:00.000".
Change line:

    on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) = @Date  ))

to:

on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(convert(datetime,D.ReceivedDate, 20) >= @Date) AND (convert(datetime,D.ReceivedDate, 20) < DATEADD(dd,1,@Date)))

You can also change it to this:

on (D.GId = c.GId and D.PId = C.Id and D.IsActive='True' and
(cast(D.ReceivedDate as date) = @Date  ))


问:
When Configuring System in Jenkins and I click save, I receive an error saying "JSONObject["useFrench"] is not a Boolean."
I am integrating a new plugin into Jenkins. It connects successfully. But when I go to save the changes I get an error. I have also tried by removing the plugin and trying to save the changes in Configure System. Still giving me the same error. Here is the stack trace:</p>

```<code>javax.servlet.ServletException: net.sf.json.JSONException: JSONObject["useFrench"] is not a Boolean.
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:796)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1494)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:132)
at hudson.plugins.greenballs.GreenBallFilter.doFilter(GreenBallFilter.java:59)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:123)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1474)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)

Caused by: net.sf.json.JSONException: JSONObject["useFrench"] is not a Boolean.
at net.sf.json.JSONObject.getBoolean(JSONObject.java:1929)
at com.fidelity.fpcms.jenkins.plugins.fitnesseplugin.FitnesseResultBuilder$DescriptorImpl.configure(FitnesseResultBuilder.java:179)
at jenkins.model.Jenkins.configureDescriptor(Jenkins.java:2965)
at jenkins.model.Jenkins.doConfigSubmit(Jenkins.java:2928)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)
at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)
at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
... 46 more
</code>```

答:
Ah, I've seen useFrench before :-)
You are implementing the HelloWorldBuilder from the hello world plugin.

I'd say check your global.jelly file - you changed the class names, perhaps there is a string reference somewhere that you didn't catch.

A dose of good old printf-debugging may help, just like running the plugin inside a debugger; for you to see how Jenkins processes requests.

If nothing succeeds, try to just fork the plugin, see it working - and only then begin to alter it step by step.

Body:
I am integrating a new plugin into Jenkins. It connects successfully. But when I go to save the changes I get an error. I have also tried by removing the plugin and trying to save the changes in Configure System. Still giving me the same error. Here is the stack trace:

javax.servlet.ServletException: net.sf.json.JSONException: JSONObject["useFrench"] is not a Boolean.
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:796)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1494)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:132)
at hudson.plugins.greenballs.GreenBallFilter.doFilter(GreenBallFilter.java:59)
at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:129)
at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:123)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:81)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1482)
at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1474)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:499)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:533)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:370)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)

Caused by: net.sf.json.JSONException: JSONObject["useFrench"] is not a Boolean.
at net.sf.json.JSONObject.getBoolean(JSONObject.java:1929)
at com.fidelity.fpcms.jenkins.plugins.fitnesseplugin.FitnesseResultBuilder$DescriptorImpl.configure(FitnesseResultBuilder.java:179)
at jenkins.model.Jenkins.configureDescriptor(Jenkins.java:2965)
at jenkins.model.Jenkins.doConfigSubmit(Jenkins.java:2928)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:298)
at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:161)
at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:96)
at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:121)
at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:53)
at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
... 46 more