问:
Datagridview background color shows on SECOND databind
I have a datagridview which I'm doing a lot of stuff to which I know I shouldn't be doing. You know, following requirements.

One of those requirements is to colorize a certain cell of each row depending on certain values.  I'm doing this on the ETA and Approved fields. Both usually work the second time this code runs. On some rows, and only for the Approved field, it never colorizes until I restart the whole app. Why does this happen?

I have verified all the referenced data does indeed exist.

I have verified the colorizing lines below do indeed get hit, even on rows that don't colorize the first time around.

Winforms / .NET 3.5

```<code>List<int>
    ClinicIDs = new List<int>(),
    ZoneIDs = new List<int>();
foreach (Clinic c in lb_Clinics_RM.SelectedItems)
    ClinicIDs.Add(((Clinic)c).ID);
foreach (Zone z in lb_Zones_RM.SelectedItems)
    ZoneIDs.Add(((Zone)z).ID);

if (lb_Clinics_RM.SelectedItems.Count == 0)
    foreach (Clinic c in lb_Clinics_RM.Items)
        ClinicIDs.Add(((Clinic)c).ID);
if (lb_Zones_RM.SelectedItems.Count == 0)
    foreach (Zone z in lb_Zones_RM.Items)
        ZoneIDs.Add(((Zone)z).ID);

dgRides.DataSource = from r in dc.Rides
                     where ((DateTime)r.ApptDatetime).Date == dtRides.Value.Date
                        && (ZoneIDs.Contains((from c in r.Location.Clinics select c.Zone.ID).FirstOrDefault())
                            || ZoneIDs.Contains((from c in r.Location1.Clinics select c.Zone.ID).FirstOrDefault()))
                        && (ClinicIDs.Contains((from c in r.Location.Clinics select c.ID).FirstOrDefault())
                            || ClinicIDs.Contains((from c in r.Location1.Clinics select c.ID).FirstOrDefault()))
                     orderby r.isRejected descending, r.ApptDatetime.Value, r.isApproved, r.PatientID
                     select new
                    {
                        r.ID,
                        PatientID = r.PatientID,
                        Approved = " ",
                        Appointment = r.ApptDatetime.Value.TimeOfDay,
                        RideID = r.ID,
                        ETA = r.ETA.TimeOfDay,
                        Clinic = (from c in dc.Clinics where c.Location.ID == r.Location.ID || c.Location.ID == r.Location1.ID select c).FirstOrDefault().Name,
                        Direction = (r.ApptDuration == 0 ? "Outbound" : "Inbound"),
                        LastName = r.Patient.LastName,
                        FirstName = r.Patient.FirstName,
                        From = r.Location.Clinics.Count() > 0 ? r.Location.Clinics.First().Name : r.Location.Address,
                        To = r.Location1.Clinics.Count() > 0 ? r.Location1.Clinics.First().Name : r.Location1.Address,
                        Driver = r.Driver.Name == "Unassigned" ? "" : r.Driver.Name,
                        Vehicle = r.Driver.Name == "Unassigned" ? "" : r.Driver.Vehicle.VehicleNumber
                    };

if (dgRides.Columns.Count == 0)
    return;

// Format displayed rides
foreach (DataGridViewRow dr in dgRides.Rows)
{
    if (dr.Index == -1) continue;
    Ride ride;
    try { ride = (from r in dc.Rides where r.ID == ((int)dr.Cells[0].Value) select r).First(); }
    catch { continue; }

    TimeSpan diff = ride.ETA - ride.ApptDatetime.Value;
    Color fore;
    dr.Cells["ETA"].Style.BackColor = Common.GetColorByLateness(diff.Minutes, out fore);
    dr.Cells["ETA"].Style.ForeColor = fore;

    if (ride.isApproved)
        dr.Cells["Approved"].Style.BackColor = Color.Green;
    else if (ride.isRejected)
        dr.Cells["Approved"].Style.BackColor = Color.Red;
}
</code>```

and

```<code>public static Color GetColorByLateness(int MinutesLate, out Color Foreground)
{
    int
        ETAYellowMinutes = int.Parse(Lookups.GetSetting("ETAYellowMinutes")),
        ETARedMinutes = int.Parse(Lookups.GetSetting("ETARedMinutes"));

    Foreground = Color.White;

    if (MinutesLate > ETARedMinutes)
        return Color.DarkRed;
    else if (MinutesLate > ETAYellowMinutes)
        return Color.FromArgb(100, 100, 0);
    else
        return Color.Green;
}
</code>```

答:
Why don't you use the CellFormatting event?
See this post</p>

Body:
I have a datagridview which I'm doing a lot of stuff to which I know I shouldn't be doing. You know, following requirements.

One of those requirements is to colorize a certain cell of each row depending on certain values.  I'm doing this on the ETA and Approved fields. Both usually work the second time this code runs. On some rows, and only for the Approved field, it never colorizes until I restart the whole app. Why does this happen?

I have verified all the referenced data does indeed exist.

I have verified the colorizing lines below do indeed get hit, even on rows that don't colorize the first time around.

Winforms / .NET 3.5

List<int>
    ClinicIDs = new List<int>(),
    ZoneIDs = new List<int>();
foreach (Clinic c in lb_Clinics_RM.SelectedItems)
    ClinicIDs.Add(((Clinic)c).ID);
foreach (Zone z in lb_Zones_RM.SelectedItems)
    ZoneIDs.Add(((Zone)z).ID);

if (lb_Clinics_RM.SelectedItems.Count == 0)
    foreach (Clinic c in lb_Clinics_RM.Items)
        ClinicIDs.Add(((Clinic)c).ID);
if (lb_Zones_RM.SelectedItems.Count == 0)
    foreach (Zone z in lb_Zones_RM.Items)
        ZoneIDs.Add(((Zone)z).ID);

dgRides.DataSource = from r in dc.Rides
                     where ((DateTime)r.ApptDatetime).Date == dtRides.Value.Date
                        && (ZoneIDs.Contains((from c in r.Location.Clinics select c.Zone.ID).FirstOrDefault())
                            || ZoneIDs.Contains((from c in r.Location1.Clinics select c.Zone.ID).FirstOrDefault()))
                        && (ClinicIDs.Contains((from c in r.Location.Clinics select c.ID).FirstOrDefault())
                            || ClinicIDs.Contains((from c in r.Location1.Clinics select c.ID).FirstOrDefault()))
                     orderby r.isRejected descending, r.ApptDatetime.Value, r.isApproved, r.PatientID
                     select new
                    {
                        r.ID,
                        PatientID = r.PatientID,
                        Approved = " ",
                        Appointment = r.ApptDatetime.Value.TimeOfDay,
                        RideID = r.ID,
                        ETA = r.ETA.TimeOfDay,
                        Clinic = (from c in dc.Clinics where c.Location.ID == r.Location.ID || c.Location.ID == r.Location1.ID select c).FirstOrDefault().Name,
                        Direction = (r.ApptDuration == 0 ? "Outbound" : "Inbound"),
                        LastName = r.Patient.LastName,
                        FirstName = r.Patient.FirstName,
                        From = r.Location.Clinics.Count() > 0 ? r.Location.Clinics.First().Name : r.Location.Address,
                        To = r.Location1.Clinics.Count() > 0 ? r.Location1.Clinics.First().Name : r.Location1.Address,
                        Driver = r.Driver.Name == "Unassigned" ? "" : r.Driver.Name,
                        Vehicle = r.Driver.Name == "Unassigned" ? "" : r.Driver.Vehicle.VehicleNumber
                    };

if (dgRides.Columns.Count == 0)
    return;

// Format displayed rides
foreach (DataGridViewRow dr in dgRides.Rows)
{
    if (dr.Index == -1) continue;
    Ride ride;
    try { ride = (from r in dc.Rides where r.ID == ((int)dr.Cells[0].Value) select r).First(); }
    catch { continue; }

    TimeSpan diff = ride.ETA - ride.ApptDatetime.Value;
    Color fore;
    dr.Cells["ETA"].Style.BackColor = Common.GetColorByLateness(diff.Minutes, out fore);
    dr.Cells["ETA"].Style.ForeColor = fore;

    if (ride.isApproved)
        dr.Cells["Approved"].Style.BackColor = Color.Green;
    else if (ride.isRejected)
        dr.Cells["Approved"].Style.BackColor = Color.Red;
}

and

public static Color GetColorByLateness(int MinutesLate, out Color Foreground)
{
    int
        ETAYellowMinutes = int.Parse(Lookups.GetSetting("ETAYellowMinutes")),
        ETARedMinutes = int.Parse(Lookups.GetSetting("ETARedMinutes"));

    Foreground = Color.White;

    if (MinutesLate > ETARedMinutes)
        return Color.DarkRed;
    else if (MinutesLate > ETAYellowMinutes)
        return Color.FromArgb(100, 100, 0);
    else
        return Color.Green;
}


来源: stackexchange

问:
How do you disable no-plusplus when using eslint?
When using eslint in Visual Studio Code, AirBnB style Ubuntu Linux, no-plusplus is enabled as default so using ++ for example in a for loop will error: [eslint] Unary operator '++' used. (no-plusplus)

How do you disable that setting?

答:
You can locate the file location you need to alter on Linux by searching for the keyword using grep, in this case to search for the file containing plusplus when in the folder eslint was installed use

grep -r plusplus

The correct file will be the eslint-config file, in this case it should be: node_modules/eslint-config-airbnb-base/rules/style.js

To disable the setting comment out the no-plusplus line, you can easily re-enable if required:

```<code>// 'no-plusplus': 'error',
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can locate the file location you need to alter on Linux by searching for the keyword using grep, in this case to search for the file containing plusplus when in the folder eslint was installed use

grep -r plusplus

The correct file will be the eslint-config file, in this case it should be: node_modules/eslint-config-airbnb-base/rules/style.js

To disable the setting comment out the no-plusplus line, you can easily re-enable if required:

// 'no-plusplus': 'error',


问:
Serving static files with nginx on multiple machines and hard drives
I have one project what will store large media content after it will be deployment. Project use Python, Django, also runned via Gunicorn and Supervisor.

For static files I will use nginx.

Basic setup I made by following this article, but I have an question, how can I store content more dynamicly. At the start I have one machine with 4 hard drives for 2Tb each, later will be buyed more, as well as the new machines (currently I have only one).

Site located as site.com, nginx located at subdomain i.site.com and have 2 folders in a root: /static for storing css, js, svg, e.t.c. design elements and /media what will be stored media content.

The problem is setup nginx to write media on each hard drives and each machine will be used.

For the speed I need to write every new file in a different hard drive (like rotation/loop), for example I saving file1, it writed at machine1/hdd1, then I saving file2, it writed at machine1/hdd2... file4 at machine1/hdd4, file5 at machine2/hdd1 (currently as I mentioned I have only one machine, but will be more in a future).

So, anyone have expirience or idea how can I make that? I'm sure nginx can at least write at multiple hard drives, but I'm not sure what can I do if I need to write media data at multiple machines.
If you also have any other idea, please suggest it as well.

Example of nginx config you may find in mentioned article, or by following this link. I also looking for nginx upstream module, but I not actually sure if I can configure that with it.

答:
Update:  Previously, I wrote the answer without giving much thought to the actual problem that you're trying to solve. Your comment below brings out some interesting problems that I had ignored previously. I've now re-written my answer. Hopefully, this will be helpful.

In the previous version of this answer I mentioned Load Balancing. But clearly your problem is more about file storage than managing load.

What you're looking for is called a Distributed File System. A distributed file system allows you to plug in many disks and it can scale out to multiple machines.

A DFS groups together all the disks and machines and gives you access to them as if it were a single disk. Not only that, a DFS software can also take care of file replication for you, if you want.

I've no experience with using any DFS, but I've read a little bit about GlusterFS. I hear it is good, but feel free to do your research.

Let me try and explain how GlusterFS works. Look at this diagram:

```<code>                                                                / Disk 1
                                  / Machine 1 [Gluster Server] |
                                 /                              \ Disk 2
                                /
Nginx  ->  Gluster Client  ->  |
                                \
                                 \                              / Disk 1
                                  \ Machine 2 [Gluster Server] |
                                                                \ Disk 2
</code>```

Without getting into too much details, the Gluster Client will allow your Nginx server to access both, Machine 1 and Machine 2 from a single directory, like /media. Inside this /media directory, you can access both the Machines just as if all the data is stored inside /media even though it is stored on different machines.

Guides and tutorials:

Setting up GlusterFS on Ubuntu - very good tutorial that explains a lot of basic stuff. Although, it's written for Ubuntu 12.04, I'm sure you can adapt it to your version of OS.

Common DFS architectures explained - some DFS architecture patterns that you might find helpful later on.

Body:
Update:  Previously, I wrote the answer without giving much thought to the actual problem that you're trying to solve. Your comment below brings out some interesting problems that I had ignored previously. I've now re-written my answer. Hopefully, this will be helpful.

In the previous version of this answer I mentioned Load Balancing. But clearly your problem is more about file storage than managing load.

What you're looking for is called a Distributed File System. A distributed file system allows you to plug in many disks and it can scale out to multiple machines.

A DFS groups together all the disks and machines and gives you access to them as if it were a single disk. Not only that, a DFS software can also take care of file replication for you, if you want.

I've no experience with using any DFS, but I've read a little bit about GlusterFS. I hear it is good, but feel free to do your research.

Let me try and explain how GlusterFS works. Look at this diagram:

                                                                / Disk 1
                                  / Machine 1 [Gluster Server] |
                                 /                              \ Disk 2
                                /
Nginx  ->  Gluster Client  ->  |
                                \
                                 \                              / Disk 1
                                  \ Machine 2 [Gluster Server] |
                                                                \ Disk 2

Without getting into too much details, the Gluster Client will allow your Nginx server to access both, Machine 1 and Machine 2 from a single directory, like /media. Inside this /media directory, you can access both the Machines just as if all the data is stored inside /media even though it is stored on different machines.

Guides and tutorials:

Setting up GlusterFS on Ubuntu - very good tutorial that explains a lot of basic stuff. Although, it's written for Ubuntu 12.04, I'm sure you can adapt it to your version of OS.

Common DFS architectures explained - some DFS architecture patterns that you might find helpful later on.


问:
PHP script not responding when estabslishing mysqli Connection
I just need a simple mysqli-Connection invoked from a php-Script. The following script doesn't respond. Would be way easier if some kind of error-message appears, or even some echo-statements for debugging purposes. But no. Only white screen.

```<code><?php
private $db_config_file = realpath(dirname(__FILE__)) . "config/db.ini";
    private $db = NULL;
    if (!file_exists($this->db_config_file)) {
    $msg = "The config-file <code>"
        . $this->db_config_file
        . "</code> doesnt't exist.";
    show_error_page($msg);
}

$config = parse_ini_file($this->db_config_file);
$host = $config[$host];
$user = $config[$user];
$password = $config[$password];
$dbname = $config[$dbname];

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else echo "Connection established!";

$conn->close();
?>
</code>```

The db.ini:

```<code>host = localhost
dbname = bl
user = mm
password = noadmin
</code>```

答:
try to change

```<code>$host = $config[$host];
$user = $config[$user];
$password = $config[$password];
$dbname = $config[$dbname];
</code>```

to

```<code>$host = $config['host'];
$user = $config['user'];
$password = $config['password'];
$dbname = $config['dbname'];
</code>```

you are using $host = $config[$host], it need to be $config['host']

Body:
I just need a simple mysqli-Connection invoked from a php-Script. The following script doesn't respond. Would be way easier if some kind of error-message appears, or even some echo-statements for debugging purposes. But no. Only white screen.

<?php
private $db_config_file = realpath(dirname(__FILE__)) . "config/db.ini";
    private $db = NULL;
    if (!file_exists($this->db_config_file)) {
    $msg = "The config-file "
        . $this->db_config_file
        . " doesnt't exist.";
    show_error_page($msg);
}

$config = parse_ini_file($this->db_config_file);
$host = $config[$host];
$user = $config[$user];
$password = $config[$password];
$dbname = $config[$dbname];

$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else echo "Connection established!";

$conn->close();
?>

The db.ini:

host = localhost
dbname = bl
user = mm
password = noadmin

Body:
try to change

$host = $config[$host];
$user = $config[$user];
$password = $config[$password];
$dbname = $config[$dbname];

to

$host = $config['host'];
$user = $config['user'];
$password = $config['password'];
$dbname = $config['dbname'];

you are using $host = $config[$host], it need to be $config['host']


问:
How to implement a singleton in C#?
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project.  I want to have them 'Global' and not need to manually bind them every object I create.</p>

答:
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TEClaim.Models
{
public class LogedinUserDetails
{
    public string UserID { get; set; }
    public string UserRole { get; set; }
    public string UserSupervisor { get; set; }
    public LogedinUserDetails()
    {

    }

    public static LogedinUserDetails Singleton()
    {
        LogedinUserDetails oSingleton;

        if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
        {
            oSingleton = new LogedinUserDetails();
            System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
        }
        else
        {
            oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
        }

        //Return the single instance of this class that was stored in the session
        return oSingleton;
    }
}
}
</code>```

Now you can set variable value for the above code in your application like this..

```<code>[HttpPost]
public ActionResult Login(FormCollection collection)
{
  LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
  User_Details.UserID = "12";
  User_Details.UserRole = "SuperAdmin";
  User_Details.UserSupervisor = "815978";
  return RedirectToAction("Dashboard", "Home");
}
</code>```

And you can retrieve those value like this..

```<code>public ActionResult Dashboard()
    {
        LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
        ViewData["UserID"] = User_Details.UserID;
        ViewData["UserRole"] = User_Details.UserRole;
        ViewData["UserSupervisor"] = User_Details.UserSupervisor;

        return View();
    }
</code>```

OwnerDisplayName: Andre

ContentLicense: CC BY-SA 2.5

Title: How to implement a singleton in C#?

LastEditorDisplayName: Corey

Body:
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TEClaim.Models
{
public class LogedinUserDetails
{
    public string UserID { get; set; }
    public string UserRole { get; set; }
    public string UserSupervisor { get; set; }
    public LogedinUserDetails()
    {

    }

    public static LogedinUserDetails Singleton()
    {
        LogedinUserDetails oSingleton;

        if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
        {
            oSingleton = new LogedinUserDetails();
            System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
        }
        else
        {
            oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
        }

        //Return the single instance of this class that was stored in the session
        return oSingleton;
    }
}
}

Now you can set variable value for the above code in your application like this..

[HttpPost]
public ActionResult Login(FormCollection collection)
{
  LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
  User_Details.UserID = "12";
  User_Details.UserRole = "SuperAdmin";
  User_Details.UserSupervisor = "815978";
  return RedirectToAction("Dashboard", "Home");
}

And you can retrieve those value like this..

public ActionResult Dashboard()
    {
        LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
        ViewData["UserID"] = User_Details.UserID;
        ViewData["UserRole"] = User_Details.UserRole;
        ViewData["UserSupervisor"] = User_Details.UserSupervisor;

        return View();
    }


问:
warning "@schematics/angular@0.0.49" has incorrect peer dependency "@angular-devkit/schematics@0.0.34"
I created new angular application using angular/cli and whenever yarn add any new packages , it warns that "@schematics/angular@0.0.49" has incorrect peer dependency "@angular-devkit/schematics@0.0.34".

can someone tell me how to resolve this issue?

答: It's a known issue with Angular CLI 1.6.0. You can safely ignore it, it will be fixed in 1.6.1.</p>


问:
Null pointer passed as argument 1
In line int d = atoi(argv[2]); there seems to be something wrong. "null pointer passed as argument 1..."

What can I do?

```<code>#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, string argv[])
{

    int num;
    int i = 1;
    int j = 1;
    int board [i][j];

   // 2nd CL argument is size of grid.

    if (argc != 2)
    {
        return false;
    }

    int d = atoi(argv[2]);

    if (d <= 0)
    {
        return false;
    }

    // setting up board.

    // number of tiles needed.
    num = d * d - 1;

    // iterating over columns and rows
    for (i = 0; i <= d; i++)
    {
        for (j = 0; j <= d; j++)
        {
            // set values.
            board[i][j] = num;
            num --;
        }
         printf ("%d", board[i][j]); // TESTING.
         printf ("\n");
    }

   // if even swap 1 & 2. Don't display 1.
}
</code>```

答:
You have a multiple issues with your program

1) string is not a standard type in C.

2) false is not a standard constant in C98.

Standard C (since C99) provides a boolean type, called _Bool. By including the header stdbool.h one can use the more intuitive name bool and the constants true and false.

3) Your board has a fixed size 1x1 board[1][1]:

```<code>   int i = 1;
   int j = 1;
   int board [i][j];
</code>```

Fix this otherwise your program will smash memory.

4) You need 2 arguments for your board. Arguments start on position argv[1] and argv[2] in argv[] Since first argv[0] is name of the program you need argc = 3.

Title: Null pointer passed as argument 1

Body:
In line int d = atoi(argv[2]); there seems to be something wrong. "null pointer passed as argument 1..."

What can I do?

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, string argv[])
{

    int num;
    int i = 1;
    int j = 1;
    int board [i][j];

   // 2nd CL argument is size of grid.

    if (argc != 2)
    {
        return false;
    }

    int d = atoi(argv[2]);

    if (d <= 0)
    {
        return false;
    }

    // setting up board.

    // number of tiles needed.
    num = d * d - 1;

    // iterating over columns and rows
    for (i = 0; i <= d; i++)
    {
        for (j = 0; j <= d; j++)
        {
            // set values.
            board[i][j] = num;
            num --;
        }
         printf ("%d", board[i][j]); // TESTING.
         printf ("\n");
    }

   // if even swap 1 & 2. Don't display 1.
}

Body:
You have a multiple issues with your program

1) string is not a standard type in C.

2) false is not a standard constant in C98.

Standard C (since C99) provides a boolean type, called _Bool. By including the header stdbool.h one can use the more intuitive name bool and the constants true and false.

3) Your board has a fixed size 1x1 board[1][1]:

   int i = 1;
   int j = 1;
   int board [i][j];

Fix this otherwise your program will smash memory.

4) You need 2 arguments for your board. Arguments start on position argv[1] and argv[2] in argv[] Since first argv[0] is name of the program you need argc = 3.


问:
Haptics don't play in background when bluetooth headphones are connected to Apple Watch
I have a watchOS3 workout app that uses haptic notifications. It setup correctly to run a workout session and haptics work when running in the background.  However, if bluetooth headphones are connected to the apple watch, then you only get the haptic vibration OR the audio chime for the haptic, depending on whether the app is currently showing on the watch face or running in background.

Here's how I'm playing the haptic:

```<code>WKInterfaceDevice.current().play(.notification)
</code>```

Here are the details:

Apple Watch Nike+ Unpaired to Headphones: Haptic and chime sound activate regardless of whether the watch face is on or off.  Chime sound is loud and clear.

Apple Watch Nike+ Paired to Bluetooth Headphones:
Haptic only active if watch face is on, audio chime is off. Audio chime is on when watch face is off, haptic is off.  Chime sound is loud and clear.

I tested the app pairing the Apple Watch separately with the Platronic Backbeat Go 2 (released 7/2013) and the Bose QuietControl 30 (released 10/2016). The results were the same.

Anyone know if this is a limitation of watchOS 3, a bug, or is there something else I need to be doing?

Thanks,
Jeff

答: The behavior documented in the question is the the way its supposed to be, according to Apple. The given reason is because of the delay between the haptic tap and the haptic audio when using bluetooth headphones. I'm hoping this behavior changes in the future...</p>

Body:
I have a watchOS3 workout app that uses haptic notifications. It setup correctly to run a workout session and haptics work when running in the background.  However, if bluetooth headphones are connected to the apple watch, then you only get the haptic vibration OR the audio chime for the haptic, depending on whether the app is currently showing on the watch face or running in background.

Here's how I'm playing the haptic:

WKInterfaceDevice.current().play(.notification)

Here are the details:

Apple Watch Nike+ Unpaired to Headphones: Haptic and chime sound activate regardless of whether the watch face is on or off.  Chime sound is loud and clear.

Apple Watch Nike+ Paired to Bluetooth Headphones:
Haptic only active if watch face is on, audio chime is off. Audio chime is on when watch face is off, haptic is off.  Chime sound is loud and clear.

I tested the app pairing the Apple Watch separately with the Platronic Backbeat Go 2 (released 7/2013) and the Bose QuietControl 30 (released 10/2016). The results were the same.

Anyone know if this is a limitation of watchOS 3, a bug, or is there something else I need to be doing?

Thanks,
Jeff


问:
Connecting two Queue Channels backed by JDBC Store in Spring Intgegration DSL
I'm trying to connect two Queue Channels (backed by JDBC Store).

```<code>@Configuration
public class DemoIntegration {
    @Bean
    public IntegrationFlow flow(MessageChannel firstJDBCChannel,
                                MessageChannel secondJDBCChannel) {
        return IntegrationFlows.from(firstJDBCChannel)
                .bridge(bridgeHandler -> bridgeHandler.poller(p -> p.fixedDelay(100L)))
                .handle(secondJDBCChannel)
                .get();
    }
}
</code>```

I tried to put different constructions between this two channels and still have an error like:

Caused by: java.lang.IllegalArgumentException: Found ambiguous
  parameter type [class java.lang.Void] for method match: [public
  boolean
  org.springframework.integration.channel.AbstractPollableChannel.removeInterceptor(org.springframework.messaging.support.ChannelInterceptor),
  public org.springframework.messaging.Message
  org.springframework.integration.channel.AbstractPollableChannel.receive(long),
  public final void
  org.springframework.integration.context.IntegrationObjectSupport.setPrimaryExpression(org.springframework.expression.Expression),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setStatsEnabled(boolean),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setMessageConverter(org.springframework.messaging.converter.MessageConverter),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setDatatypes(java.lang.Class...),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.configureMetrics(org.springframework.integration.support.management.AbstractMessageChannelMetrics),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setComponentName(java.lang.String),
  public org.springframework.messaging.support.ChannelInterceptor
  org.springframework.integration.channel.AbstractPollableChannel.removeInterceptor(int),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setMessageBuilderFactory(org.springframework.integration.support.MessageBuilderFactory),
  public java.util.List>
  org.springframework.integration.channel.QueueChannel.purge(org.springframework.integration.core.MessageSelector),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext)
  throws org.springframework.beans.BeansException, public void
  org.springframework.integration.context.IntegrationObjectSupport.setBeanFactory(org.springframework.beans.factory.BeanFactory),
  public org.springframework.expression.Expression
  org.springframework.integration.context.IntegrationObjectSupport.getExpression(),
  public void
  org.springframework.integration.channel.AbstractPollableChannel.setInterceptors(java.util.List),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setChannelResolver(org.springframework.messaging.core.DestinationResolver)]
    at org.springframework.util.Assert.isNull(Assert.java:155)
  ~[spring-core-5.0.1.RELEASE.jar:5.0.1.RELEASE]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.findHandlerMethodsForTarget(MessagingMethodInvokerHelper.java:776)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:379)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:225)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:220)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.handler.MethodInvokingMessageProcessor.(MethodInvokingMessageProcessor.java:60)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.handler.ServiceActivatingHandler.(ServiceActivatingHandler.java:38)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:924)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:904)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:891)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration.flow(DemoIntegration.java:16)
  ~[classes/:na]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3.CGLIB$flow$0()
  ~[classes/:na]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3$$FastClassBySpringCGLIB$$ef9b4b0c.invoke()
  ~[classes/:na]    at
  org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  ~[spring-core-5.0.1.RELEASE.jar:5.0.1.RELEASE]    at
  org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
  ~[spring-context-5.0.1.RELEASE.jar:5.0.1.RELEASE]     at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3.flow()
  ~[classes/:na]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method) ~[na:1.8.0_151]   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  ~[na:1.8.0_151]   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  ~[na:1.8.0_151]   at java.lang.reflect.Method.invoke(Method.java:498)
  ~[na:1.8.0_151]   at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:155)
  ~[spring-beans-5.0.1.RELEASE.jar:5.0.1.RELEASE]   ... 19 common frames
  omitted

How to correctly connect two (or more) queue channels? I need to make some processing between them and allow application to retain messages in case of stop.

Full log and code sample are on github: https://github.com/blazejkarwowski/integration-test

答:
Instead of .handle(secondJDBCChannel) you have to use .channel(secondJDBCChannel). There is nothing to handle - it is a Channel in between.

See Reference Manual  for more info.

Body:
I'm trying to connect two Queue Channels (backed by JDBC Store).

@Configuration
public class DemoIntegration {
    @Bean
    public IntegrationFlow flow(MessageChannel firstJDBCChannel,
                                MessageChannel secondJDBCChannel) {
        return IntegrationFlows.from(firstJDBCChannel)
                .bridge(bridgeHandler -> bridgeHandler.poller(p -> p.fixedDelay(100L)))
                .handle(secondJDBCChannel)
                .get();
    }
}

I tried to put different constructions between this two channels and still have an error like:

Caused by: java.lang.IllegalArgumentException: Found ambiguous
  parameter type [class java.lang.Void] for method match: [public
  boolean
  org.springframework.integration.channel.AbstractPollableChannel.removeInterceptor(org.springframework.messaging.support.ChannelInterceptor),
  public org.springframework.messaging.Message
  org.springframework.integration.channel.AbstractPollableChannel.receive(long),
  public final void
  org.springframework.integration.context.IntegrationObjectSupport.setPrimaryExpression(org.springframework.expression.Expression),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setStatsEnabled(boolean),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setMessageConverter(org.springframework.messaging.converter.MessageConverter),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.setDatatypes(java.lang.Class...),
  public void
  org.springframework.integration.channel.AbstractMessageChannel.configureMetrics(org.springframework.integration.support.management.AbstractMessageChannelMetrics),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setComponentName(java.lang.String),
  public org.springframework.messaging.support.ChannelInterceptor
  org.springframework.integration.channel.AbstractPollableChannel.removeInterceptor(int),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setMessageBuilderFactory(org.springframework.integration.support.MessageBuilderFactory),
  public java.util.List>
  org.springframework.integration.channel.QueueChannel.purge(org.springframework.integration.core.MessageSelector),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setApplicationContext(org.springframework.context.ApplicationContext)
  throws org.springframework.beans.BeansException, public void
  org.springframework.integration.context.IntegrationObjectSupport.setBeanFactory(org.springframework.beans.factory.BeanFactory),
  public org.springframework.expression.Expression
  org.springframework.integration.context.IntegrationObjectSupport.getExpression(),
  public void
  org.springframework.integration.channel.AbstractPollableChannel.setInterceptors(java.util.List),
  public void
  org.springframework.integration.context.IntegrationObjectSupport.setChannelResolver(org.springframework.messaging.core.DestinationResolver)]
    at org.springframework.util.Assert.isNull(Assert.java:155)
  ~[spring-core-5.0.1.RELEASE.jar:5.0.1.RELEASE]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.findHandlerMethodsForTarget(MessagingMethodInvokerHelper.java:776)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:379)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:225)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.util.MessagingMethodInvokerHelper.(MessagingMethodInvokerHelper.java:220)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.handler.MethodInvokingMessageProcessor.(MethodInvokingMessageProcessor.java:60)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.handler.ServiceActivatingHandler.(ServiceActivatingHandler.java:38)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:924)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:904)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  org.springframework.integration.dsl.IntegrationFlowDefinition.handle(IntegrationFlowDefinition.java:891)
  ~[spring-integration-core-5.0.0.RC1.jar:5.0.0.RC1]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration.flow(DemoIntegration.java:16)
  ~[classes/:na]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3.CGLIB$flow$0()
  ~[classes/:na]    at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3$$FastClassBySpringCGLIB$$ef9b4b0c.invoke()
  ~[classes/:na]    at
  org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  ~[spring-core-5.0.1.RELEASE.jar:5.0.1.RELEASE]    at
  org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
  ~[spring-context-5.0.1.RELEASE.jar:5.0.1.RELEASE]     at
  name.karwowski.blazej.integrationdemo2.DemoIntegration$$EnhancerBySpringCGLIB$$f82aadc3.flow()
  ~[classes/:na]    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
  Method) ~[na:1.8.0_151]   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  ~[na:1.8.0_151]   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  ~[na:1.8.0_151]   at java.lang.reflect.Method.invoke(Method.java:498)
  ~[na:1.8.0_151]   at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:155)
  ~[spring-beans-5.0.1.RELEASE.jar:5.0.1.RELEASE]   ... 19 common frames
  omitted

How to correctly connect two (or more) queue channels? I need to make some processing between them and allow application to retain messages in case of stop.

Full log and code sample are on github: https://github.com/blazejkarwowski/integration-test


问:
Display option selected with codeigniter
I want to ask for my code option selected with 2 tabel in page register

```<code>table prodi
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id_prodi    | varchar(3)  | NO   | PRI | NULL    |       |
| nama_prodi  | varchar(30) | NO   |     | NULL    |       |
| id_fakultas | varchar(3)  | NO   | MUL | NULL    |       |
| id          | int(2)      | NO   | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+
</code>```

and

```<code>table jurusan
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| id_fakultas   | varchar(3)  | NO   | PRI | NULL    |       |
| nama_fakultas | varchar(40) | NO   |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
</code>```

here's view :

```<code> <label for="fakultas">Fakultas : </label>
  <select id="fakultas" name="fakultas_user"  onChange="fakultas">

    <?php
      foreach ($qfakultas as $fakultas) {
        echo "<option value=".$fakultas->kd_fakultas.">".$fakultas->nama_fakultas."</option>";
      }
    ?>
  </select>

  <hr>

  <label for="jurusan">Jurusan  : </label>
  <select id="jurusan" name="jurusan_user" onChange="jurusan">
    <?php
      foreach ($qprodi as $prodi) {
        echo "<option value=".$prodi->kd_prodi.">".$prodi->nama_prodi."</option>";
      }
    ?>
  </select>
</code>```

but I will display 'nama_prodi' based on 'id_fakultas"

register with option value

How to display when I click 'nama_fakultas' then display 'nama_prodi' based on 'id_fakultas' ?

Thanks

答:
Here is the Ajax code that I can help, only to get nama_prodi based on id_falkutas.

You can use this code for your project, there is something you need to do.
Not just copy the code. Just a few step
(ID Lang : Jangan dicopy mentah2, hanya beberapa langkah saja untuk edit).

Change YOUR_URL_HERE into your base_url() or create var for it.

Change nama_controller into your controller name in CI_Controller

Change nama_fungsi into your function to get the data from your model (database).
Example : ambil_data_jurusan.

Remove your foreach - echo <option> and onchange from your view.

Add the script into your view files or create a new .js file.

Please help me to mark as correct answer if this code helped you. ( tolong dibantu gan )

See Code Example :

```<code><script>
$("#falkutas").on('change', function() {
   $.ajax({
        type:"POST",
        url:'YOUR_URL_HERE/nama_controller/nama_fungsi',
        data:{"falkutas_user":falkutas_user,"csrf_token":$("input[name=csrf_token]").val()},
        dataType:'json',
        success: function(result) {
            for(var i=0; i<result.length; i++) {
                res += '<option value="'+result[i]['id_prodi']+'">'+result[i]['nama_prodi']+'</option>';
            }
            $(document).ready(function() {
                 $("#prodi").html(res);
            });
        },
        error: function(result) {
            $(document).ready(function() {
                $("#prodi").html(''); //empty select value
            });
        }
    });
}
</script>
</code>```

Then, in your function code :

```<code>// Inside function ambil_data_jurusan(), harusnya sudah jalan kalau gini
$return = $this->model->get_jurusan($this->input->post('falkutas',TRUE));
if(count($return)>0) {
    echo json_encode($return);
}
</code>```

In your view, just let select empty like this.

```<code><select id="jurusan" name="jurusan_user">

</select>
</code>```

Body:
I want to ask for my code option selected with 2 tabel in page register

table prodi
+-------------+-------------+------+-----+---------+-------+
| Field       | Type        | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| id_prodi    | varchar(3)  | NO   | PRI | NULL    |       |
| nama_prodi  | varchar(30) | NO   |     | NULL    |       |
| id_fakultas | varchar(3)  | NO   | MUL | NULL    |       |
| id          | int(2)      | NO   | MUL | NULL    |       |
+-------------+-------------+------+-----+---------+-------+

and

table jurusan
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| id_fakultas   | varchar(3)  | NO   | PRI | NULL    |       |
| nama_fakultas | varchar(40) | NO   |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+

here's view :

 Fakultas :
  <select id="fakultas" name="fakultas_user"  onChange="fakultas">

    <?php
      foreach ($qfakultas as $fakultas) {
        echo "<option value=".$fakultas->kd_fakultas.">".$fakultas->nama_fakultas."</option>";
      }
    ?>
  </select>

  Jurusan  :
  <select id="jurusan" name="jurusan_user" onChange="jurusan">
    <?php
      foreach ($qprodi as $prodi) {
        echo "<option value=".$prodi->kd_prodi.">".$prodi->nama_prodi."</option>";
      }
    ?>
  </select>

but I will display 'nama_prodi' based on 'id_fakultas"

register with option value

How to display when I click 'nama_fakultas' then display 'nama_prodi' based on 'id_fakultas' ?

Thanks

Body:
Here is the Ajax code that I can help, only to get nama_prodi based on id_falkutas.

You can use this code for your project, there is something you need to do.
Not just copy the code. Just a few step
(ID Lang : Jangan dicopy mentah2, hanya beberapa langkah saja untuk edit).

Change YOUR_URL_HERE into your base_url() or create var for it.

Change nama_controller into your controller name in CI_Controller

Change nama_fungsi into your function to get the data from your model (database).
Example : ambil_data_jurusan.

Remove your foreach - echo <option> and onchange from your view.

Add the script into your view files or create a new .js file.

Please help me to mark as correct answer if this code helped you. ( tolong dibantu gan )

See Code Example :

<script>
$("#falkutas").on('change', function() {
   $.ajax({
        type:"POST",
        url:'YOUR_URL_HERE/nama_controller/nama_fungsi',
        data:{"falkutas_user":falkutas_user,"csrf_token":$("input[name=csrf_token]").val()},
        dataType:'json',
        success: function(result) {
            for(var i=0; i<result.length; i++) {
                res += '<option value="'+result[i]['id_prodi']+'">'+result[i]['nama_prodi']+'</option>';
            }
            $(document).ready(function() {
                 $("#prodi").html(res);
            });
        },
        error: function(result) {
            $(document).ready(function() {
                $("#prodi").html(''); //empty select value
            });
        }
    });
}
</script>

Then, in your function code :

// Inside function ambil_data_jurusan(), harusnya sudah jalan kalau gini
$return = $this->model->get_jurusan($this->input->post('falkutas',TRUE));
if(count($return)>0) {
    echo json_encode($return);
}

In your view, just let select empty like this.

<select id="jurusan" name="jurusan_user">

</select>


问:
Any way to provide Eclipse auto error-discovery feature in Vim/Emacs?
I know that Vim/Emacs offers some enticing mouse-free capabilities for typing out programs. I have tried both and I love these facilities. But when coding Java, especially when using the libraries extensively, the auto-complete and error-highlighting features of Eclipse are too useful to be set aside.
                                                                                Is there a way to combine the best of both worlds? </p>

答: maybe something like this: Eclim ?</p>

Body: maybe something like this: Eclim ?


问:
git shasum and node sha1 do not produce the same hashe
```<code>$ echo -e 'blob 14\0Hello, World!' | shasum
</code>```

produces: 8ab686eafeb1f44702738c8b0f24f2567c36da6d

running this in js/node:

```<code>var sha1 = require('sha1');

const fileContents = "Hello, World!";
const length = fileContents.length + 1;

const blobString = `blob ${length}\0${fileContents}`;

const hash = sha1(blobString);

console.log(blobString);
console.log(hash);
</code>```

produces:

```<code>blob 14Hello, World!
d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6
</code>```

why are the hashes not equal ? (8ab686eafeb1f44702738c8b0f24f2567c36da6d != d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6)

答:
The hashes are not equal because of the difference of a newline character in the input.
echo adds a newline. Use printf instead:

```<code>printf 'blob 14\0Hello, World!' | shasum
# prints: d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6
</code>```

This works too, but not as portable, because the flags of echo are not supported predictably in all systems:

```<code>echo -ne 'blob 14\0Hello, World!' | shasum
</code>```

Body:
$ echo -e 'blob 14\0Hello, World!' | shasum

produces: 8ab686eafeb1f44702738c8b0f24f2567c36da6d

running this in js/node:

var sha1 = require('sha1');

const fileContents = "Hello, World!";
const length = fileContents.length + 1;

const blobString = `blob ${length}\0${fileContents}`;

const hash = sha1(blobString);

console.log(blobString);
console.log(hash);

produces:

blob 14Hello, World!
d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

why are the hashes not equal ? (8ab686eafeb1f44702738c8b0f24f2567c36da6d != d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6)

Body:
The hashes are not equal because of the difference of a newline character in the input.
echo adds a newline. Use printf instead:

printf 'blob 14\0Hello, World!' | shasum
# prints: d4fcfe4d339d4e59d168fdf3c0ad445fa980a7d6

This works too, but not as portable, because the flags of echo are not supported predictably in all systems:

echo -ne 'blob 14\0Hello, World!' | shasum


问:
add a row with button in td dynamically using javascript
I'm trying to add a row into a table with a button on the 3rd cell but it seems not to work</p>

```<code>Script:

   function addRow()
      {
        var table = document.getElementById("myTable"),
          newRow = table.insertRow(table.length),
          cell1 = newRow.insertCell(0),
          cell2 = newRow.insertCell(1),
          cell3 = newRow.insertCell(2),
          name = document.getElementById("form").value,
          amount = document.getElementById("amount").value;
          //this is where I assign a button
          delete1 = <input type='button' id='delete' value="delete">;

        cell1.innerHTML = name;
        cell2.innerHTML = amount;
        cell3.innerHTML = delete1;
      }
</code>```

答:
I wrote an example for your question.

You did serveral things wrong.
First you also need to declare the variables newRow, cell1, cell2, cell3, name, amount, delete1.

Like The Codesee said you have to format the string for the variable delete1 right.
I think with my example you can solve the rest.

addRows();

function addRows(){
    var table = document.getElementById("myTable");

    var row1 = table.insertRow(0);

    var cell1 = row1.insertCell(0);
    var cell2 = row1.insertCell(1);
    var cell3 = row1.insertCell(2);

    cell1.innerHTML = 'CELL 1';
    cell2.innerHTML = '<input type="button" id="delete" value="delete">'
    cell3.innerHTML = 'CELL 2';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myTable{border: 1px solid black;}

tr {background-color: yellow;}

td {border: 1px solid red;}</code>```

```

Body:
I'm trying to add a row into a table with a button on the 3rd cell but it seems not to work

Script:

   function addRow()
      {
        var table = document.getElementById("myTable"),
          newRow = table.insertRow(table.length),
          cell1 = newRow.insertCell(0),
          cell2 = newRow.insertCell(1),
          cell3 = newRow.insertCell(2),
          name = document.getElementById("form").value,
          amount = document.getElementById("amount").value;
          //this is where I assign a button
          delete1 = <input type='button' id='delete' value="delete">;

        cell1.innerHTML = name;
        cell2.innerHTML = amount;
        cell3.innerHTML = delete1;
      }

Body:
I wrote an example for your question.

You did serveral things wrong.
First you also need to declare the variables newRow, cell1, cell2, cell3, name, amount, delete1.

Like The Codesee said you have to format the string for the variable delete1 right.
I think with my example you can solve the rest.

addRows();

function addRows(){
    var table = document.getElementById("myTable");

    var row1 = table.insertRow(0);

    var cell1 = row1.insertCell(0);
    var cell2 = row1.insertCell(1);
    var cell3 = row1.insertCell(2);

    cell1.innerHTML = 'CELL 1';
    cell2.innerHTML = '<input type="button" id="delete" value="delete">'
    cell3.innerHTML = 'CELL 2';
}

#myTable{border: 1px solid black;}

tr {background-color: yellow;}

td {border: 1px solid red;}

<table id="myTable"></table>


问:
The infinite monkey theorem in Java
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:

```<code>    package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
 *
 * @author robi1
 */

public class RandomString {

public static void main(String[] args){
     List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "final.txt");
    String letters = "abcdefghijklmnopqrstuvwxyz ";
    Object[] wrds = readFile("basicWordsInEnglish.txt");

    int x = wrds.length;
    String[] words = new String[x];
    for(int i =0;i<x;i++){
        words[i] = wrds[i].toString();
    }
    char[] let = letters.toCharArray();
    String n ="";

    Random r = new Random();
    char t;

}

public static Object[] readFile(String name){

    ArrayList<String> al = new ArrayList<String>();
    FileInputStream fstream;
    try {
        fstream = new FileInputStream(name);

    DataInputStream in = new DataInputStream(fstream);

    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while((strLine=br.readLine())!=null){
        if(strLine.length()>4)
            al.add(strLine);

    }
    fstream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Object[] array  = al.toArray();

    return array;

}
public static List<String> readDictionaryFrom(String path) {
    try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
}

public RandomString(List<String> text, String path) {
    try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
        for(String word : text) {
            file.write(word+" ");
        }
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}

public static List<String> generateTextFrom(List<String> words) {
       Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
}

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word+" ");
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

}
</code>```

答:
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.

```<code> public void main(String... args) {
        List<String> dictionary = readDictionaryFrom("path to dictionary");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "path to destination file");
    }

    public List<String> readDictionaryFrom(String path) {
        try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word);
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String> generateTextFrom(List<String> words) {
        Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10_000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
    }
</code>```

Title: The infinite monkey theorem in Java

Body:
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:

    package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
 *
 * @author robi1
 */

public class RandomString {

public static void main(String[] args){
     List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "final.txt");
    String letters = "abcdefghijklmnopqrstuvwxyz ";
    Object[] wrds = readFile("basicWordsInEnglish.txt");

    int x = wrds.length;
    String[] words = new String[x];
    for(int i =0;i<x;i++){
        words[i] = wrds[i].toString();
    }
    char[] let = letters.toCharArray();
    String n ="";

    Random r = new Random();
    char t;

}

public static Object[] readFile(String name){

    ArrayList<String> al = new ArrayList<String>();
    FileInputStream fstream;
    try {
        fstream = new FileInputStream(name);

    DataInputStream in = new DataInputStream(fstream);

    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;

    while((strLine=br.readLine())!=null){
        if(strLine.length()>4)
            al.add(strLine);

    }
    fstream.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Object[] array  = al.toArray();

    return array;

}
public static List<String> readDictionaryFrom(String path) {
    try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
}

public RandomString(List<String> text, String path) {
    try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
        for(String word : text) {
            file.write(word+" ");
        }
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}

public static List<String> generateTextFrom(List<String> words) {
       Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
}

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word+" ");
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

}

Body:
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.

 public void main(String... args) {
        List<String> dictionary = readDictionaryFrom("path to dictionary");
        List<String> monkeyText = generateTextFrom(dictionary);
        writeTextToFile(monkeyText, "path to destination file");
    }

    public List<String> readDictionaryFrom(String path) {
        try {
            return Files.readAllLines(new File(path).toPath());
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void writeTextToFile(List<String> text, String path) {
        try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
            for(String word : text) {
                file.write(word);
            }
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String> generateTextFrom(List<String> words) {
        Random generator = new Random();
        List<String> result = new ArrayList<>();
        for(int i = 0; i < 10_000; i++) {
            int random = generator.nextInt(words.size());
            result.add(words.get(random));
        }
        return result;
    }


问:
Scilab - gui - axes auto_clean the graph during adjusting the slider ...?
I'm trying to create a simple GUI in scilab, just for display the graph of function a'sin(x), where a slider is driving the value of "a". I don't seem to find a way to display only the curve corresponding to the current value of "a"... it just add new curves to the existing ones. I hope there is a simple solution for this, as I cannot get further at the moment (I only have some experience with Mathematica). The very simple code I use is:

```<code>// This GUI file is generated by guibuilder version 3.0
//////////
f=figure('figure_position',[400,50],'figure_size',
[656,581],'auto_resize','on','background',[33],'figure_name','Graphic
window number %d');
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0;
handles.slider=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',
[],'Max',[1],'Min',[0],'Position',[0.0359375,0.78125,0.2625,0.09375],
'Relief','default','SliderStep',
[0.01,0.1],'String','slider1','Style','slider','Value',
[0],'VerticalAlignment','middle','Visible','on','Tag','slider',
'Callback','slider_callback(handles)')
handles.graph= newaxes();handles.graph.margins = [ 0 0 0
0];handles.graph.axes_bounds = [0.31875,0.01875,0.6640625,0.925];

//////////
// Callbacks are defined as below. Please do not delete the comments as
it will be used in coming version
//////////

function slider_callback(handles)
//Write your callback for  slider  here
x=0:0.1:10;
a=handles.slider.Value;
plot(x,a*sin(x));
endfunction
</code>```

Thank you in advance for your help.

答:
By default each graphic instruction add its result to the current display
If you want the figure to be erased automatically before a new graphic instruction is displayed you can set the auto-clear property of the axes to "on". An other solution is to erase the previous drawing using the delete function.

If you do not want the graduations to be displayed you can use the xpoly function instead of the plot function

```<code>// This GUI file is generated by guibuilder version 3.0
//////////
f=figure('figure_position',[400,50],'figure_size',...
[656,581],'auto_resize','on','background',[33],'figure_name','Graphic window number %d');
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0;
handles.slider=uicontrol(f,'unit','normalized','BackgroundColor',...
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',...
'FontSize',[12],'FontUnits','points','FontWeight','normal',...
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',...
[],'Max',[1],'Min',[0],'Position',[0.0359375,0.78125,0.2625,0.09375],...
'Relief','default','SliderStep',...
[0.01,0.1],'String','slider1','Style','slider','Value',...
[0],'VerticalAlignment','middle','Visible','on','Tag','slider',...
'Callback','slider_callback(handles)')
handles.graph= newaxes();
handles.graph.margins = [ 0 0 0 0];
handles.graph.axes_bounds = [0.31875,0.01875,0.6640625,0.925];
handles.graph.data_bounds=[0 -1.2;10 1.2];
handles.graph.auto_clear="on";
//////////
// Callbacks are defined as below. Please do not delete the comments as
//it will be used in coming version
//////////

function slider_callback(handles)
//Write your callback for  slider  here
x=0:0.1:10;
a=handles.slider.Value;
drawlater()
//delete(handles.graph.children)
xpoly(x,a*sin(x))
handles.graph.data_bounds=[0 -1.2;10 1.2];
drawnow
//plot(x,a*sin(x));
endfunction
</code>```

Body:
I'm trying to create a simple GUI in scilab, just for display the graph of function a'sin(x), where a slider is driving the value of "a". I don't seem to find a way to display only the curve corresponding to the current value of "a"... it just add new curves to the existing ones. I hope there is a simple solution for this, as I cannot get further at the moment (I only have some experience with Mathematica). The very simple code I use is:

// This GUI file is generated by guibuilder version 3.0
//////////
f=figure('figure_position',[400,50],'figure_size',
[656,581],'auto_resize','on','background',[33],'figure_name','Graphic
window number %d');
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0;
handles.slider=uicontrol(f,'unit','normalized','BackgroundColor',
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',
'FontSize',[12],'FontUnits','points','FontWeight','normal',
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',
[],'Max',[1],'Min',[0],'Position',[0.0359375,0.78125,0.2625,0.09375],
'Relief','default','SliderStep',
[0.01,0.1],'String','slider1','Style','slider','Value',
[0],'VerticalAlignment','middle','Visible','on','Tag','slider',
'Callback','slider_callback(handles)')
handles.graph= newaxes();handles.graph.margins = [ 0 0 0
0];handles.graph.axes_bounds = [0.31875,0.01875,0.6640625,0.925];

//////////
// Callbacks are defined as below. Please do not delete the comments as
it will be used in coming version
//////////

function slider_callback(handles)
//Write your callback for  slider  here
x=0:0.1:10;
a=handles.slider.Value;
plot(x,a*sin(x));
endfunction

Thank you in advance for your help.

Body:
By default each graphic instruction add its result to the current display
If you want the figure to be erased automatically before a new graphic instruction is displayed you can set the auto-clear property of the axes to "on". An other solution is to erase the previous drawing using the delete function.

If you do not want the graduations to be displayed you can use the xpoly function instead of the plot function

// This GUI file is generated by guibuilder version 3.0
//////////
f=figure('figure_position',[400,50],'figure_size',...
[656,581],'auto_resize','on','background',[33],'figure_name','Graphic window number %d');
//////////
delmenu(f.figure_id,gettext('File'))
delmenu(f.figure_id,gettext('?'))
delmenu(f.figure_id,gettext('Tools'))
toolbar(f.figure_id,'off')
handles.dummy = 0;
handles.slider=uicontrol(f,'unit','normalized','BackgroundColor',...
[-1,-1,-1],'Enable','on','FontAngle','normal','FontName','Tahoma',...
'FontSize',[12],'FontUnits','points','FontWeight','normal',...
'ForegroundColor',[-1,-1,-1],'HorizontalAlignment','left','ListboxTop',...
[],'Max',[1],'Min',[0],'Position',[0.0359375,0.78125,0.2625,0.09375],...
'Relief','default','SliderStep',...
[0.01,0.1],'String','slider1','Style','slider','Value',...
[0],'VerticalAlignment','middle','Visible','on','Tag','slider',...
'Callback','slider_callback(handles)')
handles.graph= newaxes();
handles.graph.margins = [ 0 0 0 0];
handles.graph.axes_bounds = [0.31875,0.01875,0.6640625,0.925];
handles.graph.data_bounds=[0 -1.2;10 1.2];
handles.graph.auto_clear="on";
//////////
// Callbacks are defined as below. Please do not delete the comments as
//it will be used in coming version
//////////

function slider_callback(handles)
//Write your callback for  slider  here
x=0:0.1:10;
a=handles.slider.Value;
drawlater()
//delete(handles.graph.children)
xpoly(x,a*sin(x))
handles.graph.data_bounds=[0 -1.2;10 1.2];
drawnow
//plot(x,a*sin(x));
endfunction


问:
Need to track unwanted file downloads
I'm looking to track how many people on the web have made my software program file available for download without my permission.

I've thought of searching for my product name and file size to catch possible thieves.

Do you think a web search API is the best way forward?

EDIT: I plan to use the detection data for survey purposes.

答:
No. This ultimately doesn't help you. What are you going to do? Send them emails tellings them to buy your software? Sounds like a spam filter will get it.

I would suggest in prevention rather than detection. A registration or activation process is pretty popular and reasonably successful, though if you have an amazing app it won't stop the really bad people from hacking it, however it will make it much more difficult.

Title: Need to track unwanted file downloads


问:
PHP posting error
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>```
</div>
</div>
</p>

<p>PHP file is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?></code>```

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?

答:
Looks like there ; missing

i have changed you code to bellow, it should run now

```<code><?php
if (isset($_POST["submit"]))
{
  $title = $_POST['title'];
  $desc = $_POST['desc'];
}
?>
</code>```

try this

Title: PHP posting error

Body:
I keep getting a Cannot POST /app/newpost/newpost.php error when i try to post a HTML form and retrieve the data from another HTML page

HTML for the form is:

    Create a new forum post

<form action="newpost.php" method="POST" style="text-align:center">

Title: <input type="text" name="title" style="font-size:24px; font-family:verdana;">

Description: <input type="text" name="desc" style="font-size:24px; font-family:verdana;">

<input type="submit" action="window.location.href='/app/forum/forum.component.html'" style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: left; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">
</form>

PHP file is

<?php
if (isset($_POST["submit"]))
{$title = $_POST['title'];
$desc = $_POST['desc']
}
?>

im still very new to PHP someone pls help!
And how to retrieve the posted data on another html page?

Body:
Looks like there ; missing

i have changed you code to bellow, it should run now

<?php
if (isset($_POST["submit"]))
{
  $title = $_POST['title'];
  $desc = $_POST['desc'];
}
?>

try this


问:
How to Copy(Automatically Insert) a Value From a Input form to a JS File
I am getting some value through a form . But unable to automatically insert that value in a separate js file.

Details :

i am getting value from form as $id and $marks.
i have a js file named as raw_data.js
JS File Content : window.raw_data = " (6,9) ";
Now i want that any value that i get from form should cancanate in that JS file in ($id,$marks) format.

答:
LocalStorage is your solution:

```<code>window.localStorage.setItem('some title', $id);
window.localStorage.setItem('some title2', $marks);
</code>```

And get it on raw_data.js:

```<code>var $id = window.localStorage.getItem('some title');
var $marks = window.localStorage.getItem('some title2');

window.raw_data = "($id, $marks)";
</code>```

Edit: in your code, should be like this:

```<code><?php
if($_POST["marks"] && $_POST["id"]) {
    $marks = $_POST["marks"];
    $id = "ID_" . $_POST["id"];
?>
<script>
    window.localStorage.setItem('some title', $id);
    window.localStorage.setItem('some title2', $marks);
</script>
<?php
}
?>
</code>```

Body:
LocalStorage is your solution:

window.localStorage.setItem('some title', $id);
window.localStorage.setItem('some title2', $marks);

And get it on raw_data.js:

var $id = window.localStorage.getItem('some title');
var $marks = window.localStorage.getItem('some title2');

window.raw_data = "($id, $marks)";

Edit: in your code, should be like this:

<?php
if($_POST["marks"] && $_POST["id"]) {
    $marks = $_POST["marks"];
    $id = "ID_" . $_POST["id"];
?>
<script>
    window.localStorage.setItem('some title', $id);
    window.localStorage.setItem('some title2', $marks);
</script>
<?php
}
?>


问:
Why doesn't my jQuery Mobile code work?
I'm not sure how to make any jQuery mobile event like tap or touchstart work on my mobile device. When I run it on desktop, it all works fine. Using PhoneGap to build the apk.

The code should be working on mobile according to the jQuery mobile docs. Tried to debug it on mobile as well, doesn't seem the jquery even loads...

* {
  margin: 0;
  padding: 0
}

body {
  background-color: red;
}

h1 {
  position: absolute;
  right: 30px;
  padding: 30px;
  color: white;
  text-shadow: none;
}

#hello {
  z-index: 3;
  background-color: #222222;
}

#hello > div {
  height: 200px;
  width: 200px;
  background-color: green;
}

.ui-page { background:transparent; }

.ui-input-text {
  border: none;
}

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" type="text/css" href="jquery-mobile/jquery.mobile-1.4.5.min.css" />
    <script  type="text/javascript" src="jquery-mobile/jquery-3.2.1.min.js">
    <script type="text/javascript" src="jquery-mobile/jquery.mobile-1.4.5.min.js"></script>
   </script>

    <title>Hello World</title>
</head>

<body>
    <div class="app" data-role='page'>
        <h1>PhoneGap</h1>
        <div id="deviceready" class="blink">
            <p class="event listening">Connecting to Device</p>
            <p class="event received">Device is Ready</p>
        </div>
    </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>

    <script type="text/javascript">
      $(document).ready(function() {
        $('h1').bind("tap", function() {
          $(this).css({color: 'red'});

        });
      });

      /* works
      $(document).ready(function() {
        $('h1').on("click", function() {
          $(this).css({color: 'red'});

        });
      });
    </script>
</body>

</html></code>```

答:
in Cordova or in PhoneGap applications use jQuery that you will have in www directory of app that you are publishing, and then include it like this for example:

```<code><script type="text/javascript" src="js/jquery.min.js"></script>
</code>```

and not from cdn, or remote address like: https://code.jquery.com

Title: Why doesn't my jQuery Mobile code work?

Body:
I'm not sure how to make any jQuery mobile event like tap or touchstart work on my mobile device. When I run it on desktop, it all works fine. Using PhoneGap to build the apk.

The code should be working on mobile according to the jQuery mobile docs. Tried to debug it on mobile as well, doesn't seem the jquery even loads...

* {
  margin: 0;
  padding: 0
}

body {
  background-color: red;
}

h1 {
  position: absolute;
  right: 30px;
  padding: 30px;
  color: white;
  text-shadow: none;
}

#hello {
  z-index: 3;
  background-color: #222222;
}

#hello > div {
  height: 200px;
  width: 200px;
  background-color: green;
}

.ui-page { background:transparent; }

.ui-input-text {
  border: none;
}

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" type="text/css" href="jquery-mobile/jquery.mobile-1.4.5.min.css" />

   </script>

    <title>Hello World</title>

PhoneGap

Connecting to Device

Device is Ready

Body:
in Cordova or in PhoneGap applications use jQuery that you will have in www directory of app that you are publishing, and then include it like this for example:

<script type="text/javascript" src="js/jquery.min.js"></script>

and not from cdn, or remote address like: https://code.jquery.com


问:
How to push an object in an array in Mongoose (error)
I am making a route in a Node server using Mongoose and Mongo which stores a comment in the comments array in blogPost (I will post model code). When I try to execute the query it gives me the following error:
Postman error

These are my models and the route:

blogPost model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'comment'
  }]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;
</code>```

comment model

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

const Comment = mongoose.model('comment', CommentSchema);

module.exports = Comment;
</code>```

Route

```<code>routes.put('/blogPosts/:id/comment', function(req, res) {
    const blogPostId = req.param('id');
    const commentProps = req.body;

    BlogPost.findById(req.params.id)
        .then((blogPost) => {
          blogPost.comments.push(commentProps);
          blogPost.save();
        })
    .catch((error) => res.status(400).json(error))
});
</code>```

Any help is greatly appreciated.

答:
The problem is that you are pushing an entire comment object into an array that's only supposed to have objectids.

dnickless answer uses a solution with referencing, meaning you have a collection for blogposts and a collection for comments. The blogpost documents will refer to their comments with objectids.

You can also change the blogpost model to use embedding rather than referencing, meaning the comments will be a part of the blogpost documents as subdocuments. There are a couple of nice discussions regarding what's better here and here. The short answer is that it depends on the use case. You can choose what you want to use yourself.

Here's how embedding is done:

Blogpost model:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentSchema = require('./comment.model');

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [commentSchema]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;
</code>```

Notice how the comments array uses the comment schema rather than being an array of object ids. The comment model has to be changed slightly:

Comment model:

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

module.exports = CommentSchema;
</code>```

const Comment = mongoose.model('comment', CommentSchema); was removed. The schema should no longer be registered and comments will not have their own collection. The schema is now being exported rather than the registered model.

The original code for adding comments should work after that. Comments will be a part of the blogpost document, not be in their own collection.

Body:
I am making a route in a Node server using Mongoose and Mongo which stores a comment in the comments array in blogPost (I will post model code). When I try to execute the query it gives me the following error:
Postman error

These are my models and the route:

blogPost model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [{
    type: Schema.Types.ObjectId,
    ref: 'comment'
  }]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;

comment model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

const Comment = mongoose.model('comment', CommentSchema);

module.exports = Comment;

Route

routes.put('/blogPosts/:id/comment', function(req, res) {
    const blogPostId = req.param('id');
    const commentProps = req.body;

    BlogPost.findById(req.params.id)
        .then((blogPost) => {
          blogPost.comments.push(commentProps);
          blogPost.save();
        })
    .catch((error) => res.status(400).json(error))
});

Any help is greatly appreciated.

Body:
The problem is that you are pushing an entire comment object into an array that's only supposed to have objectids.

dnickless answer uses a solution with referencing, meaning you have a collection for blogposts and a collection for comments. The blogpost documents will refer to their comments with objectids.

You can also change the blogpost model to use embedding rather than referencing, meaning the comments will be a part of the blogpost documents as subdocuments. There are a couple of nice discussions regarding what's better here and here. The short answer is that it depends on the use case. You can choose what you want to use yourself.

Here's how embedding is done:

Blogpost model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentSchema = require('./comment.model');

const BlogPostSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  rating: Number,
  title: String,
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  board: {type: Schema.Types.ObjectId, ref: 'board'},
  comments: [commentSchema]
});

const BlogPost = mongoose.model('blogPost', BlogPostSchema);

module.exports = BlogPost;

Notice how the comments array uses the comment schema rather than being an array of object ids. The comment model has to be changed slightly:

Comment model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  content: {
    type: String,
    validate: {
      validator: (content) => content.length > 5,
      message: 'Content must contain at least 6 characters.'
    },
    required: [true, 'Content must be filled in.']
  },
  user: { type: Schema.Types.ObjectId, ref: 'user' },
  rating: Number

  // board: Board
});

// UserSchema.virtual('postCount').get(function(){
//   return this.posts.length;
// });

module.exports = CommentSchema;

const Comment = mongoose.model('comment', CommentSchema); was removed. The schema should no longer be registered and comments will not have their own collection. The schema is now being exported rather than the registered model.

The original code for adding comments should work after that. Comments will be a part of the blogpost document, not be in their own collection.


问:
Using Stacks In C++ for infix and postfix expressions
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

```<code>#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}
</code>```

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

答:
The problem is here:

```<code>bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');
</code>```

I'm guessing this is intended to define a precedence function, but that's not what it's doing. The first line declares that such a function exists (and its arguments have nothing to do with the variables declared in the previous lines), and the second causes the whole program to terminate. If you want a function like this, you must define it outside main.

A slightly less dramatic bug is here:

```<code>if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)
</code>```

First, this part

```<code>input == '*'||'/'||'+'||'-'
</code>```

is interpreted as

```<code>(input == '*') || ('/') || ('+') || ('-')
</code>```

The last three terms are true, the first is irrelevant. And I'm not even sure what s.top() does if s is empty.

This should be enough to go on. I suggest you start by building and testing routines that can, e.g., identify the operators and evaluate their precedence, before you try putting everything together in one program.

Body:
I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty())
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty())
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.

Body:
The problem is here:

bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');

I'm guessing this is intended to define a precedence function, but that's not what it's doing. The first line declares that such a function exists (and its arguments have nothing to do with the variables declared in the previous lines), and the second causes the whole program to terminate. If you want a function like this, you must define it outside main.

A slightly less dramatic bug is here:

if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)

First, this part

input == '*'||'/'||'+'||'-'

is interpreted as

(input == '*') || ('/') || ('+') || ('-')

The last three terms are true, the first is irrelevant. And I'm not even sure what s.top() does if s is empty.

This should be enough to go on. I suggest you start by building and testing routines that can, e.g., identify the operators and evaluate their precedence, before you try putting everything together in one program.